blob: 75a58046faaadb8ea8abce9d317a8c8ce00d0d40 [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;
Mathew Inwoodaf972c82018-08-20 14:13:20 +010021import android.annotation.UnsupportedAppUsage;
Dianne Hackborn61659e52014-07-09 16:13:01 -070022import android.app.ActivityManager;
Adam Lesinski33dac552015-03-09 15:24:48 -070023import android.bluetooth.BluetoothActivityEnergyInfo;
Adam Lesinski50e47602015-12-04 17:04:54 -080024import android.bluetooth.UidTraffic;
Mike Mafbc01fc2018-04-02 10:28:28 -070025import android.content.BroadcastReceiver;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080026import android.content.ContentResolver;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080027import android.content.Context;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070028import android.content.Intent;
Mike Mafbc01fc2018-04-02 10:28:28 -070029import android.content.IntentFilter;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080030import android.database.ContentObserver;
Mike Mafbc01fc2018-04-02 10:28:28 -070031import android.hardware.usb.UsbManager;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070032import android.net.ConnectivityManager;
Chenbo Fenge62e2872019-01-11 15:50:17 -080033import android.net.INetworkStatsService;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070034import android.net.NetworkStats;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080035import android.net.Uri;
Adam Lesinski33dac552015-03-09 15:24:48 -070036import android.net.wifi.WifiActivityEnergyInfo;
Dianne Hackborn3251b902014-06-20 14:40:53 -070037import android.net.wifi.WifiManager;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070038import android.os.BatteryManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.os.BatteryStats;
Dianne Hackborncd0e3352014-08-07 17:08:09 -070040import android.os.Build;
Dianne Hackborn0d903a82010-09-07 23:51:03 -070041import android.os.Handler;
Adam Lesinskie1f480d2017-02-15 18:51:23 -080042import android.os.IBatteryPropertiesRegistrar;
Jeff Brown6f357d32014-01-15 20:40:55 -080043import android.os.Looper;
Dianne Hackborn0d903a82010-09-07 23:51:03 -070044import android.os.Message;
Bookatz1a1b0462018-01-12 11:47:03 -080045import android.os.OsProtoEnums;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.os.Parcel;
47import android.os.ParcelFormatException;
48import android.os.Parcelable;
Bookatz1a1b0462018-01-12 11:47:03 -080049import android.os.PowerManager;
Evan Millarc64edde2009-04-18 12:26:32 -070050import android.os.Process;
Adam Lesinskie1f480d2017-02-15 18:51:23 -080051import android.os.RemoteException;
52import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.os.SystemClock;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070054import android.os.UserHandle;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070055import android.os.WorkSource;
Narayan Kamath81822022017-12-08 11:56:01 +000056import android.os.WorkSource.WorkChain;
Mike Ma234d1822018-03-13 18:53:21 -070057import android.os.connectivity.CellularBatteryStats;
58import android.os.connectivity.GpsBatteryStats;
59import android.os.connectivity.WifiBatteryStats;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080060import android.provider.Settings;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070061import android.telephony.DataConnectionRealTimeInfo;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080062import android.telephony.ModemActivityInfo;
Chen Xu7322e4a2019-09-07 15:51:22 -070063import android.telephony.ModemActivityInfo.TransmitPower;
Amith Yamasanif37447b2009-10-08 18:28:01 -070064import android.telephony.ServiceState;
Wink Savillee9b06d72009-05-18 21:47:50 -070065import android.telephony.SignalStrength;
Dianne Hackborn627bba72009-03-24 22:32:56 -070066import android.telephony.TelephonyManager;
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -070067import android.text.TextUtils;
Dianne Hackborn61659e52014-07-09 16:13:01 -070068import android.util.ArrayMap;
Al Sutton7407e2c2019-09-06 09:17:01 +010069import android.util.AtomicFile;
Sudheer Shankab2f83c12017-11-13 19:25:01 -080070import android.util.IntArray;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080071import android.util.KeyValueListParser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.util.Log;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070073import android.util.LogWriter;
James Carr3a226052016-07-01 14:49:52 -070074import android.util.LongSparseArray;
75import android.util.LongSparseLongArray;
Dianne Hackbornd953c532014-08-16 18:17:38 -070076import android.util.MutableInt;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070077import android.util.Pools;
Dianne Hackborn1d442e02009-04-20 18:14:05 -070078import android.util.PrintWriterPrinter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079import android.util.Printer;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070080import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.util.SparseArray;
Dianne Hackborn099bc622014-01-22 13:39:16 -080082import android.util.SparseIntArray;
Adam Lesinskie08af192015-03-25 16:42:59 -070083import android.util.SparseLongArray;
Bookatzc1a050a2017-10-10 15:49:28 -070084import android.util.StatsLog;
Dianne Hackbornae384452011-06-28 12:33:48 -070085import android.util.TimeUtils;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080086import android.util.Xml;
Jeff Browne95c3cd2014-05-02 16:59:26 -070087import android.view.Display;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088
Adam Lesinski14ae39a2017-05-26 11:50:40 -070089import com.android.internal.annotations.GuardedBy;
Adam Lesinski98f0d462016-04-19 16:46:20 -070090import com.android.internal.annotations.VisibleForTesting;
Siddharth Ray78ccaf52017-12-23 16:16:21 -080091import com.android.internal.location.gnssmetrics.GnssMetrics;
Mike Ma7ab7fcd2019-01-16 15:00:40 -080092import com.android.internal.os.KernelCpuUidTimeReader.KernelCpuUidActiveTimeReader;
93import com.android.internal.os.KernelCpuUidTimeReader.KernelCpuUidClusterTimeReader;
94import com.android.internal.os.KernelCpuUidTimeReader.KernelCpuUidFreqTimeReader;
95import com.android.internal.os.KernelCpuUidTimeReader.KernelCpuUidUserSysTimeReader;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080096import com.android.internal.util.ArrayUtils;
Dianne Hackborn8c841092013-06-24 13:46:13 -070097import com.android.internal.util.FastPrintWriter;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080098import com.android.internal.util.FastXmlSerializer;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080099import com.android.internal.util.XmlUtils;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700100
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700101import libcore.util.EmptyArray;
Mike Ma234d1822018-03-13 18:53:21 -0700102
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800103import org.xmlpull.v1.XmlPullParser;
104import org.xmlpull.v1.XmlPullParserException;
105import org.xmlpull.v1.XmlSerializer;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700106
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800107import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108import java.io.File;
109import java.io.FileInputStream;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800110import java.io.FileNotFoundException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111import java.io.FileOutputStream;
112import java.io.IOException;
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700113import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100114import java.nio.charset.StandardCharsets;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115import java.util.ArrayList;
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700116import java.util.Arrays;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800117import java.util.Calendar;
Hui Yu8e88e952018-07-23 17:59:59 -0700118import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119import java.util.HashMap;
Hui Yu8e88e952018-07-23 17:59:59 -0700120import java.util.HashSet;
Evan Millarc64edde2009-04-18 12:26:32 -0700121import java.util.Iterator;
Mike Ma234d1822018-03-13 18:53:21 -0700122import java.util.LinkedList;
123import java.util.List;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124import java.util.Map;
Mike Ma234d1822018-03-13 18:53:21 -0700125import java.util.Queue;
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700126import java.util.concurrent.Future;
Christopher Tate4cee7252010-03-19 14:50:40 -0700127import java.util.concurrent.atomic.AtomicInteger;
Dianne Hackbornce2ef762010-09-20 11:39:14 -0700128import java.util.concurrent.locks.ReentrantLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129
130/**
131 * All information we are collecting about things that can happen that impact
132 * battery life. All times are represented in microseconds except where indicated
133 * otherwise.
134 */
Joe Onoratoabded112016-02-08 16:49:39 -0800135public class BatteryStatsImpl extends BatteryStats {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136 private static final String TAG = "BatteryStatsImpl";
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800137 private static final boolean DEBUG = false;
Adam Lesinskia7c90c82015-06-18 14:52:24 -0700138 public static final boolean DEBUG_ENERGY = false;
Adam Lesinski50e47602015-12-04 17:04:54 -0800139 private static final boolean DEBUG_ENERGY_CPU = DEBUG_ENERGY;
James Carr3a226052016-07-01 14:49:52 -0700140 private static final boolean DEBUG_MEMORY = false;
Dianne Hackborn32907cf2010-06-10 17:50:20 -0700141 private static final boolean DEBUG_HISTORY = false;
Dianne Hackborne8c88e62011-08-17 19:09:09 -0700142 private static final boolean USE_OLD_HISTORY = false; // for debugging.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700143
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700144 // TODO: remove "tcp" from network methods, since we measure total stats.
145
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800146 // In-memory Parcel magic number, used to detect attempts to unmarshall bad data
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700147 private static final int MAGIC = 0xBA757475; // 'BATSTATS'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148
149 // Current on-disk Parcel version
Mike Ma99e57c32018-03-15 14:40:37 -0700150 static final int VERSION = 186 + (USE_OLD_HISTORY ? 1000 : 0);
Dianne Hackbornf47d8f22010-10-08 10:46:55 -0700151
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800152 // The maximum number of names wakelocks we will keep track of
153 // per uid; once the limit is reached, we batch the remaining wakelocks
154 // in to one common name.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100155 private static final int MAX_WAKELOCKS_PER_UID;
156
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100157 static {
158 if (ActivityManager.isLowRamDeviceStatic()) {
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100159 MAX_WAKELOCKS_PER_UID = 40;
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100160 } else {
Makoto Onuki44d64602018-01-18 08:44:28 -0800161 MAX_WAKELOCKS_PER_UID = 200;
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100162 }
163 }
Dianne Hackbornc24ab862011-10-18 15:55:03 -0700164
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800165 // Number of transmit power states the Wifi controller can be in.
166 private static final int NUM_WIFI_TX_LEVELS = 1;
167
168 // Number of transmit power states the Bluetooth controller can be in.
169 private static final int NUM_BT_TX_LEVELS = 1;
170
Sudheer Shanka38383232017-07-25 09:55:03 -0700171 /**
172 * Holding a wakelock costs more than just using the cpu.
173 * Currently, we assign only half the cpu time to an app that is running but
174 * not holding a wakelock. The apps holding wakelocks get the rest of the blame.
175 * If no app is holding a wakelock, then the distribution is normal.
176 */
177 @VisibleForTesting
178 public static final int WAKE_LOCK_WEIGHT = 50;
179
Joe Onoratoabded112016-02-08 16:49:39 -0800180 protected Clocks mClocks;
181
Hui Yu0ed84f12018-06-20 19:07:56 -0700182 private final AtomicFile mStatsFile;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700183 public final AtomicFile mCheckinFile;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800184 public final AtomicFile mDailyFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185
Sudheer Shankac57729a2018-02-09 15:44:42 -0800186 static final int MSG_REPORT_CPU_UPDATE_NEEDED = 1;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700187 static final int MSG_REPORT_POWER_CHANGE = 2;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700188 static final int MSG_REPORT_CHARGING = 3;
Fyodor Kupolov8aa51242018-04-23 12:44:51 -0700189 static final int MSG_REPORT_RESET_STATS = 4;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700190 static final long DELAY_UPDATE_WAKELOCKS = 5*1000;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700191
Blake Kragtencb308d92019-01-28 10:54:13 -0800192 private static final double MILLISECONDS_IN_HOUR = 3600 * 1000;
Hui Yu5104da02019-06-03 13:58:20 -0700193 private static final long MILLISECONDS_IN_YEAR = 365 * 24 * 3600 * 1000L;
Blake Kragtencb308d92019-01-28 10:54:13 -0800194
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700195 private final KernelWakelockReader mKernelWakelockReader = new KernelWakelockReader();
196 private final KernelWakelockStats mTmpWakelockStats = new KernelWakelockStats();
197
Sudheer Shanka38383232017-07-25 09:55:03 -0700198 @VisibleForTesting
Mike Ma7ab7fcd2019-01-16 15:00:40 -0800199 protected KernelCpuUidUserSysTimeReader mCpuUidUserSysTimeReader =
200 new KernelCpuUidUserSysTimeReader(true);
Sudheer Shanka38383232017-07-25 09:55:03 -0700201 @VisibleForTesting
202 protected KernelCpuSpeedReader[] mKernelCpuSpeedReaders;
203 @VisibleForTesting
Mike Ma7ab7fcd2019-01-16 15:00:40 -0800204 protected KernelCpuUidFreqTimeReader mCpuUidFreqTimeReader =
205 new KernelCpuUidFreqTimeReader(true);
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800206 @VisibleForTesting
Mike Ma7ab7fcd2019-01-16 15:00:40 -0800207 protected KernelCpuUidActiveTimeReader mCpuUidActiveTimeReader =
208 new KernelCpuUidActiveTimeReader(true);
Mike Ma3d422c32017-10-25 11:08:57 -0700209 @VisibleForTesting
Mike Ma7ab7fcd2019-01-16 15:00:40 -0800210 protected KernelCpuUidClusterTimeReader mCpuUidClusterTimeReader =
211 new KernelCpuUidClusterTimeReader(true);
Mike Ma3d422c32017-10-25 11:08:57 -0700212 @VisibleForTesting
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800213 protected KernelSingleUidTimeReader mKernelSingleUidTimeReader;
Adam Lesinski06af1fa2015-05-05 17:35:35 -0700214
James Carr3a226052016-07-01 14:49:52 -0700215 private final KernelMemoryBandwidthStats mKernelMemoryBandwidthStats
216 = new KernelMemoryBandwidthStats();
217 private final LongSparseArray<SamplingTimer> mKernelMemoryStats = new LongSparseArray<>();
218 public LongSparseArray<SamplingTimer> getKernelMemoryStats() {
219 return mKernelMemoryStats;
220 }
221
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800222 @GuardedBy("this")
223 public boolean mPerProcStateCpuTimesAvailable = true;
224
225 /**
Sudheer Shanka020239d2018-07-16 18:00:46 -0700226 * When per process state cpu times tracking is off, cpu times in KernelSingleUidTimeReader are
227 * not updated. So, when the setting is turned on later, we would end up with huge cpu time
228 * deltas. This flag tracks the case where tracking is turned on from off so that we won't
229 * end up attributing the huge deltas to wrong buckets.
230 */
231 @GuardedBy("this")
232 private boolean mIsPerProcessStateCpuDataStale;
233
234 /**
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800235 * Uids for which per-procstate cpu times need to be updated.
236 *
237 * Contains uid -> procState mappings.
238 */
239 @GuardedBy("this")
240 @VisibleForTesting
241 protected final SparseIntArray mPendingUids = new SparseIntArray();
242
Sudheer Shankac20379e2018-02-15 00:06:21 -0800243 @GuardedBy("this")
Mike Ma234d1822018-03-13 18:53:21 -0700244 private long mNumSingleUidCpuTimeReads;
Sudheer Shankac20379e2018-02-15 00:06:21 -0800245 @GuardedBy("this")
Mike Ma234d1822018-03-13 18:53:21 -0700246 private long mNumBatchedSingleUidCpuTimeReads;
Sudheer Shankac20379e2018-02-15 00:06:21 -0800247 @GuardedBy("this")
248 private long mCpuTimeReadsTrackingStartTime = SystemClock.uptimeMillis();
Mike Ma234d1822018-03-13 18:53:21 -0700249 @GuardedBy("this")
250 private int mNumUidsRemoved;
251 @GuardedBy("this")
252 private int mNumAllUidCpuTimeReads;
Sudheer Shankac20379e2018-02-15 00:06:21 -0800253
Bookatz0b8a0502017-09-13 11:51:52 -0700254 /** Container for Resource Power Manager stats. Updated by updateRpmStatsLocked. */
Bookatz50df7112017-08-04 14:53:26 -0700255 private final RpmStats mTmpRpmStats = new RpmStats();
Bookatz0b8a0502017-09-13 11:51:52 -0700256 /** The soonest the RPM stats can be updated after it was last updated. */
257 private static final long RPM_STATS_UPDATE_FREQ_MS = 1000;
258 /** Last time that RPM stats were updated by updateRpmStatsLocked. */
259 private long mLastRpmStatsUpdateTimeMs = -RPM_STATS_UPDATE_FREQ_MS;
Blake Kragtencb308d92019-01-28 10:54:13 -0800260
261 /** Container for Rail Energy Data stats. */
262 private final RailStats mTmpRailStats = new RailStats();
Mike Ma234d1822018-03-13 18:53:21 -0700263 /**
Mike Ma7ab7fcd2019-01-16 15:00:40 -0800264 * Use a queue to delay removing UIDs from {@link KernelCpuUidUserSysTimeReader},
265 * {@link KernelCpuUidActiveTimeReader}, {@link KernelCpuUidClusterTimeReader},
266 * {@link KernelCpuUidFreqTimeReader} and from the Kernel.
Mike Ma234d1822018-03-13 18:53:21 -0700267 *
268 * Isolated and invalid UID info must be removed to conserve memory. However, STATSD and
269 * Batterystats both need to access UID cpu time. To resolve this race condition, only
270 * Batterystats shall remove UIDs, and a delay {@link Constants#UID_REMOVE_DELAY_MS} is
271 * implemented so that STATSD can capture those UID times before they are deleted.
272 */
273 @GuardedBy("this")
274 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
275 protected Queue<UidToRemove> mPendingRemovedUids = new LinkedList<>();
276
277 @VisibleForTesting
278 public final class UidToRemove {
279 int startUid;
280 int endUid;
281 long timeAddedInQueue;
282
283 /** Remove just one UID */
284 public UidToRemove(int uid, long timestamp) {
285 this(uid, uid, timestamp);
286 }
287
288 /** Remove a range of UIDs, startUid must be smaller than endUid. */
289 public UidToRemove(int startUid, int endUid, long timestamp) {
290 this.startUid = startUid;
291 this.endUid = endUid;
292 timeAddedInQueue = timestamp;
293 }
294
295 void remove() {
296 if (startUid == endUid) {
Mike Ma7ab7fcd2019-01-16 15:00:40 -0800297 mCpuUidUserSysTimeReader.removeUid(startUid);
298 mCpuUidFreqTimeReader.removeUid(startUid);
Mike Ma234d1822018-03-13 18:53:21 -0700299 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
Mike Ma7ab7fcd2019-01-16 15:00:40 -0800300 mCpuUidActiveTimeReader.removeUid(startUid);
301 mCpuUidClusterTimeReader.removeUid(startUid);
Mike Ma234d1822018-03-13 18:53:21 -0700302 }
303 if (mKernelSingleUidTimeReader != null) {
304 mKernelSingleUidTimeReader.removeUid(startUid);
305 }
306 mNumUidsRemoved++;
307 } else if (startUid < endUid) {
Mike Ma7ab7fcd2019-01-16 15:00:40 -0800308 mCpuUidFreqTimeReader.removeUidsInRange(startUid, endUid);
309 mCpuUidUserSysTimeReader.removeUidsInRange(startUid, endUid);
Mike Ma234d1822018-03-13 18:53:21 -0700310 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
Mike Ma7ab7fcd2019-01-16 15:00:40 -0800311 mCpuUidActiveTimeReader.removeUidsInRange(startUid, endUid);
312 mCpuUidClusterTimeReader.removeUidsInRange(startUid, endUid);
Mike Ma234d1822018-03-13 18:53:21 -0700313 }
314 if (mKernelSingleUidTimeReader != null) {
315 mKernelSingleUidTimeReader.removeUidsInRange(startUid, endUid);
316 }
317 // Treat as one. We don't know how many uids there are in between.
318 mNumUidsRemoved++;
319 } else {
320 Slog.w(TAG, "End UID " + endUid + " is smaller than start UID " + startUid);
321 }
322 }
323 }
Bookatz50df7112017-08-04 14:53:26 -0700324
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700325 public interface BatteryCallback {
326 public void batteryNeedsCpuUpdate();
327 public void batteryPowerChanged(boolean onBattery);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700328 public void batterySendBroadcast(Intent intent);
Fyodor Kupolov8aa51242018-04-23 12:44:51 -0700329 public void batteryStatsReset();
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700330 }
331
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700332 public interface PlatformIdleStateCallback {
Bookatz50df7112017-08-04 14:53:26 -0700333 public void fillLowPowerStats(RpmStats rpmStats);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700334 public String getPlatformLowPowerStats();
Ahmed ElArabawyd8b44112017-05-23 21:25:02 +0000335 public String getSubsystemLowPowerStats();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700336 }
337
Blake Kragtencb308d92019-01-28 10:54:13 -0800338 /** interface to update rail information for power monitor */
339 public interface RailEnergyDataCallback {
340 /** Function to fill the map for the rail data stats
341 * Used for power monitoring feature
342 * @param railStats
343 */
344 void fillRailDataStats(RailStats railStats);
345 }
346
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700347 public static abstract class UserInfoProvider {
348 private int[] userIds;
349 protected abstract @Nullable int[] getUserIds();
Sudheer Shanka38383232017-07-25 09:55:03 -0700350 @VisibleForTesting
351 public final void refreshUserIds() {
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700352 userIds = getUserIds();
353 }
Sudheer Shanka38383232017-07-25 09:55:03 -0700354 @VisibleForTesting
355 public boolean exists(int userId) {
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700356 return userIds != null ? ArrayUtils.contains(userIds, userId) : true;
357 }
358 }
359
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700360 private final PlatformIdleStateCallback mPlatformIdleStateCallback;
361
Zhi An Ng11b63622018-12-27 16:43:34 +0800362 private final Runnable mDeferSetCharging = new Runnable() {
363 @Override
364 public void run() {
365 synchronized (BatteryStatsImpl.this) {
366 if (mOnBattery) {
367 // if the device gets unplugged in the time between this runnable being
368 // executed and the lock being taken, we don't want to set charging state
369 return;
370 }
371 boolean changed = setChargingLocked(true);
372 if (changed) {
373 final long uptime = mClocks.uptimeMillis();
374 final long elapsedRealtime = mClocks.elapsedRealtime();
375 addHistoryRecordLocked(elapsedRealtime, uptime);
376 }
377 }
378 }
379 };
380
Blake Kragtencb308d92019-01-28 10:54:13 -0800381 public final RailEnergyDataCallback mRailEnergyDataCallback;
382
Olivier Gaillardc2d02b522018-09-20 13:53:18 +0100383 /**
384 * This handler is running on {@link BackgroundThread}.
385 */
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700386 final class MyHandler extends Handler {
Jeff Brown6f357d32014-01-15 20:40:55 -0800387 public MyHandler(Looper looper) {
388 super(looper, null, true);
389 }
390
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700391 @Override
392 public void handleMessage(Message msg) {
393 BatteryCallback cb = mCallback;
394 switch (msg.what) {
Sudheer Shankac57729a2018-02-09 15:44:42 -0800395 case MSG_REPORT_CPU_UPDATE_NEEDED:
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700396 if (cb != null) {
397 cb.batteryNeedsCpuUpdate();
398 }
399 break;
400 case MSG_REPORT_POWER_CHANGE:
401 if (cb != null) {
402 cb.batteryPowerChanged(msg.arg1 != 0);
403 }
404 break;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700405 case MSG_REPORT_CHARGING:
406 if (cb != null) {
407 final String action;
408 synchronized (BatteryStatsImpl.this) {
409 action = mCharging ? BatteryManager.ACTION_CHARGING
410 : BatteryManager.ACTION_DISCHARGING;
411 }
412 Intent intent = new Intent(action);
413 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
414 cb.batterySendBroadcast(intent);
415 }
416 break;
Fyodor Kupolov8aa51242018-04-23 12:44:51 -0700417 case MSG_REPORT_RESET_STATS:
418 if (cb != null) {
419 cb.batteryStatsReset();
420 }
421 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700422 }
423 }
424
Sudheer Shankac57729a2018-02-09 15:44:42 -0800425 public void postBatteryNeedsCpuUpdateMsg() {
426 mHandler.sendEmptyMessage(MSG_REPORT_CPU_UPDATE_NEEDED);
427 }
428
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800429 /**
430 * Update per-freq cpu times for all the uids in {@link #mPendingUids}.
431 */
Sudheer Shankae544d162017-12-28 17:06:20 -0800432 public void updateProcStateCpuTimes(boolean onBattery, boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800433 final SparseIntArray uidStates;
434 synchronized (BatteryStatsImpl.this) {
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800435 if (!mConstants.TRACK_CPU_TIMES_BY_PROC_STATE) {
436 return;
437 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800438 if(!initKernelSingleUidTimeReaderLocked()) {
439 return;
440 }
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800441 // If the KernelSingleUidTimeReader has stale cpu times, then we shouldn't try to
442 // compute deltas since it might result in mis-attributing cpu times to wrong states.
Sudheer Shanka020239d2018-07-16 18:00:46 -0700443 if (mIsPerProcessStateCpuDataStale) {
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800444 mPendingUids.clear();
445 return;
446 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800447
448 if (mPendingUids.size() == 0) {
449 return;
450 }
451 uidStates = mPendingUids.clone();
452 mPendingUids.clear();
453 }
454 for (int i = uidStates.size() - 1; i >= 0; --i) {
455 final int uid = uidStates.keyAt(i);
456 final int procState = uidStates.valueAt(i);
457 final int[] isolatedUids;
458 final Uid u;
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800459 synchronized (BatteryStatsImpl.this) {
460 // It's possible that uid no longer exists and any internal references have
461 // already been deleted, so using {@link #getAvailableUidStatsLocked} to avoid
462 // creating an UidStats object if it doesn't already exist.
463 u = getAvailableUidStatsLocked(uid);
464 if (u == null) {
465 continue;
466 }
467 if (u.mChildUids == null) {
468 isolatedUids = null;
469 } else {
470 isolatedUids = u.mChildUids.toArray();
471 for (int j = isolatedUids.length - 1; j >= 0; --j) {
472 isolatedUids[j] = u.mChildUids.get(j);
473 }
474 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800475 }
476 long[] cpuTimesMs = mKernelSingleUidTimeReader.readDeltaMs(uid);
477 if (isolatedUids != null) {
478 for (int j = isolatedUids.length - 1; j >= 0; --j) {
479 cpuTimesMs = addCpuTimes(cpuTimesMs,
480 mKernelSingleUidTimeReader.readDeltaMs(isolatedUids[j]));
481 }
482 }
483 if (onBattery && cpuTimesMs != null) {
484 synchronized (BatteryStatsImpl.this) {
Sudheer Shankae544d162017-12-28 17:06:20 -0800485 u.addProcStateTimesMs(procState, cpuTimesMs, onBattery);
486 u.addProcStateScreenOffTimesMs(procState, cpuTimesMs, onBatteryScreenOff);
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800487 }
488 }
489 }
490 }
491
Mike Ma234d1822018-03-13 18:53:21 -0700492 public void clearPendingRemovedUids() {
493 long cutOffTime = mClocks.elapsedRealtime() - mConstants.UID_REMOVE_DELAY_MS;
494 while (!mPendingRemovedUids.isEmpty()
495 && mPendingRemovedUids.peek().timeAddedInQueue < cutOffTime) {
496 mPendingRemovedUids.poll().remove();
497 }
498 }
499
Sudheer Shankae544d162017-12-28 17:06:20 -0800500 public void copyFromAllUidsCpuTimes() {
501 synchronized (BatteryStatsImpl.this) {
502 copyFromAllUidsCpuTimes(
503 mOnBatteryTimeBase.isRunning(), mOnBatteryScreenOffTimeBase.isRunning());
504 }
505 }
506
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800507 /**
508 * When the battery/screen state changes, we don't attribute the cpu times to any process
509 * but we still need to snapshots of all uids to get correct deltas later on. Since we
510 * already read this data for updating per-freq cpu times, we can use the same data for
511 * per-procstate cpu times.
512 */
Sudheer Shankae544d162017-12-28 17:06:20 -0800513 public void copyFromAllUidsCpuTimes(boolean onBattery, boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800514 synchronized (BatteryStatsImpl.this) {
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800515 if (!mConstants.TRACK_CPU_TIMES_BY_PROC_STATE) {
516 return;
517 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800518 if(!initKernelSingleUidTimeReaderLocked()) {
519 return;
520 }
521
522 final SparseArray<long[]> allUidCpuFreqTimesMs =
Mike Ma7ab7fcd2019-01-16 15:00:40 -0800523 mCpuUidFreqTimeReader.getAllUidCpuFreqTimeMs();
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800524 // If the KernelSingleUidTimeReader has stale cpu times, then we shouldn't try to
525 // compute deltas since it might result in mis-attributing cpu times to wrong states.
Sudheer Shanka020239d2018-07-16 18:00:46 -0700526 if (mIsPerProcessStateCpuDataStale) {
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800527 mKernelSingleUidTimeReader.setAllUidsCpuTimesMs(allUidCpuFreqTimesMs);
Sudheer Shanka020239d2018-07-16 18:00:46 -0700528 mIsPerProcessStateCpuDataStale = false;
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800529 mPendingUids.clear();
530 return;
531 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800532 for (int i = allUidCpuFreqTimesMs.size() - 1; i >= 0; --i) {
533 final int uid = allUidCpuFreqTimesMs.keyAt(i);
534 final Uid u = getAvailableUidStatsLocked(mapUid(uid));
535 if (u == null) {
536 continue;
537 }
538 final long[] cpuTimesMs = allUidCpuFreqTimesMs.valueAt(i);
539 if (cpuTimesMs == null) {
540 continue;
541 }
542 final long[] deltaTimesMs = mKernelSingleUidTimeReader.computeDelta(
543 uid, cpuTimesMs.clone());
Sudheer Shankae544d162017-12-28 17:06:20 -0800544 if (onBattery && deltaTimesMs != null) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800545 final int procState;
546 final int idx = mPendingUids.indexOfKey(uid);
547 if (idx >= 0) {
548 procState = mPendingUids.valueAt(idx);
549 mPendingUids.removeAt(idx);
550 } else {
551 procState = u.mProcessState;
552 }
553 if (procState >= 0 && procState < Uid.NUM_PROCESS_STATE) {
Sudheer Shankae544d162017-12-28 17:06:20 -0800554 u.addProcStateTimesMs(procState, deltaTimesMs, onBattery);
555 u.addProcStateScreenOffTimesMs(procState, deltaTimesMs, onBatteryScreenOff);
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800556 }
557 }
558 }
559 }
560 }
561
562 @VisibleForTesting
563 public long[] addCpuTimes(long[] timesA, long[] timesB) {
564 if (timesA != null && timesB != null) {
565 for (int i = timesA.length - 1; i >= 0; --i) {
566 timesA[i] += timesB[i];
567 }
568 return timesA;
569 }
570 return timesA == null ? (timesB == null ? null : timesB) : timesA;
571 }
572
573 @GuardedBy("this")
574 private boolean initKernelSingleUidTimeReaderLocked() {
575 if (mKernelSingleUidTimeReader == null) {
576 if (mPowerProfile == null) {
577 return false;
578 }
579 if (mCpuFreqs == null) {
Mike Ma7ab7fcd2019-01-16 15:00:40 -0800580 mCpuFreqs = mCpuUidFreqTimeReader.readFreqs(mPowerProfile);
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800581 }
582 if (mCpuFreqs != null) {
583 mKernelSingleUidTimeReader = new KernelSingleUidTimeReader(mCpuFreqs.length);
584 } else {
Mike Ma7ab7fcd2019-01-16 15:00:40 -0800585 mPerProcStateCpuTimesAvailable = mCpuUidFreqTimeReader.allUidTimesAvailable();
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800586 return false;
587 }
588 }
Mike Ma7ab7fcd2019-01-16 15:00:40 -0800589 mPerProcStateCpuTimesAvailable = mCpuUidFreqTimeReader.allUidTimesAvailable()
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800590 && mKernelSingleUidTimeReader.singleUidCpuTimesAvailable();
591 return true;
592 }
593
Joe Onoratoabded112016-02-08 16:49:39 -0800594 public interface Clocks {
595 public long elapsedRealtime();
596 public long uptimeMillis();
597 }
598
599 public static class SystemClocks implements Clocks {
600 public long elapsedRealtime() {
601 return SystemClock.elapsedRealtime();
602 }
603
604 public long uptimeMillis() {
605 return SystemClock.uptimeMillis();
606 }
607 }
608
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700609 public interface ExternalStatsSync {
Adam Lesinski14ae39a2017-05-26 11:50:40 -0700610 int UPDATE_CPU = 0x01;
611 int UPDATE_WIFI = 0x02;
612 int UPDATE_RADIO = 0x04;
613 int UPDATE_BT = 0x08;
Bookatz50df7112017-08-04 14:53:26 -0700614 int UPDATE_RPM = 0x10; // 16
Blake Kragtenf68fa9e2019-04-16 10:23:11 -0700615 int UPDATE_ALL = UPDATE_CPU | UPDATE_WIFI | UPDATE_RADIO | UPDATE_BT | UPDATE_RPM;
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800616
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700617 Future<?> scheduleSync(String reason, int flags);
618 Future<?> scheduleCpuSyncDueToRemovedUid(int uid);
Sudheer Shankac20379e2018-02-15 00:06:21 -0800619 Future<?> scheduleReadProcStateCpuTimes(boolean onBattery, boolean onBatteryScreenOff,
620 long delayMillis);
Sudheer Shankae544d162017-12-28 17:06:20 -0800621 Future<?> scheduleCopyFromAllUidsCpuTimes(boolean onBattery, boolean onBatteryScreenOff);
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800622 Future<?> scheduleCpuSyncDueToSettingChange();
Sudheer Shankac57729a2018-02-09 15:44:42 -0800623 Future<?> scheduleCpuSyncDueToScreenStateChange(boolean onBattery,
624 boolean onBatteryScreenOff);
625 Future<?> scheduleCpuSyncDueToWakelockChange(long delayMillis);
626 void cancelCpuSyncDueToWakelockChange();
Sudheer Shanka0719c6a2018-04-24 11:12:11 -0700627 Future<?> scheduleSyncDueToBatteryLevelChange(long delayMillis);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700628 }
629
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800630 public Handler mHandler;
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700631 private ExternalStatsSync mExternalSync = null;
Sudheer Shanka38383232017-07-25 09:55:03 -0700632 @VisibleForTesting
633 protected UserInfoProvider mUserInfoProvider = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700634
635 private BatteryCallback mCallback;
636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800637 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -0800638 * Mapping isolated uids to the actual owning app uid.
639 */
640 final SparseIntArray mIsolatedUids = new SparseIntArray();
641
642 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800643 * The statistics we have collected organized by uids.
644 */
Adam Lesinski50e47602015-12-04 17:04:54 -0800645 final SparseArray<BatteryStatsImpl.Uid> mUidStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800646
647 // A set of pools of currently active timers. When a timer is queried, we will divide the
648 // elapsed time by the number of active timers to arrive at that timer's share of the time.
649 // In order to do this, we must refresh each timer whenever the number of active timers
650 // changes.
Sudheer Shanka38383232017-07-25 09:55:03 -0700651 @VisibleForTesting
Mathew Inwoodaf972c82018-08-20 14:13:20 +0100652 @UnsupportedAppUsage
Sudheer Shanka38383232017-07-25 09:55:03 -0700653 protected ArrayList<StopwatchTimer> mPartialTimers = new ArrayList<>();
Mathew Inwoodaf972c82018-08-20 14:13:20 +0100654 @UnsupportedAppUsage
Adam Lesinskie08af192015-03-25 16:42:59 -0700655 final ArrayList<StopwatchTimer> mFullTimers = new ArrayList<>();
Mathew Inwoodaf972c82018-08-20 14:13:20 +0100656 @UnsupportedAppUsage
Adam Lesinskie08af192015-03-25 16:42:59 -0700657 final ArrayList<StopwatchTimer> mWindowTimers = new ArrayList<>();
Jeff Brown6a8bd7b2015-06-19 15:07:51 -0700658 final ArrayList<StopwatchTimer> mDrawTimers = new ArrayList<>();
Adam Lesinskie08af192015-03-25 16:42:59 -0700659 final SparseArray<ArrayList<StopwatchTimer>> mSensorTimers = new SparseArray<>();
660 final ArrayList<StopwatchTimer> mWifiRunningTimers = new ArrayList<>();
661 final ArrayList<StopwatchTimer> mFullWifiLockTimers = new ArrayList<>();
662 final ArrayList<StopwatchTimer> mWifiMulticastTimers = new ArrayList<>();
663 final ArrayList<StopwatchTimer> mWifiScanTimers = new ArrayList<>();
664 final SparseArray<ArrayList<StopwatchTimer>> mWifiBatchedScanTimers = new SparseArray<>();
665 final ArrayList<StopwatchTimer> mAudioTurnedOnTimers = new ArrayList<>();
666 final ArrayList<StopwatchTimer> mVideoTurnedOnTimers = new ArrayList<>();
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700667 final ArrayList<StopwatchTimer> mFlashlightTurnedOnTimers = new ArrayList<>();
668 final ArrayList<StopwatchTimer> mCameraTurnedOnTimers = new ArrayList<>();
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800669 final ArrayList<StopwatchTimer> mBluetoothScanOnTimers = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700671 // Last partial timers we use for distributing CPU usage.
Sudheer Shanka38383232017-07-25 09:55:03 -0700672 @VisibleForTesting
673 protected ArrayList<StopwatchTimer> mLastPartialTimers = new ArrayList<>();
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675 // These are the objects that will want to do something when the device
676 // is unplugged from power.
Hui Yu8e88e952018-07-23 17:59:59 -0700677 protected final TimeBase mOnBatteryTimeBase = new TimeBase(true);
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800678
679 // These are the objects that will want to do something when the device
Mike Mac2f518a2017-09-19 16:06:03 -0700680 // is unplugged from power *and* the screen is off or doze.
Hui Yu8e88e952018-07-23 17:59:59 -0700681 protected final TimeBase mOnBatteryScreenOffTimeBase = new TimeBase(true);
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800682
683 // Set to true when we want to distribute CPU across wakelocks for the next
684 // CPU update, even if we aren't currently running wake locks.
685 boolean mDistributeWakelockCpu;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700686
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700687 boolean mShuttingDown;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700688
Dianne Hackborn37de0982014-05-09 09:32:18 -0700689 final HistoryEventTracker mActiveEvents = new HistoryEventTracker();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800690
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700691 long mHistoryBaseTime;
Narayan Kamath695cf722017-12-21 18:32:47 +0000692 protected boolean mHaveBatteryLevel = false;
693 protected boolean mRecordingHistory = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700694 int mNumHistoryItems;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700695
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700696 final Parcel mHistoryBuffer = Parcel.obtain();
697 final HistoryItem mHistoryLastWritten = new HistoryItem();
698 final HistoryItem mHistoryLastLastWritten = new HistoryItem();
Dianne Hackborn1fadab52011-04-14 17:57:33 -0700699 final HistoryItem mHistoryReadTmp = new HistoryItem();
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700700 final HistoryItem mHistoryAddTmp = new HistoryItem();
Adam Lesinskie08af192015-03-25 16:42:59 -0700701 final HashMap<HistoryTag, Integer> mHistoryTagPool = new HashMap<>();
Dianne Hackborn099bc622014-01-22 13:39:16 -0800702 String[] mReadHistoryStrings;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -0800703 int[] mReadHistoryUids;
704 int mReadHistoryChars;
705 int mNextHistoryTagIdx = 0;
706 int mNumHistoryTagChars = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700707 int mHistoryBufferLastPos = -1;
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700708 int mActiveHistoryStates = 0xffffffff;
709 int mActiveHistoryStates2 = 0xffffffff;
Dianne Hackborn40c87252014-03-19 16:55:40 -0700710 long mLastHistoryElapsedRealtime = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700711 long mTrackRunningHistoryElapsedRealtime = 0;
712 long mTrackRunningHistoryUptime = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700713
Hui Yu0ed84f12018-06-20 19:07:56 -0700714 final BatteryStatsHistory mBatteryStatsHistory;
715
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700716 final HistoryItem mHistoryCur = new HistoryItem();
717
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700718 HistoryItem mHistory;
719 HistoryItem mHistoryEnd;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700720 HistoryItem mHistoryLastEnd;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700721 HistoryItem mHistoryCache;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700722
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800723 // Used by computeHistoryStepDetails
724 HistoryStepDetails mLastHistoryStepDetails = null;
725 byte mLastHistoryStepLevel = 0;
726 final HistoryStepDetails mCurHistoryStepDetails = new HistoryStepDetails();
727 final HistoryStepDetails mReadHistoryStepDetails = new HistoryStepDetails();
728 final HistoryStepDetails mTmpHistoryStepDetails = new HistoryStepDetails();
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700729
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800730 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700731 * Total time (in milliseconds) spent executing in user code.
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800732 */
733 long mLastStepCpuUserTime;
734 long mCurStepCpuUserTime;
735 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700736 * Total time (in milliseconds) spent executing in kernel code.
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800737 */
738 long mLastStepCpuSystemTime;
739 long mCurStepCpuSystemTime;
740 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700741 * Times from /proc/stat (but measured in milliseconds).
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800742 */
743 long mLastStepStatUserTime;
744 long mLastStepStatSystemTime;
745 long mLastStepStatIOWaitTime;
746 long mLastStepStatIrqTime;
747 long mLastStepStatSoftIrqTime;
748 long mLastStepStatIdleTime;
749 long mCurStepStatUserTime;
750 long mCurStepStatSystemTime;
751 long mCurStepStatIOWaitTime;
752 long mCurStepStatIrqTime;
753 long mCurStepStatSoftIrqTime;
754 long mCurStepStatIdleTime;
755
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700756 private HistoryItem mHistoryIterator;
757 private boolean mReadOverflow;
758 private boolean mIteratingHistory;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 int mStartCount;
761
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -0800762 long mStartClockTime;
Dianne Hackborncd0e3352014-08-07 17:08:09 -0700763 String mStartPlatformVersion;
764 String mEndPlatformVersion;
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -0800765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766 long mUptime;
767 long mUptimeStart;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800768 long mRealtime;
769 long mRealtimeStart;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700770
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800771 int mWakeLockNesting;
772 boolean mWakeLockImportant;
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700773 public boolean mRecordAllHistory;
Dianne Hackborn9a755432014-05-15 17:05:22 -0700774 boolean mNoAutoReset;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800775
Mike Mac2f518a2017-09-19 16:06:03 -0700776 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
777 protected int mScreenState = Display.STATE_UNKNOWN;
778 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
779 protected StopwatchTimer mScreenOnTimer;
780 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
781 protected StopwatchTimer mScreenDozeTimer;
Amith Yamasani3718aaa2009-06-09 06:32:35 -0700782
Dianne Hackborn617f8772009-03-31 15:04:46 -0700783 int mScreenBrightnessBin = -1;
Evan Millarc64edde2009-04-18 12:26:32 -0700784 final StopwatchTimer[] mScreenBrightnessTimer = new StopwatchTimer[NUM_SCREEN_BRIGHTNESS_BINS];
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700785
Amith Yamasani674c9bb2017-02-01 09:45:17 -0800786 boolean mPretendScreenOff;
787
Jeff Browne95c3cd2014-05-02 16:59:26 -0700788 boolean mInteractive;
789 StopwatchTimer mInteractiveTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700790
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700791 boolean mPowerSaveModeEnabled;
792 StopwatchTimer mPowerSaveModeEnabledTimer;
793
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700794 boolean mDeviceIdling;
795 StopwatchTimer mDeviceIdlingTimer;
796
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700797 boolean mDeviceLightIdling;
798 StopwatchTimer mDeviceLightIdlingTimer;
799
800 int mDeviceIdleMode;
801 long mLastIdleTimeStart;
802 long mLongestLightIdleTime;
803 long mLongestFullIdleTime;
804 StopwatchTimer mDeviceIdleModeLightTimer;
805 StopwatchTimer mDeviceIdleModeFullTimer;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 boolean mPhoneOn;
Evan Millarc64edde2009-04-18 12:26:32 -0700808 StopwatchTimer mPhoneOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700809
Dianne Hackborn10eaa852014-07-22 22:54:55 -0700810 int mAudioOnNesting;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700811 StopwatchTimer mAudioOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700812
Dianne Hackborn10eaa852014-07-22 22:54:55 -0700813 int mVideoOnNesting;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700814 StopwatchTimer mVideoOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700815
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700816 int mFlashlightOnNesting;
Dianne Hackbornabc7c492014-06-30 16:57:46 -0700817 StopwatchTimer mFlashlightOnTimer;
818
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700819 int mCameraOnNesting;
820 StopwatchTimer mCameraOnTimer;
821
Mike Mafbc01fc2018-04-02 10:28:28 -0700822 private static final int USB_DATA_UNKNOWN = 0;
823 private static final int USB_DATA_DISCONNECTED = 1;
824 private static final int USB_DATA_CONNECTED = 2;
825 int mUsbDataState = USB_DATA_UNKNOWN;
Mike Ma926a97c2018-03-25 02:32:35 -0700826
Siddharth Ray78ccaf52017-12-23 16:16:21 -0800827 int mGpsSignalQualityBin = -1;
Narayan Kamathefa0fe62018-02-05 16:04:43 +0000828 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
829 protected final StopwatchTimer[] mGpsSignalQualityTimer =
Siddharth Ray78ccaf52017-12-23 16:16:21 -0800830 new StopwatchTimer[GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS];
831
Dianne Hackborn627bba72009-03-24 22:32:56 -0700832 int mPhoneSignalStrengthBin = -1;
Dianne Hackborne4a59512010-12-07 11:08:07 -0800833 int mPhoneSignalStrengthBinRaw = -1;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700834 final StopwatchTimer[] mPhoneSignalStrengthsTimer =
Wink Saville52840902011-02-18 12:40:47 -0800835 new StopwatchTimer[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
Amith Yamasanif37447b2009-10-08 18:28:01 -0700836
837 StopwatchTimer mPhoneSignalScanningTimer;
838
Dianne Hackborn627bba72009-03-24 22:32:56 -0700839 int mPhoneDataConnectionType = -1;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700840 final StopwatchTimer[] mPhoneDataConnectionsTimer =
Evan Millarc64edde2009-04-18 12:26:32 -0700841 new StopwatchTimer[NUM_DATA_CONNECTION_TYPES];
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700842
Dianne Hackborn57ed6a62013-12-09 18:15:56 -0800843 final LongSamplingCounter[] mNetworkByteActivityCounters =
844 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
845 final LongSamplingCounter[] mNetworkPacketActivityCounters =
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700846 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
847
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800848 /**
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -0800849 * The WiFi Overall wakelock timer
850 * This timer tracks the actual aggregate time for which MC wakelocks are enabled
851 * since addition of per UID timers would not result in an accurate value due to overlapp of
852 * per uid wakelock timers
853 */
854 StopwatchTimer mWifiMulticastWakelockTimer;
855
856 /**
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800857 * The WiFi controller activity (time in tx, rx, idle, and power consumed) for the device.
858 */
859 ControllerActivityCounterImpl mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -0700860
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800861 /**
862 * The Bluetooth controller activity (time in tx, rx, idle, and power consumed) for the device.
863 */
864 ControllerActivityCounterImpl mBluetoothActivity;
865
866 /**
867 * The Modem controller activity (time in tx, rx, idle, and power consumed) for the device.
868 */
869 ControllerActivityCounterImpl mModemActivity;
870
871 /**
872 * Whether the device supports WiFi controller energy reporting. This is set to true on
873 * the first WiFi energy report. See {@link #mWifiActivity}.
874 */
875 boolean mHasWifiReporting = false;
876
877 /**
878 * Whether the device supports Bluetooth controller energy reporting. This is set to true on
879 * the first Bluetooth energy report. See {@link #mBluetoothActivity}.
880 */
881 boolean mHasBluetoothReporting = false;
882
883 /**
884 * Whether the device supports Modem controller energy reporting. This is set to true on
885 * the first Modem energy report. See {@link #mModemActivity}.
886 */
887 boolean mHasModemReporting = false;
Adam Lesinski33dac552015-03-09 15:24:48 -0700888
The Android Open Source Project10592532009-03-18 17:39:46 -0700889 boolean mWifiOn;
Evan Millarc64edde2009-04-18 12:26:32 -0700890 StopwatchTimer mWifiOnTimer;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -0700891
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700892 boolean mGlobalWifiRunning;
893 StopwatchTimer mGlobalWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700894
Dianne Hackbornca1bf212014-02-14 14:18:36 -0800895 int mWifiState = -1;
896 final StopwatchTimer[] mWifiStateTimer = new StopwatchTimer[NUM_WIFI_STATES];
897
Dianne Hackborn3251b902014-06-20 14:40:53 -0700898 int mWifiSupplState = -1;
899 final StopwatchTimer[] mWifiSupplStateTimer = new StopwatchTimer[NUM_WIFI_SUPPL_STATES];
900
901 int mWifiSignalStrengthBin = -1;
902 final StopwatchTimer[] mWifiSignalStrengthsTimer =
903 new StopwatchTimer[NUM_WIFI_SIGNAL_STRENGTH_BINS];
904
Siddharth Rayb50a6842017-12-14 15:15:28 -0800905 StopwatchTimer mWifiActiveTimer;
906
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800907 int mBluetoothScanNesting;
Bookatz867c0d72017-03-07 18:23:42 -0800908 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
909 protected StopwatchTimer mBluetoothScanTimer;
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800910
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700911 int mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackbornf7097a52014-05-13 09:56:14 -0700912 long mMobileRadioActiveStartTime;
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800913 StopwatchTimer mMobileRadioActiveTimer;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800914 StopwatchTimer mMobileRadioActivePerAppTimer;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700915 LongSamplingCounter mMobileRadioActiveAdjustedTime;
Dianne Hackbornd45665b2014-02-26 12:35:32 -0800916 LongSamplingCounter mMobileRadioActiveUnknownTime;
917 LongSamplingCounter mMobileRadioActiveUnknownCount;
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800918
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700919 int mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
920
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921 /**
922 * These provide time bases that discount the time the device is plugged
923 * in to power.
924 */
925 boolean mOnBattery;
Sudheer Shanka38383232017-07-25 09:55:03 -0700926 @VisibleForTesting
927 protected boolean mOnBatteryInternal;
Amith Yamasani3718aaa2009-06-09 06:32:35 -0700928
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700929 /**
930 * External reporting of whether the device is actually charging.
931 */
932 boolean mCharging = true;
933 int mLastChargingStateLevel;
934
The Android Open Source Project10592532009-03-18 17:39:46 -0700935 /*
936 * These keep track of battery levels (1-100) at the last plug event and the last unplug event.
937 */
Evan Millar633a1742009-04-02 16:36:33 -0700938 int mDischargeStartLevel;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700939 int mDischargeUnplugLevel;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700940 int mDischargePlugLevel;
Evan Millar633a1742009-04-02 16:36:33 -0700941 int mDischargeCurrentLevel;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700942 int mCurrentBatteryLevel;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -0700943 int mLowDischargeAmountSinceCharge;
944 int mHighDischargeAmountSinceCharge;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -0800945 int mDischargeScreenOnUnplugLevel;
946 int mDischargeScreenOffUnplugLevel;
Mike Mac2f518a2017-09-19 16:06:03 -0700947 int mDischargeScreenDozeUnplugLevel;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -0800948 int mDischargeAmountScreenOn;
949 int mDischargeAmountScreenOnSinceCharge;
950 int mDischargeAmountScreenOff;
951 int mDischargeAmountScreenOffSinceCharge;
Mike Mac2f518a2017-09-19 16:06:03 -0700952 int mDischargeAmountScreenDoze;
953 int mDischargeAmountScreenDozeSinceCharge;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700954
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700955 private LongSamplingCounter mDischargeScreenOffCounter;
Mike Mac2f518a2017-09-19 16:06:03 -0700956 private LongSamplingCounter mDischargeScreenDozeCounter;
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700957 private LongSamplingCounter mDischargeCounter;
Mike Ma15313c92017-11-15 17:58:21 -0800958 private LongSamplingCounter mDischargeLightDozeCounter;
959 private LongSamplingCounter mDischargeDeepDozeCounter;
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700960
Dianne Hackborncd0e3352014-08-07 17:08:09 -0700961 static final int MAX_LEVEL_STEPS = 200;
Dianne Hackborn260c5022014-04-29 11:23:16 -0700962
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700963 int mInitStepMode = 0;
964 int mCurStepMode = 0;
965 int mModStepMode = 0;
966
Dianne Hackborn260c5022014-04-29 11:23:16 -0700967 int mLastDischargeStepLevel;
Dianne Hackborn29325132014-05-21 15:01:03 -0700968 int mMinDischargeStepLevel;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800969 final LevelStepTracker mDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS);
970 final LevelStepTracker mDailyDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700971 ArrayList<PackageChange> mDailyPackageChanges;
Dianne Hackborn260c5022014-04-29 11:23:16 -0700972
973 int mLastChargeStepLevel;
Dianne Hackborn29325132014-05-21 15:01:03 -0700974 int mMaxChargeStepLevel;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800975 final LevelStepTracker mChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS);
976 final LevelStepTracker mDailyChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2);
977
978 static final int MAX_DAILY_ITEMS = 10;
979
980 long mDailyStartTime = 0;
981 long mNextMinDailyDeadline = 0;
982 long mNextMaxDailyDeadline = 0;
983
984 final ArrayList<DailyItem> mDailyItems = new ArrayList<>();
Dianne Hackborn260c5022014-04-29 11:23:16 -0700985
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 long mLastWriteTime = 0; // Milliseconds
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700987
Amith Yamasanif37447b2009-10-08 18:28:01 -0700988 private int mPhoneServiceState = -1;
Dianne Hackborne4a59512010-12-07 11:08:07 -0800989 private int mPhoneServiceStateRaw = -1;
990 private int mPhoneSimStateRaw = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -0700991
Dianne Hackborn1e01d162014-12-04 17:46:42 -0800992 private int mNumConnectivityChange;
Dianne Hackborn1e01d162014-12-04 17:46:42 -0800993
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700994 private int mEstimatedBatteryCapacity = -1;
995
Jocelyn Dangc627d102017-04-14 13:15:14 -0700996 private int mMinLearnedBatteryCapacity = -1;
997 private int mMaxLearnedBatteryCapacity = -1;
Adam Lesinski041d9172016-12-12 12:03:56 -0800998
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700999 private long[] mCpuFreqs;
1000
Sudheer Shanka38383232017-07-25 09:55:03 -07001001 @VisibleForTesting
1002 protected PowerProfile mPowerProfile;
Adam Lesinskie08af192015-03-25 16:42:59 -07001003
Sudheer Shanka5c19b892018-01-05 17:25:46 -08001004 @GuardedBy("this")
Hui Yu0ed84f12018-06-20 19:07:56 -07001005 final Constants mConstants;
Sudheer Shanka5c19b892018-01-05 17:25:46 -08001006
Evan Millarc64edde2009-04-18 12:26:32 -07001007 /*
Bookatz50df7112017-08-04 14:53:26 -07001008 * Holds a SamplingTimer associated with each Resource Power Manager state and voter,
1009 * recording their times when on-battery (regardless of screen state).
1010 */
1011 private final HashMap<String, SamplingTimer> mRpmStats = new HashMap<>();
1012 /** Times for each Resource Power Manager state and voter when screen-off and on-battery. */
1013 private final HashMap<String, SamplingTimer> mScreenOffRpmStats = new HashMap<>();
1014
1015 @Override
1016 public Map<String, ? extends Timer> getRpmStats() {
1017 return mRpmStats;
1018 }
1019
Bookatz82b341172017-09-07 19:06:08 -07001020 // TODO: Note: screenOffRpmStats has been disabled via SCREEN_OFF_RPM_STATS_ENABLED.
Bookatz50df7112017-08-04 14:53:26 -07001021 @Override
1022 public Map<String, ? extends Timer> getScreenOffRpmStats() {
1023 return mScreenOffRpmStats;
1024 }
1025
1026 /*
Evan Millarc64edde2009-04-18 12:26:32 -07001027 * Holds a SamplingTimer associated with each kernel wakelock name being tracked.
1028 */
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07001029 private final HashMap<String, SamplingTimer> mKernelWakelockStats = new HashMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001030
Mathew Inwoodaf972c82018-08-20 14:13:20 +01001031 @UnsupportedAppUsage
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001032 public Map<String, ? extends Timer> getKernelWakelockStats() {
Evan Millarc64edde2009-04-18 12:26:32 -07001033 return mKernelWakelockStats;
1034 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001035
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001036 String mLastWakeupReason = null;
1037 long mLastWakeupUptimeMs = 0;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07001038 private final HashMap<String, SamplingTimer> mWakeupReasonStats = new HashMap<>();
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001039
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07001040 public Map<String, ? extends Timer> getWakeupReasonStats() {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001041 return mWakeupReasonStats;
1042 }
1043
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001044 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -07001045 public long getUahDischarge(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -07001046 return mDischargeCounter.getCountLocked(which);
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001047 }
1048
1049 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -07001050 public long getUahDischargeScreenOff(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -07001051 return mDischargeScreenOffCounter.getCountLocked(which);
1052 }
1053
1054 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -07001055 public long getUahDischargeScreenDoze(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -07001056 return mDischargeScreenDozeCounter.getCountLocked(which);
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001057 }
1058
Adam Lesinskif9b20a92016-06-17 17:30:01 -07001059 @Override
Mike Ma15313c92017-11-15 17:58:21 -08001060 public long getUahDischargeLightDoze(int which) {
1061 return mDischargeLightDozeCounter.getCountLocked(which);
1062 }
1063
1064 @Override
1065 public long getUahDischargeDeepDoze(int which) {
1066 return mDischargeDeepDozeCounter.getCountLocked(which);
1067 }
1068
1069 @Override
Adam Lesinskif9b20a92016-06-17 17:30:01 -07001070 public int getEstimatedBatteryCapacity() {
1071 return mEstimatedBatteryCapacity;
1072 }
1073
Jocelyn Dangc627d102017-04-14 13:15:14 -07001074 @Override
1075 public int getMinLearnedBatteryCapacity() {
1076 return mMinLearnedBatteryCapacity;
1077 }
1078
1079 @Override
1080 public int getMaxLearnedBatteryCapacity() {
1081 return mMaxLearnedBatteryCapacity;
1082 }
1083
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 public BatteryStatsImpl() {
Joe Onoratoabded112016-02-08 16:49:39 -08001085 this(new SystemClocks());
1086 }
1087
1088 public BatteryStatsImpl(Clocks clocks) {
1089 init(clocks);
Hui Yu0ed84f12018-06-20 19:07:56 -07001090 mStatsFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07001091 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08001092 mDailyFile = null;
Hui Yu0ed84f12018-06-20 19:07:56 -07001093 mBatteryStatsHistory = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001094 mHandler = null;
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07001095 mPlatformIdleStateCallback = null;
Blake Kragtencb308d92019-01-28 10:54:13 -08001096 mRailEnergyDataCallback = null;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -07001097 mUserInfoProvider = null;
Sudheer Shanka5c19b892018-01-05 17:25:46 -08001098 mConstants = new Constants(mHandler);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07001099 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100 }
1101
Joe Onoratoabded112016-02-08 16:49:39 -08001102 private void init(Clocks clocks) {
1103 mClocks = clocks;
Joe Onoratoabded112016-02-08 16:49:39 -08001104 }
1105
Hui Yu8e88e952018-07-23 17:59:59 -07001106 /**
1107 * TimeBase observer.
1108 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -07001109 public interface TimeBaseObs {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001110 void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime);
1111 void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime);
Hui Yu8e88e952018-07-23 17:59:59 -07001112
1113 /**
1114 * Reset the observer's state, returns true if the timer/counter is inactive
Hui Yu10571e02018-08-06 13:12:40 -07001115 * so it can be destroyed.
Hui Yu8e88e952018-07-23 17:59:59 -07001116 * @param detachIfReset detach if true, no-op if false.
Hui Yu10571e02018-08-06 13:12:40 -07001117 * @return Returns true if the timer/counter is inactive and can be destroyed.
Hui Yu8e88e952018-07-23 17:59:59 -07001118 */
1119 boolean reset(boolean detachIfReset);
1120 /**
1121 * Detach the observer from TimeBase.
1122 */
1123 void detach();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001124 }
1125
Joe Onoratoabded112016-02-08 16:49:39 -08001126 // methods are protected not private to be VisibleForTesting
1127 public static class TimeBase {
Hui Yu8e88e952018-07-23 17:59:59 -07001128 protected final Collection<TimeBaseObs> mObservers;
Joe Onoratoabded112016-02-08 16:49:39 -08001129 protected long mUptime;
1130 protected long mRealtime;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001131
Joe Onoratoabded112016-02-08 16:49:39 -08001132 protected boolean mRunning;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001133
Joe Onoratoabded112016-02-08 16:49:39 -08001134 protected long mPastUptime;
1135 protected long mUptimeStart;
1136 protected long mPastRealtime;
1137 protected long mRealtimeStart;
1138 protected long mUnpluggedUptime;
1139 protected long mUnpluggedRealtime;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001140
1141 public void dump(PrintWriter pw, String prefix) {
1142 StringBuilder sb = new StringBuilder(128);
1143 pw.print(prefix); pw.print("mRunning="); pw.println(mRunning);
1144 sb.setLength(0);
1145 sb.append(prefix);
1146 sb.append("mUptime=");
Dianne Hackborn4590e522014-03-24 13:36:46 -07001147 formatTimeMs(sb, mUptime / 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001148 pw.println(sb.toString());
1149 sb.setLength(0);
1150 sb.append(prefix);
1151 sb.append("mRealtime=");
Dianne Hackborn4590e522014-03-24 13:36:46 -07001152 formatTimeMs(sb, mRealtime / 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001153 pw.println(sb.toString());
1154 sb.setLength(0);
1155 sb.append(prefix);
1156 sb.append("mPastUptime=");
1157 formatTimeMs(sb, mPastUptime / 1000); sb.append("mUptimeStart=");
1158 formatTimeMs(sb, mUptimeStart / 1000);
1159 sb.append("mUnpluggedUptime="); formatTimeMs(sb, mUnpluggedUptime / 1000);
1160 pw.println(sb.toString());
1161 sb.setLength(0);
1162 sb.append(prefix);
1163 sb.append("mPastRealtime=");
1164 formatTimeMs(sb, mPastRealtime / 1000); sb.append("mRealtimeStart=");
1165 formatTimeMs(sb, mRealtimeStart / 1000);
1166 sb.append("mUnpluggedRealtime="); formatTimeMs(sb, mUnpluggedRealtime / 1000);
1167 pw.println(sb.toString());
1168 }
Hui Yu8e88e952018-07-23 17:59:59 -07001169 /**
1170 * The mObservers of TimeBase in BatteryStatsImpl object can contain up to 20k entries.
1171 * The mObservers of TimeBase in BatteryStatsImpl.Uid object only contains a few or tens of
1172 * entries.
1173 * mObservers must have good performance on add(), remove(), also be memory efficient.
1174 * This is why we provide isLongList parameter for long and short list user cases.
1175 * @param isLongList If true, use HashSet for mObservers list.
1176 * If false, use ArrayList for mObservers list.
1177 */
1178 public TimeBase(boolean isLongList) {
Hui Yu10571e02018-08-06 13:12:40 -07001179 mObservers = isLongList ? new HashSet<>() : new ArrayList<>();
Hui Yu8e88e952018-07-23 17:59:59 -07001180 }
1181
1182 public TimeBase() {
1183 this(false);
1184 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001185
1186 public void add(TimeBaseObs observer) {
Hui Yu6fc752c2018-07-20 17:48:43 +00001187 mObservers.add(observer);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001188 }
1189
1190 public void remove(TimeBaseObs observer) {
Hui Yu8e88e952018-07-23 17:59:59 -07001191 mObservers.remove(observer);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001192 }
1193
Joe Onoratoabded112016-02-08 16:49:39 -08001194 public boolean hasObserver(TimeBaseObs observer) {
Hui Yu6fc752c2018-07-20 17:48:43 +00001195 return mObservers.contains(observer);
Joe Onoratoabded112016-02-08 16:49:39 -08001196 }
1197
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001198 public void init(long uptime, long realtime) {
1199 mRealtime = 0;
1200 mUptime = 0;
1201 mPastUptime = 0;
1202 mPastRealtime = 0;
1203 mUptimeStart = uptime;
1204 mRealtimeStart = realtime;
1205 mUnpluggedUptime = getUptime(mUptimeStart);
1206 mUnpluggedRealtime = getRealtime(mRealtimeStart);
1207 }
1208
1209 public void reset(long uptime, long realtime) {
1210 if (!mRunning) {
1211 mPastUptime = 0;
1212 mPastRealtime = 0;
1213 } else {
1214 mUptimeStart = uptime;
1215 mRealtimeStart = realtime;
Joe Onoratoabded112016-02-08 16:49:39 -08001216 // TODO: Since mUptimeStart was just reset and we are running, getUptime will
1217 // just return mPastUptime. Also, are we sure we don't want to reset that?
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001218 mUnpluggedUptime = getUptime(uptime);
Joe Onoratoabded112016-02-08 16:49:39 -08001219 // TODO: likewise.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001220 mUnpluggedRealtime = getRealtime(realtime);
1221 }
1222 }
1223
1224 public long computeUptime(long curTime, int which) {
Mike Ma99e57c32018-03-15 14:40:37 -07001225 return mUptime + getUptime(curTime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001226 }
1227
1228 public long computeRealtime(long curTime, int which) {
Mike Ma99e57c32018-03-15 14:40:37 -07001229 return mRealtime + getRealtime(curTime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001230 }
1231
1232 public long getUptime(long curTime) {
1233 long time = mPastUptime;
1234 if (mRunning) {
1235 time += curTime - mUptimeStart;
1236 }
1237 return time;
1238 }
1239
1240 public long getRealtime(long curTime) {
1241 long time = mPastRealtime;
1242 if (mRunning) {
1243 time += curTime - mRealtimeStart;
1244 }
1245 return time;
1246 }
1247
1248 public long getUptimeStart() {
1249 return mUptimeStart;
1250 }
1251
1252 public long getRealtimeStart() {
1253 return mRealtimeStart;
1254 }
1255
1256 public boolean isRunning() {
1257 return mRunning;
1258 }
1259
1260 public boolean setRunning(boolean running, long uptime, long realtime) {
1261 if (mRunning != running) {
1262 mRunning = running;
1263 if (running) {
1264 mUptimeStart = uptime;
1265 mRealtimeStart = realtime;
1266 long batteryUptime = mUnpluggedUptime = getUptime(uptime);
1267 long batteryRealtime = mUnpluggedRealtime = getRealtime(realtime);
Hui Yu10571e02018-08-06 13:12:40 -07001268 // Normally we do not use Iterator in framework code to avoid alloc/dealloc
1269 // Iterator object, here is an exception because mObservers' type is Collection
1270 // instead of list.
Hui Yu8e88e952018-07-23 17:59:59 -07001271 final Iterator<TimeBaseObs> iter = mObservers.iterator();
1272 while (iter.hasNext()) {
1273 iter.next().onTimeStarted(realtime, batteryUptime, batteryRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001274 }
1275 } else {
1276 mPastUptime += uptime - mUptimeStart;
1277 mPastRealtime += realtime - mRealtimeStart;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001278 long batteryUptime = getUptime(uptime);
1279 long batteryRealtime = getRealtime(realtime);
Hui Yu10571e02018-08-06 13:12:40 -07001280 // Normally we do not use Iterator in framework code to avoid alloc/dealloc
1281 // Iterator object, here is an exception because mObservers' type is Collection
1282 // instead of list.
Hui Yu8e88e952018-07-23 17:59:59 -07001283 final Iterator<TimeBaseObs> iter = mObservers.iterator();
1284 while (iter.hasNext()) {
1285 iter.next().onTimeStopped(realtime, batteryUptime, batteryRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001286 }
1287 }
1288 return true;
1289 }
1290 return false;
1291 }
1292
1293 public void readSummaryFromParcel(Parcel in) {
1294 mUptime = in.readLong();
1295 mRealtime = in.readLong();
1296 }
1297
1298 public void writeSummaryToParcel(Parcel out, long uptime, long realtime) {
1299 out.writeLong(computeUptime(uptime, STATS_SINCE_CHARGED));
1300 out.writeLong(computeRealtime(realtime, STATS_SINCE_CHARGED));
1301 }
1302
1303 public void readFromParcel(Parcel in) {
1304 mRunning = false;
1305 mUptime = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001306 mPastUptime = in.readLong();
1307 mUptimeStart = in.readLong();
Dianne Hackbornef640cd2014-03-25 14:41:05 -07001308 mRealtime = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001309 mPastRealtime = in.readLong();
1310 mRealtimeStart = in.readLong();
1311 mUnpluggedUptime = in.readLong();
1312 mUnpluggedRealtime = in.readLong();
1313 }
1314
1315 public void writeToParcel(Parcel out, long uptime, long realtime) {
1316 final long runningUptime = getUptime(uptime);
1317 final long runningRealtime = getRealtime(realtime);
1318 out.writeLong(mUptime);
1319 out.writeLong(runningUptime);
1320 out.writeLong(mUptimeStart);
Dianne Hackbornef640cd2014-03-25 14:41:05 -07001321 out.writeLong(mRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001322 out.writeLong(runningRealtime);
1323 out.writeLong(mRealtimeStart);
1324 out.writeLong(mUnpluggedUptime);
1325 out.writeLong(mUnpluggedRealtime);
1326 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329 /**
Dianne Hackborn617f8772009-03-31 15:04:46 -07001330 * State for keeping track of counting information.
1331 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001332 public static class Counter extends BatteryStats.Counter implements TimeBaseObs {
Mathew Inwoodaf972c82018-08-20 14:13:20 +01001333 @UnsupportedAppUsage
Christopher Tate4cee7252010-03-19 14:50:40 -07001334 final AtomicInteger mCount = new AtomicInteger();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001335 final TimeBase mTimeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001336
Bookatz8c6f3c52017-05-24 12:00:17 -07001337 public Counter(TimeBase timeBase, Parcel in) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001338 mTimeBase = timeBase;
Mike Ma99e57c32018-03-15 14:40:37 -07001339 mCount.set(in.readInt());
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001340 timeBase.add(this);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001341 }
1342
Bookatz8c6f3c52017-05-24 12:00:17 -07001343 public Counter(TimeBase timeBase) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001344 mTimeBase = timeBase;
1345 timeBase.add(this);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001346 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001347
Dianne Hackborn617f8772009-03-31 15:04:46 -07001348 public void writeToParcel(Parcel out) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001349 out.writeInt(mCount.get());
Dianne Hackborn617f8772009-03-31 15:04:46 -07001350 }
1351
Bookatz8c6f3c52017-05-24 12:00:17 -07001352 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001353 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07001354 }
1355
Bookatz8c6f3c52017-05-24 12:00:17 -07001356 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001357 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07001358 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001359
Dianne Hackborn617f8772009-03-31 15:04:46 -07001360 /**
1361 * Writes a possibly null Counter to a Parcel.
1362 *
1363 * @param out the Parcel to be written to.
1364 * @param counter a Counter, or null.
1365 */
Amith Yamasani977e11f2018-02-16 11:29:54 -08001366 public static void writeCounterToParcel(Parcel out, @Nullable Counter counter) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07001367 if (counter == null) {
1368 out.writeInt(0); // indicates null
1369 return;
1370 }
1371 out.writeInt(1); // indicates non-null
1372
1373 counter.writeToParcel(out);
1374 }
1375
Amith Yamasani977e11f2018-02-16 11:29:54 -08001376 /**
1377 * Reads a Counter that was written using {@link #writeCounterToParcel(Parcel, Counter)}.
1378 * @param timeBase the timebase to assign to the Counter
1379 * @param in the parcel to read from
1380 * @return the Counter or null.
1381 */
1382 public static @Nullable Counter readCounterFromParcel(TimeBase timeBase, Parcel in) {
1383 if (in.readInt() == 0) {
1384 return null;
1385 }
1386 return new Counter(timeBase, in);
1387 }
1388
Dianne Hackborn617f8772009-03-31 15:04:46 -07001389 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001390 public int getCountLocked(int which) {
Mike Ma99e57c32018-03-15 14:40:37 -07001391 return mCount.get();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001392 }
1393
1394 public void logState(Printer pw, String prefix) {
Mike Ma99e57c32018-03-15 14:40:37 -07001395 pw.println(prefix + "mCount=" + mCount.get());
Dianne Hackborn617f8772009-03-31 15:04:46 -07001396 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001397
Bookatz8c6f3c52017-05-24 12:00:17 -07001398 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1399 public void stepAtomic() {
1400 if (mTimeBase.isRunning()) {
1401 mCount.incrementAndGet();
1402 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001403 }
1404
Bookatz4ebc0642017-05-11 12:21:19 -07001405 void addAtomic(int delta) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001406 if (mTimeBase.isRunning()) {
1407 mCount.addAndGet(delta);
1408 }
Bookatz4ebc0642017-05-11 12:21:19 -07001409 }
1410
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001411 /**
1412 * Clear state of this counter.
1413 */
Hui Yu8e88e952018-07-23 17:59:59 -07001414 @Override
1415 public boolean reset(boolean detachIfReset) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001416 mCount.set(0);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001417 if (detachIfReset) {
1418 detach();
1419 }
Hui Yu8e88e952018-07-23 17:59:59 -07001420 return true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001421 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001422
Hui Yu8e88e952018-07-23 17:59:59 -07001423 @Override
1424 public void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001425 mTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001426 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001427
Bookatz8c6f3c52017-05-24 12:00:17 -07001428 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1429 public void writeSummaryFromParcelLocked(Parcel out) {
Mike Ma99e57c32018-03-15 14:40:37 -07001430 out.writeInt(mCount.get());
Dianne Hackborn617f8772009-03-31 15:04:46 -07001431 }
1432
Bookatz8c6f3c52017-05-24 12:00:17 -07001433 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1434 public void readSummaryFromParcelLocked(Parcel in) {
Mike Ma99e57c32018-03-15 14:40:37 -07001435 mCount.set(in.readInt());
Dianne Hackborn617f8772009-03-31 15:04:46 -07001436 }
1437 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07001438
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001439 @VisibleForTesting
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001440 public static class LongSamplingCounterArray extends LongCounterArray implements TimeBaseObs {
1441 final TimeBase mTimeBase;
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001442 public long[] mCounts;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001443
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001444 private LongSamplingCounterArray(TimeBase timeBase, Parcel in) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001445 mTimeBase = timeBase;
Sudheer Shankae544d162017-12-28 17:06:20 -08001446 mCounts = in.createLongArray();
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001447 timeBase.add(this);
1448 }
1449
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001450 public LongSamplingCounterArray(TimeBase timeBase) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001451 mTimeBase = timeBase;
1452 timeBase.add(this);
1453 }
1454
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001455 private void writeToParcel(Parcel out) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001456 out.writeLongArray(mCounts);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001457 }
1458
1459 @Override
1460 public void onTimeStarted(long elapsedRealTime, long baseUptime, long baseRealtime) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001461 }
1462
1463 @Override
1464 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001465 }
1466
1467 @Override
1468 public long[] getCountsLocked(int which) {
Mike Ma99e57c32018-03-15 14:40:37 -07001469 return mCounts == null ? null : Arrays.copyOf(mCounts, mCounts.length);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001470 }
1471
1472 @Override
1473 public void logState(Printer pw, String prefix) {
Mike Ma99e57c32018-03-15 14:40:37 -07001474 pw.println(prefix + "mCounts=" + Arrays.toString(mCounts));
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001475 }
1476
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001477 public void addCountLocked(long[] counts) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001478 addCountLocked(counts, mTimeBase.isRunning());
1479 }
1480
1481 public void addCountLocked(long[] counts, boolean isRunning) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001482 if (counts == null) {
1483 return;
1484 }
Sudheer Shankae544d162017-12-28 17:06:20 -08001485 if (isRunning) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001486 if (mCounts == null) {
1487 mCounts = new long[counts.length];
1488 }
1489 for (int i = 0; i < counts.length; ++i) {
1490 mCounts[i] += counts[i];
1491 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001492 }
1493 }
1494
Sudheer Shankab8ad5942017-08-08 12:16:09 -07001495 public int getSize() {
1496 return mCounts == null ? 0 : mCounts.length;
1497 }
1498
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001499 /**
1500 * Clear state of this counter.
1501 */
Hui Yu8e88e952018-07-23 17:59:59 -07001502 @Override
1503 public boolean reset(boolean detachIfReset) {
Mike Ma99e57c32018-03-15 14:40:37 -07001504 if (mCounts != null) {
1505 Arrays.fill(mCounts, 0);
1506 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001507 if (detachIfReset) {
1508 detach();
1509 }
Hui Yu8e88e952018-07-23 17:59:59 -07001510 return true;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001511 }
1512
Hui Yu8e88e952018-07-23 17:59:59 -07001513 @Override
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001514 public void detach() {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001515 mTimeBase.remove(this);
1516 }
1517
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001518 private void writeSummaryToParcelLocked(Parcel out) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001519 out.writeLongArray(mCounts);
1520 }
1521
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001522 private void readSummaryFromParcelLocked(Parcel in) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001523 mCounts = in.createLongArray();
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001524 }
1525
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001526 public static void writeToParcel(Parcel out, LongSamplingCounterArray counterArray) {
1527 if (counterArray != null) {
1528 out.writeInt(1);
1529 counterArray.writeToParcel(out);
1530 } else {
1531 out.writeInt(0);
1532 }
1533 }
1534
1535 public static LongSamplingCounterArray readFromParcel(Parcel in, TimeBase timeBase) {
1536 if (in.readInt() != 0) {
1537 return new LongSamplingCounterArray(timeBase, in);
1538 } else {
1539 return null;
1540 }
1541 }
1542
1543 public static void writeSummaryToParcelLocked(Parcel out,
1544 LongSamplingCounterArray counterArray) {
1545 if (counterArray != null) {
1546 out.writeInt(1);
1547 counterArray.writeSummaryToParcelLocked(out);
1548 } else {
1549 out.writeInt(0);
1550 }
1551 }
1552
1553 public static LongSamplingCounterArray readSummaryFromParcelLocked(Parcel in,
1554 TimeBase timeBase) {
1555 if (in.readInt() != 0) {
1556 final LongSamplingCounterArray counterArray
1557 = new LongSamplingCounterArray(timeBase);
1558 counterArray.readSummaryFromParcelLocked(in);
1559 return counterArray;
1560 } else {
1561 return null;
1562 }
1563 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001564 }
1565
Mike Ma561a8d92018-03-20 18:24:05 -07001566 @VisibleForTesting
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001567 public static class LongSamplingCounter extends LongCounter implements TimeBaseObs {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001568 final TimeBase mTimeBase;
Bookatz1371b9a2019-03-15 11:37:02 -07001569 private long mCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001570
Mike Ma561a8d92018-03-20 18:24:05 -07001571 public LongSamplingCounter(TimeBase timeBase, Parcel in) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001572 mTimeBase = timeBase;
Sudheer Shankac57729a2018-02-09 15:44:42 -08001573 mCount = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001574 timeBase.add(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001575 }
1576
Mike Ma561a8d92018-03-20 18:24:05 -07001577 public LongSamplingCounter(TimeBase timeBase) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001578 mTimeBase = timeBase;
1579 timeBase.add(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001580 }
1581
1582 public void writeToParcel(Parcel out) {
1583 out.writeLong(mCount);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001584 }
1585
1586 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001587 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001588 }
1589
1590 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001591 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001592 }
1593
1594 public long getCountLocked(int which) {
Mike Ma99e57c32018-03-15 14:40:37 -07001595 return mCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001596 }
1597
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001598 @Override
1599 public void logState(Printer pw, String prefix) {
Bookatz1371b9a2019-03-15 11:37:02 -07001600 pw.println(prefix + "mCount=" + mCount);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001601 }
1602
Mike Ma561a8d92018-03-20 18:24:05 -07001603 public void addCountLocked(long count) {
Bookatz1371b9a2019-03-15 11:37:02 -07001604 addCountLocked(count, mTimeBase.isRunning());
Sudheer Shankac57729a2018-02-09 15:44:42 -08001605 }
1606
Mike Ma561a8d92018-03-20 18:24:05 -07001607 public void addCountLocked(long count, boolean isRunning) {
Mike Ma561a8d92018-03-20 18:24:05 -07001608 if (isRunning) {
Bookatz1371b9a2019-03-15 11:37:02 -07001609 mCount += count;
Mike Ma561a8d92018-03-20 18:24:05 -07001610 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001611 }
1612
1613 /**
1614 * Clear state of this counter.
1615 */
Hui Yu8e88e952018-07-23 17:59:59 -07001616 @Override
1617 public boolean reset(boolean detachIfReset) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001618 mCount = 0;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001619 if (detachIfReset) {
1620 detach();
1621 }
Hui Yu8e88e952018-07-23 17:59:59 -07001622 return true;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001623 }
1624
Hui Yu8e88e952018-07-23 17:59:59 -07001625 @Override
Mike Ma561a8d92018-03-20 18:24:05 -07001626 public void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001627 mTimeBase.remove(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001628 }
1629
Mike Ma561a8d92018-03-20 18:24:05 -07001630 public void writeSummaryFromParcelLocked(Parcel out) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001631 out.writeLong(mCount);
1632 }
1633
Mike Ma561a8d92018-03-20 18:24:05 -07001634 public void readSummaryFromParcelLocked(Parcel in) {
Mike Ma99e57c32018-03-15 14:40:37 -07001635 mCount = in.readLong();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001636 }
1637 }
1638
Dianne Hackborn617f8772009-03-31 15:04:46 -07001639 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 * State for keeping track of timing information.
1641 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001642 public static abstract class Timer extends BatteryStats.Timer implements TimeBaseObs {
Joe Onoratoabded112016-02-08 16:49:39 -08001643 protected final Clocks mClocks;
1644 protected final int mType;
1645 protected final TimeBase mTimeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001646
Joe Onoratoabded112016-02-08 16:49:39 -08001647 protected int mCount;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001648
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 // Times are in microseconds for better accuracy when dividing by the
1650 // lock count, and are in "battery realtime" units.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001651
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 /**
1653 * The total time we have accumulated since the start of the original
1654 * boot, to the last time something interesting happened in the
1655 * current run.
1656 */
Joe Onoratoabded112016-02-08 16:49:39 -08001657 protected long mTotalTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001658
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07001660 * The total time this timer has been running until the latest mark has been set.
1661 * Subtract this from mTotalTime to get the time spent running since the mark was set.
1662 */
Joe Onoratoabded112016-02-08 16:49:39 -08001663 protected long mTimeBeforeMark;
Adam Lesinskie08af192015-03-25 16:42:59 -07001664
1665 /**
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001666 * Constructs from a parcel.
1667 * @param type
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001668 * @param timeBase
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001669 * @param in
1670 */
Joe Onoratoabded112016-02-08 16:49:39 -08001671 public Timer(Clocks clocks, int type, TimeBase timeBase, Parcel in) {
1672 mClocks = clocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 mType = type;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001674 mTimeBase = timeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 mCount = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 mTotalTime = in.readLong();
Adam Lesinskie08af192015-03-25 16:42:59 -07001678 mTimeBeforeMark = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001679 timeBase.add(this);
Dianne Hackborn29325132014-05-21 15:01:03 -07001680 if (DEBUG) Log.i(TAG, "**** READ TIMER #" + mType + ": mTotalTime=" + mTotalTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 }
1682
Joe Onoratoabded112016-02-08 16:49:39 -08001683 public Timer(Clocks clocks, int type, TimeBase timeBase) {
1684 mClocks = clocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 mType = type;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001686 mTimeBase = timeBase;
1687 timeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 }
Evan Millarc64edde2009-04-18 12:26:32 -07001689
Mike Ma99e57c32018-03-15 14:40:37 -07001690 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
1691 if (DEBUG) {
1692 Log.i(TAG, "**** WRITING TIMER #" + mType + ": mTotalTime="
1693 + computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)));
1694 }
1695 out.writeInt(computeCurrentCountLocked());
1696 out.writeLong(computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)));
1697 out.writeLong(mTimeBeforeMark);
1698 }
1699
Evan Millarc64edde2009-04-18 12:26:32 -07001700 protected abstract long computeRunTimeLocked(long curBatteryRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001701
Evan Millarc64edde2009-04-18 12:26:32 -07001702 protected abstract int computeCurrentCountLocked();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001703
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001704 /**
1705 * Clear state of this timer. Returns true if the timer is inactive
1706 * so can be completely dropped.
1707 */
Hui Yu8e88e952018-07-23 17:59:59 -07001708 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08001709 public boolean reset(boolean detachIfReset) {
Mike Ma99e57c32018-03-15 14:40:37 -07001710 mTotalTime = mTimeBeforeMark = 0;
1711 mCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001712 if (detachIfReset) {
1713 detach();
1714 }
1715 return true;
1716 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001717
Hui Yu8e88e952018-07-23 17:59:59 -07001718 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08001719 public void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001720 mTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001721 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001722
Adam Lesinskie08af192015-03-25 16:42:59 -07001723 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001724 public void onTimeStarted(long elapsedRealtime, long timeBaseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 }
1726
Adam Lesinskie08af192015-03-25 16:42:59 -07001727 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001728 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Evan Millarc64edde2009-04-18 12:26:32 -07001729 if (DEBUG && mType < 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001730 Log.v(TAG, "plug #" + mType + ": realtime=" + baseRealtime
Evan Millarc64edde2009-04-18 12:26:32 -07001731 + " old mTotalTime=" + mTotalTime);
1732 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001733 mTotalTime = computeRunTimeLocked(baseRealtime);
Evan Millarc64edde2009-04-18 12:26:32 -07001734 mCount = computeCurrentCountLocked();
1735 if (DEBUG && mType < 0) {
Mike Ma99e57c32018-03-15 14:40:37 -07001736 Log.v(TAG, "plug #" + mType + ": new mTotalTime=" + mTotalTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 }
1738 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 /**
1741 * Writes a possibly null Timer to a Parcel.
1742 *
1743 * @param out the Parcel to be written to.
1744 * @param timer a Timer, or null.
1745 */
Mathew Inwoodaf972c82018-08-20 14:13:20 +01001746 @UnsupportedAppUsage
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001747 public static void writeTimerToParcel(Parcel out, Timer timer, long elapsedRealtimeUs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 if (timer == null) {
1749 out.writeInt(0); // indicates null
1750 return;
1751 }
1752 out.writeInt(1); // indicates non-null
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001753 timer.writeToParcel(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 }
1755
1756 @Override
Mathew Inwoodaf972c82018-08-20 14:13:20 +01001757 @UnsupportedAppUsage
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001758 public long getTotalTimeLocked(long elapsedRealtimeUs, int which) {
Mike Ma99e57c32018-03-15 14:40:37 -07001759 return computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 }
1761
1762 @Override
Mathew Inwoodaf972c82018-08-20 14:13:20 +01001763 @UnsupportedAppUsage
Evan Millarc64edde2009-04-18 12:26:32 -07001764 public int getCountLocked(int which) {
Mike Ma99e57c32018-03-15 14:40:37 -07001765 return computeCurrentCountLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 }
1767
Adam Lesinskie08af192015-03-25 16:42:59 -07001768 @Override
1769 public long getTimeSinceMarkLocked(long elapsedRealtimeUs) {
1770 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1771 return val - mTimeBeforeMark;
1772 }
1773
1774 @Override
Dianne Hackborn627bba72009-03-24 22:32:56 -07001775 public void logState(Printer pw, String prefix) {
Mike Ma99e57c32018-03-15 14:40:37 -07001776 pw.println(prefix + "mCount=" + mCount);
1777 pw.println(prefix + "mTotalTime=" + mTotalTime);
Evan Millarc64edde2009-04-18 12:26:32 -07001778 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001779
1780
Joe Onoratoabded112016-02-08 16:49:39 -08001781 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001782 long runTime = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1783 out.writeLong(runTime);
Adam Lesinski98f0d462016-04-19 16:46:20 -07001784 out.writeInt(computeCurrentCountLocked());
Evan Millarc64edde2009-04-18 12:26:32 -07001785 }
1786
Joe Onoratoabded112016-02-08 16:49:39 -08001787 public void readSummaryFromParcelLocked(Parcel in) {
Evan Millarc64edde2009-04-18 12:26:32 -07001788 // Multiply by 1000 for backwards compatibility
Mike Ma99e57c32018-03-15 14:40:37 -07001789 mTotalTime = in.readLong();
1790 mCount = in.readInt();
Adam Lesinskie08af192015-03-25 16:42:59 -07001791 // When reading the summary, we set the mark to be the latest information.
1792 mTimeBeforeMark = mTotalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001793 }
1794 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001795
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001796 /**
1797 * A counter meant to accept monotonically increasing values to its {@link #update(long, int)}
1798 * method. The state of the timer according to its {@link TimeBase} will determine how much
1799 * of the value is recorded.
1800 *
1801 * If the value being recorded resets, {@link #endSample()} can be called in order to
1802 * account for the change. If the value passed in to {@link #update(long, int)} decreased
1803 * between calls, the {@link #endSample()} is automatically called and the new value is
1804 * expected to increase monotonically from that point on.
1805 */
Joe Onoratoabded112016-02-08 16:49:39 -08001806 public static class SamplingTimer extends Timer {
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001807
Evan Millarc64edde2009-04-18 12:26:32 -07001808 /**
1809 * The most recent reported count from /proc/wakelocks.
1810 */
1811 int mCurrentReportedCount;
1812
1813 /**
1814 * The reported count from /proc/wakelocks when unplug() was last
1815 * called.
1816 */
1817 int mUnpluggedReportedCount;
1818
1819 /**
1820 * The most recent reported total_time from /proc/wakelocks.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001821 */
Evan Millarc64edde2009-04-18 12:26:32 -07001822 long mCurrentReportedTotalTime;
1823
1824
1825 /**
1826 * The reported total_time from /proc/wakelocks when unplug() was last
1827 * called.
1828 */
1829 long mUnpluggedReportedTotalTime;
1830
1831 /**
1832 * Whether we are currently in a discharge cycle.
1833 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001834 boolean mTimeBaseRunning;
Evan Millarc64edde2009-04-18 12:26:32 -07001835
1836 /**
1837 * Whether we are currently recording reported values.
1838 */
1839 boolean mTrackingReportedValues;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001840
Evan Millarc64edde2009-04-18 12:26:32 -07001841 /*
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001842 * A sequence counter, incremented once for each update of the stats.
Evan Millarc64edde2009-04-18 12:26:32 -07001843 */
1844 int mUpdateVersion;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001845
Adam Lesinski98f0d462016-04-19 16:46:20 -07001846 @VisibleForTesting
1847 public SamplingTimer(Clocks clocks, TimeBase timeBase, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08001848 super(clocks, 0, timeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -07001849 mCurrentReportedCount = in.readInt();
1850 mUnpluggedReportedCount = in.readInt();
1851 mCurrentReportedTotalTime = in.readLong();
1852 mUnpluggedReportedTotalTime = in.readLong();
1853 mTrackingReportedValues = in.readInt() == 1;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001854 mTimeBaseRunning = timeBase.isRunning();
Evan Millarc64edde2009-04-18 12:26:32 -07001855 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001856
Adam Lesinski98f0d462016-04-19 16:46:20 -07001857 @VisibleForTesting
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001858 public SamplingTimer(Clocks clocks, TimeBase timeBase) {
Joe Onoratoabded112016-02-08 16:49:39 -08001859 super(clocks, 0, timeBase);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001860 mTrackingReportedValues = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001861 mTimeBaseRunning = timeBase.isRunning();
Evan Millarc64edde2009-04-18 12:26:32 -07001862 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001863
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001864 /**
1865 * Ends the current sample, allowing subsequent values to {@link #update(long, int)} to
1866 * be less than the values used for a previous invocation.
1867 */
1868 public void endSample() {
1869 mTotalTime = computeRunTimeLocked(0 /* unused by us */);
1870 mCount = computeCurrentCountLocked();
1871 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime = 0;
1872 mUnpluggedReportedCount = mCurrentReportedCount = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001873 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001874
Evan Millarc64edde2009-04-18 12:26:32 -07001875 public void setUpdateVersion(int version) {
1876 mUpdateVersion = version;
1877 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001878
Evan Millarc64edde2009-04-18 12:26:32 -07001879 public int getUpdateVersion() {
1880 return mUpdateVersion;
1881 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001882
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001883 /**
1884 * Updates the current recorded values. These are meant to be monotonically increasing
1885 * and cumulative. If you are dealing with deltas, use {@link #add(long, int)}.
1886 *
1887 * If the values being recorded have been reset, the monotonically increasing requirement
1888 * will be broken. In this case, {@link #endSample()} is automatically called and
1889 * the total value of totalTime and count are recorded, starting a new monotonically
1890 * increasing sample.
1891 *
1892 * @param totalTime total time of sample in microseconds.
1893 * @param count total number of times the event being sampled occurred.
1894 */
1895 public void update(long totalTime, int count) {
1896 if (mTimeBaseRunning && !mTrackingReportedValues) {
Evan Millarc64edde2009-04-18 12:26:32 -07001897 // Updating the reported value for the first time.
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001898 mUnpluggedReportedTotalTime = totalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001899 mUnpluggedReportedCount = count;
Evan Millarc64edde2009-04-18 12:26:32 -07001900 }
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001901
1902 mTrackingReportedValues = true;
1903
1904 if (totalTime < mCurrentReportedTotalTime || count < mCurrentReportedCount) {
1905 endSample();
1906 }
1907
1908 mCurrentReportedTotalTime = totalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001909 mCurrentReportedCount = count;
1910 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001911
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001912 /**
1913 * Adds deltaTime and deltaCount to the current sample.
1914 *
1915 * @param deltaTime additional time recorded since the last sampled event, in microseconds.
1916 * @param deltaCount additional number of times the event being sampled occurred.
1917 */
1918 public void add(long deltaTime, int deltaCount) {
1919 update(mCurrentReportedTotalTime + deltaTime, mCurrentReportedCount + deltaCount);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07001920 }
1921
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001922 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001923 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
1924 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime);
Evan Millarc64edde2009-04-18 12:26:32 -07001925 if (mTrackingReportedValues) {
1926 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime;
1927 mUnpluggedReportedCount = mCurrentReportedCount;
1928 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001929 mTimeBaseRunning = true;
Evan Millarc64edde2009-04-18 12:26:32 -07001930 }
1931
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001932 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001933 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
1934 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
1935 mTimeBaseRunning = false;
Evan Millarc64edde2009-04-18 12:26:32 -07001936 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001937
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001938 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001939 public void logState(Printer pw, String prefix) {
1940 super.logState(pw, prefix);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001941 pw.println(prefix + "mCurrentReportedCount=" + mCurrentReportedCount
Evan Millarc64edde2009-04-18 12:26:32 -07001942 + " mUnpluggedReportedCount=" + mUnpluggedReportedCount
1943 + " mCurrentReportedTotalTime=" + mCurrentReportedTotalTime
1944 + " mUnpluggedReportedTotalTime=" + mUnpluggedReportedTotalTime);
1945 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001946
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001947 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001948 protected long computeRunTimeLocked(long curBatteryRealtime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001949 return mTotalTime + (mTimeBaseRunning && mTrackingReportedValues
Evan Millarc64edde2009-04-18 12:26:32 -07001950 ? mCurrentReportedTotalTime - mUnpluggedReportedTotalTime : 0);
1951 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001952
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001953 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001954 protected int computeCurrentCountLocked() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001955 return mCount + (mTimeBaseRunning && mTrackingReportedValues
Evan Millarc64edde2009-04-18 12:26:32 -07001956 ? mCurrentReportedCount - mUnpluggedReportedCount : 0);
1957 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001958
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001959 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001960 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
1961 super.writeToParcel(out, elapsedRealtimeUs);
Evan Millarc64edde2009-04-18 12:26:32 -07001962 out.writeInt(mCurrentReportedCount);
1963 out.writeInt(mUnpluggedReportedCount);
1964 out.writeLong(mCurrentReportedTotalTime);
1965 out.writeLong(mUnpluggedReportedTotalTime);
1966 out.writeInt(mTrackingReportedValues ? 1 : 0);
1967 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001968
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001969 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08001970 public boolean reset(boolean detachIfReset) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001971 super.reset(detachIfReset);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001972 mTrackingReportedValues = false;
1973 mUnpluggedReportedTotalTime = 0;
1974 mUnpluggedReportedCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001975 return true;
1976 }
Evan Millarc64edde2009-04-18 12:26:32 -07001977 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001978
Evan Millarc64edde2009-04-18 12:26:32 -07001979 /**
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001980 * A timer that increments in batches. It does not run for durations, but just jumps
1981 * for a pre-determined amount.
1982 */
Joe Onoratoabded112016-02-08 16:49:39 -08001983 public static class BatchTimer extends Timer {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001984 final Uid mUid;
1985
1986 /**
1987 * The last time at which we updated the timer. This is in elapsed realtime microseconds.
1988 */
1989 long mLastAddedTime;
1990
1991 /**
1992 * The last duration that we added to the timer. This is in microseconds.
1993 */
1994 long mLastAddedDuration;
1995
1996 /**
1997 * Whether we are currently in a discharge cycle.
1998 */
1999 boolean mInDischarge;
2000
Joe Onoratoabded112016-02-08 16:49:39 -08002001 BatchTimer(Clocks clocks, Uid uid, int type, TimeBase timeBase, Parcel in) {
2002 super(clocks, type, timeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002003 mUid = uid;
2004 mLastAddedTime = in.readLong();
2005 mLastAddedDuration = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002006 mInDischarge = timeBase.isRunning();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002007 }
2008
Joe Onoratoabded112016-02-08 16:49:39 -08002009 BatchTimer(Clocks clocks, Uid uid, int type, TimeBase timeBase) {
2010 super(clocks, type, timeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002011 mUid = uid;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002012 mInDischarge = timeBase.isRunning();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002013 }
2014
2015 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002016 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2017 super.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002018 out.writeLong(mLastAddedTime);
2019 out.writeLong(mLastAddedDuration);
2020 }
2021
2022 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002023 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Joe Onoratoabded112016-02-08 16:49:39 -08002024 recomputeLastDuration(mClocks.elapsedRealtime() * 1000, false);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002025 mInDischarge = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002026 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002027 }
2028
2029 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002030 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002031 recomputeLastDuration(elapsedRealtime, false);
2032 mInDischarge = true;
2033 // If we are still within the last added duration, then re-added whatever remains.
2034 if (mLastAddedTime == elapsedRealtime) {
2035 mTotalTime += mLastAddedDuration;
2036 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002037 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002038 }
2039
2040 @Override
2041 public void logState(Printer pw, String prefix) {
2042 super.logState(pw, prefix);
2043 pw.println(prefix + "mLastAddedTime=" + mLastAddedTime
2044 + " mLastAddedDuration=" + mLastAddedDuration);
2045 }
2046
2047 private long computeOverage(long curTime) {
2048 if (mLastAddedTime > 0) {
Mike Ma99e57c32018-03-15 14:40:37 -07002049 return mLastAddedDuration - curTime;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002050 }
2051 return 0;
2052 }
2053
2054 private void recomputeLastDuration(long curTime, boolean abort) {
2055 final long overage = computeOverage(curTime);
2056 if (overage > 0) {
2057 // Aborting before the duration ran out -- roll back the remaining
2058 // duration. Only do this if currently discharging; otherwise we didn't
2059 // actually add the time.
2060 if (mInDischarge) {
2061 mTotalTime -= overage;
2062 }
2063 if (abort) {
2064 mLastAddedTime = 0;
2065 } else {
2066 mLastAddedTime = curTime;
2067 mLastAddedDuration -= overage;
2068 }
2069 }
2070 }
2071
2072 public void addDuration(BatteryStatsImpl stats, long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08002073 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002074 recomputeLastDuration(now, true);
2075 mLastAddedTime = now;
2076 mLastAddedDuration = durationMillis * 1000;
2077 if (mInDischarge) {
2078 mTotalTime += mLastAddedDuration;
2079 mCount++;
2080 }
2081 }
2082
2083 public void abortLastDuration(BatteryStatsImpl stats) {
Joe Onoratoabded112016-02-08 16:49:39 -08002084 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002085 recomputeLastDuration(now, true);
2086 }
2087
2088 @Override
2089 protected int computeCurrentCountLocked() {
2090 return mCount;
2091 }
2092
2093 @Override
2094 protected long computeRunTimeLocked(long curBatteryRealtime) {
Joe Onoratoabded112016-02-08 16:49:39 -08002095 final long overage = computeOverage(mClocks.elapsedRealtime() * 1000);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002096 if (overage > 0) {
2097 return mTotalTime = overage;
2098 }
2099 return mTotalTime;
2100 }
2101
2102 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002103 public boolean reset(boolean detachIfReset) {
2104 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002105 recomputeLastDuration(now, true);
2106 boolean stillActive = mLastAddedTime == now;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002107 super.reset(!stillActive && detachIfReset);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002108 return !stillActive;
2109 }
2110 }
2111
Joe Onorato92fd23f2016-07-25 11:18:42 -07002112
2113 /**
2114 * A StopwatchTimer that also tracks the total and max individual
2115 * time spent active according to the given timebase. Whereas
2116 * StopwatchTimer apportions the time amongst all in the pool,
2117 * the total and max durations are not apportioned.
2118 */
2119 public static class DurationTimer extends StopwatchTimer {
2120 /**
2121 * The time (in ms) that the timer was last acquired or the time base
2122 * last (re-)started. Increasing the nesting depth does not reset this time.
2123 *
2124 * -1 if the timer is currently not running or the time base is not running.
2125 *
2126 * If written to a parcel, the start time is reset, as is mNesting in the base class
2127 * StopwatchTimer.
2128 */
2129 long mStartTimeMs = -1;
2130
2131 /**
Bookatz867c0d72017-03-07 18:23:42 -08002132 * The longest time period (in ms) that the timer has been active. Not pooled.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002133 */
2134 long mMaxDurationMs;
2135
2136 /**
Bookatz867c0d72017-03-07 18:23:42 -08002137 * The time (in ms) that that the timer has been active since most recent
2138 * stopRunningLocked() or reset(). Not pooled.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002139 */
2140 long mCurrentDurationMs;
2141
Bookatz867c0d72017-03-07 18:23:42 -08002142 /**
2143 * The total time (in ms) that that the timer has been active since most recent reset()
2144 * prior to the current startRunningLocked. This is the sum of all past currentDurations
2145 * (but not including the present currentDuration) since reset. Not pooled.
2146 */
2147 long mTotalDurationMs;
2148
Joe Onorato92fd23f2016-07-25 11:18:42 -07002149 public DurationTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2150 TimeBase timeBase, Parcel in) {
2151 super(clocks, uid, type, timerPool, timeBase, in);
2152 mMaxDurationMs = in.readLong();
Bookatz867c0d72017-03-07 18:23:42 -08002153 mTotalDurationMs = in.readLong();
jackqdyulei610a0a02017-08-09 14:02:01 -07002154 mCurrentDurationMs = in.readLong();
Joe Onorato92fd23f2016-07-25 11:18:42 -07002155 }
2156
2157 public DurationTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2158 TimeBase timeBase) {
2159 super(clocks, uid, type, timerPool, timeBase);
2160 }
2161
2162 @Override
2163 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2164 super.writeToParcel(out, elapsedRealtimeUs);
Kweku Adams47db5a82016-12-09 19:04:50 -08002165 out.writeLong(getMaxDurationMsLocked(elapsedRealtimeUs / 1000));
jackqdyulei610a0a02017-08-09 14:02:01 -07002166 out.writeLong(mTotalDurationMs);
2167 out.writeLong(getCurrentDurationMsLocked(elapsedRealtimeUs / 1000));
Joe Onorato92fd23f2016-07-25 11:18:42 -07002168 }
2169
2170 /**
2171 * Write the summary to the parcel.
2172 *
2173 * Since the time base is probably meaningless after we come back, reading
2174 * from this will have the effect of stopping the timer. So here all we write
Bookatz867c0d72017-03-07 18:23:42 -08002175 * is the max and total durations.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002176 */
2177 @Override
2178 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
2179 super.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
Kweku Adams47db5a82016-12-09 19:04:50 -08002180 out.writeLong(getMaxDurationMsLocked(elapsedRealtimeUs / 1000));
Bookatz867c0d72017-03-07 18:23:42 -08002181 out.writeLong(getTotalDurationMsLocked(elapsedRealtimeUs / 1000));
Joe Onorato92fd23f2016-07-25 11:18:42 -07002182 }
2183
2184 /**
2185 * Read the summary parcel.
2186 *
2187 * Has the side effect of stopping the timer.
2188 */
2189 @Override
2190 public void readSummaryFromParcelLocked(Parcel in) {
2191 super.readSummaryFromParcelLocked(in);
2192 mMaxDurationMs = in.readLong();
Bookatz867c0d72017-03-07 18:23:42 -08002193 mTotalDurationMs = in.readLong();
Joe Onorato92fd23f2016-07-25 11:18:42 -07002194 mStartTimeMs = -1;
2195 mCurrentDurationMs = 0;
2196 }
2197
2198 /**
2199 * The TimeBase time started (again).
2200 *
2201 * If the timer is also running, store the start time.
2202 */
2203 public void onTimeStarted(long elapsedRealtimeUs, long baseUptime, long baseRealtime) {
2204 super.onTimeStarted(elapsedRealtimeUs, baseUptime, baseRealtime);
2205 if (mNesting > 0) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002206 mStartTimeMs = baseRealtime / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002207 }
2208 }
2209
2210 /**
2211 * The TimeBase stopped running.
2212 *
2213 * If the timer is running, add the duration into mCurrentDurationMs.
2214 */
2215 @Override
Kweku Adams47db5a82016-12-09 19:04:50 -08002216 public void onTimeStopped(long elapsedRealtimeUs, long baseUptime, long baseRealtimeUs) {
2217 super.onTimeStopped(elapsedRealtimeUs, baseUptime, baseRealtimeUs);
Joe Onorato92fd23f2016-07-25 11:18:42 -07002218 if (mNesting > 0) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002219 // baseRealtimeUs has already been converted to the timebase's realtime.
2220 mCurrentDurationMs += (baseRealtimeUs / 1000) - mStartTimeMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002221 }
2222 mStartTimeMs = -1;
2223 }
2224
2225 @Override
2226 public void logState(Printer pw, String prefix) {
2227 super.logState(pw, prefix);
2228 }
2229
2230 @Override
2231 public void startRunningLocked(long elapsedRealtimeMs) {
2232 super.startRunningLocked(elapsedRealtimeMs);
2233 if (mNesting == 1 && mTimeBase.isRunning()) {
2234 // Just started
Kweku Adams47db5a82016-12-09 19:04:50 -08002235 mStartTimeMs = mTimeBase.getRealtime(elapsedRealtimeMs * 1000) / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002236 }
2237 }
2238
2239 /**
2240 * Decrements the mNesting ref-count on this timer.
2241 *
2242 * If it actually stopped (mNesting went to 0), then possibly update
2243 * mMaxDuration if the current duration was the longest ever.
2244 */
2245 @Override
2246 public void stopRunningLocked(long elapsedRealtimeMs) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002247 if (mNesting == 1) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07002248 final long durationMs = getCurrentDurationMsLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002249 mTotalDurationMs += durationMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002250 if (durationMs > mMaxDurationMs) {
2251 mMaxDurationMs = durationMs;
2252 }
2253 mStartTimeMs = -1;
2254 mCurrentDurationMs = 0;
2255 }
Kweku Adams47db5a82016-12-09 19:04:50 -08002256 // super method decrements mNesting, which getCurrentDurationMsLocked relies on,
2257 // so call super.stopRunningLocked after calling getCurrentDurationMsLocked.
2258 super.stopRunningLocked(elapsedRealtimeMs);
Joe Onorato92fd23f2016-07-25 11:18:42 -07002259 }
2260
2261 @Override
2262 public boolean reset(boolean detachIfReset) {
2263 boolean result = super.reset(detachIfReset);
2264 mMaxDurationMs = 0;
Bookatz867c0d72017-03-07 18:23:42 -08002265 mTotalDurationMs = 0;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002266 mCurrentDurationMs = 0;
2267 if (mNesting > 0) {
Mike Ma99e57c32018-03-15 14:40:37 -07002268 mStartTimeMs = mTimeBase.getRealtime(mClocks.elapsedRealtime() * 1000) / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002269 } else {
2270 mStartTimeMs = -1;
2271 }
2272 return result;
2273 }
2274
2275 /**
2276 * Returns the max duration that this timer has ever seen.
2277 *
2278 * Note that this time is NOT split between the timers in the timer group that
2279 * this timer is attached to. It is the TOTAL time.
2280 */
2281 @Override
2282 public long getMaxDurationMsLocked(long elapsedRealtimeMs) {
2283 if (mNesting > 0) {
2284 final long durationMs = getCurrentDurationMsLocked(elapsedRealtimeMs);
2285 if (durationMs > mMaxDurationMs) {
2286 return durationMs;
2287 }
2288 }
2289 return mMaxDurationMs;
2290 }
2291
2292 /**
2293 * Returns the time since the timer was started.
Bookatz867c0d72017-03-07 18:23:42 -08002294 * Returns 0 if the timer is not currently running.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002295 *
2296 * Note that this time is NOT split between the timers in the timer group that
2297 * this timer is attached to. It is the TOTAL time.
jackqdyulei610a0a02017-08-09 14:02:01 -07002298 *
2299 * Note that if running timer is parceled and unparceled, this method will return
2300 * current duration value at the time of parceling even though timer may not be
2301 * currently running.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002302 */
2303 @Override
2304 public long getCurrentDurationMsLocked(long elapsedRealtimeMs) {
2305 long durationMs = mCurrentDurationMs;
Kweku Adams47db5a82016-12-09 19:04:50 -08002306 if (mNesting > 0 && mTimeBase.isRunning()) {
Mike Ma99e57c32018-03-15 14:40:37 -07002307 durationMs += (mTimeBase.getRealtime(elapsedRealtimeMs * 1000) / 1000)
Kweku Adams47db5a82016-12-09 19:04:50 -08002308 - mStartTimeMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002309 }
2310 return durationMs;
2311 }
Bookatz867c0d72017-03-07 18:23:42 -08002312
2313 /**
2314 * Returns the total cumulative duration that this timer has been on since reset().
2315 * If mTimerPool == null, this should be the same
2316 * as getTotalTimeLocked(elapsedRealtimeMs*1000, STATS_SINCE_CHARGED)/1000.
2317 *
2318 * Note that this time is NOT split between the timers in the timer group that
2319 * this timer is attached to. It is the TOTAL time. For this reason, if mTimerPool != null,
2320 * the result will not be equivalent to getTotalTimeLocked.
2321 */
2322 @Override
2323 public long getTotalDurationMsLocked(long elapsedRealtimeMs) {
2324 return mTotalDurationMs + getCurrentDurationMsLocked(elapsedRealtimeMs);
2325 }
Joe Onorato92fd23f2016-07-25 11:18:42 -07002326 }
2327
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002328 /**
Evan Millarc64edde2009-04-18 12:26:32 -07002329 * State for keeping track of timing information.
2330 */
Joe Onoratoabded112016-02-08 16:49:39 -08002331 public static class StopwatchTimer extends Timer {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002332 final Uid mUid;
Evan Millarc64edde2009-04-18 12:26:32 -07002333 final ArrayList<StopwatchTimer> mTimerPool;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002334
Evan Millarc64edde2009-04-18 12:26:32 -07002335 int mNesting;
2336
Evan Millarc64edde2009-04-18 12:26:32 -07002337 /**
2338 * The last time at which we updated the timer. If mNesting is > 0,
2339 * subtract this from the current battery time to find the amount of
2340 * time we have been running since we last computed an update.
2341 */
2342 long mUpdateTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002343
Evan Millarc64edde2009-04-18 12:26:32 -07002344 /**
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002345 * The total time at which the timer was acquired, to determine if it
Bookatzceebafe2017-04-06 11:59:13 -07002346 * was actually held for an interesting duration. If time base was not running when timer
2347 * was acquired, will be -1.
Evan Millarc64edde2009-04-18 12:26:32 -07002348 */
Bookatzceebafe2017-04-06 11:59:13 -07002349 long mAcquireTime = -1;
Evan Millarc64edde2009-04-18 12:26:32 -07002350
Amith Yamasanif37447b2009-10-08 18:28:01 -07002351 long mTimeout;
2352
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002353 /**
2354 * For partial wake locks, keep track of whether we are in the list
2355 * to consume CPU cycles.
2356 */
Sudheer Shanka38383232017-07-25 09:55:03 -07002357 @VisibleForTesting
2358 public boolean mInList;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002359
Joe Onoratoabded112016-02-08 16:49:39 -08002360 public StopwatchTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002361 TimeBase timeBase, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08002362 super(clocks, type, timeBase, in);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002363 mUid = uid;
Evan Millarc64edde2009-04-18 12:26:32 -07002364 mTimerPool = timerPool;
2365 mUpdateTime = in.readLong();
2366 }
2367
Joe Onoratoabded112016-02-08 16:49:39 -08002368 public StopwatchTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002369 TimeBase timeBase) {
Joe Onoratoabded112016-02-08 16:49:39 -08002370 super(clocks, type, timeBase);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002371 mUid = uid;
Evan Millarc64edde2009-04-18 12:26:32 -07002372 mTimerPool = timerPool;
2373 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002374
Joe Onoratoabded112016-02-08 16:49:39 -08002375 public void setTimeout(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07002376 mTimeout = timeout;
2377 }
2378
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002379 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2380 super.writeToParcel(out, elapsedRealtimeUs);
Evan Millarc64edde2009-04-18 12:26:32 -07002381 out.writeLong(mUpdateTime);
2382 }
2383
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002384 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Evan Millarc64edde2009-04-18 12:26:32 -07002385 if (mNesting > 0) {
2386 if (DEBUG && mType < 0) {
2387 Log.v(TAG, "old mUpdateTime=" + mUpdateTime);
2388 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002389 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
2390 mUpdateTime = baseRealtime;
Evan Millarc64edde2009-04-18 12:26:32 -07002391 if (DEBUG && mType < 0) {
2392 Log.v(TAG, "new mUpdateTime=" + mUpdateTime);
2393 }
2394 }
2395 }
2396
2397 public void logState(Printer pw, String prefix) {
2398 super.logState(pw, prefix);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07002399 pw.println(prefix + "mNesting=" + mNesting + " mUpdateTime=" + mUpdateTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002400 + " mAcquireTime=" + mAcquireTime);
2401 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002402
Joe Onoratoabded112016-02-08 16:49:39 -08002403 public void startRunningLocked(long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002404 if (mNesting++ == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002405 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002406 mUpdateTime = batteryRealtime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002407 if (mTimerPool != null) {
2408 // Accumulate time to all currently active timers before adding
2409 // this new one to the pool.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002410 refreshTimersLocked(batteryRealtime, mTimerPool, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002411 // Add this timer to the active pool
2412 mTimerPool.add(this);
2413 }
Bookatzceebafe2017-04-06 11:59:13 -07002414 if (mTimeBase.isRunning()) {
2415 // Increment the count
2416 mCount++;
2417 mAcquireTime = mTotalTime;
2418 } else {
2419 mAcquireTime = -1;
2420 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002421 if (DEBUG && mType < 0) {
2422 Log.v(TAG, "start #" + mType + ": mUpdateTime=" + mUpdateTime
2423 + " mTotalTime=" + mTotalTime + " mCount=" + mCount
2424 + " mAcquireTime=" + mAcquireTime);
2425 }
2426 }
2427 }
2428
Joe Onoratoabded112016-02-08 16:49:39 -08002429 public boolean isRunningLocked() {
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002430 return mNesting > 0;
2431 }
2432
Joe Onoratoabded112016-02-08 16:49:39 -08002433 public void stopRunningLocked(long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002434 // Ignore attempt to stop a timer that isn't running
2435 if (mNesting == 0) {
2436 return;
2437 }
2438 if (--mNesting == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002439 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002440 if (mTimerPool != null) {
2441 // Accumulate time to all active counters, scaled by the total
2442 // active in the pool, before taking this one out of the pool.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002443 refreshTimersLocked(batteryRealtime, mTimerPool, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002444 // Remove this timer from the active pool
2445 mTimerPool.remove(this);
2446 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002447 mNesting = 1;
2448 mTotalTime = computeRunTimeLocked(batteryRealtime);
2449 mNesting = 0;
2450 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002451
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002452 if (DEBUG && mType < 0) {
2453 Log.v(TAG, "stop #" + mType + ": mUpdateTime=" + mUpdateTime
2454 + " mTotalTime=" + mTotalTime + " mCount=" + mCount
2455 + " mAcquireTime=" + mAcquireTime);
2456 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002457
Bookatzceebafe2017-04-06 11:59:13 -07002458 if (mAcquireTime >= 0 && mTotalTime == mAcquireTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002459 // If there was no change in the time, then discard this
2460 // count. A somewhat cheezy strategy, but hey.
2461 mCount--;
2462 }
2463 }
2464 }
2465
Joe Onoratoabded112016-02-08 16:49:39 -08002466 public void stopAllRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07002467 if (mNesting > 0) {
2468 mNesting = 1;
2469 stopRunningLocked(elapsedRealtimeMs);
2470 }
2471 }
2472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002473 // Update the total time for all other running Timers with the same type as this Timer
2474 // due to a change in timer count
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002475 private static long refreshTimersLocked(long batteryRealtime,
2476 final ArrayList<StopwatchTimer> pool, StopwatchTimer self) {
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002477 long selfTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002478 final int N = pool.size();
2479 for (int i=N-1; i>= 0; i--) {
Evan Millarc64edde2009-04-18 12:26:32 -07002480 final StopwatchTimer t = pool.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002481 long heldTime = batteryRealtime - t.mUpdateTime;
2482 if (heldTime > 0) {
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002483 final long myTime = heldTime / N;
2484 if (t == self) {
2485 selfTime = myTime;
2486 }
2487 t.mTotalTime += myTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002488 }
2489 t.mUpdateTime = batteryRealtime;
2490 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002491 return selfTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002492 }
2493
Evan Millarc64edde2009-04-18 12:26:32 -07002494 @Override
2495 protected long computeRunTimeLocked(long curBatteryRealtime) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07002496 if (mTimeout > 0 && curBatteryRealtime > mUpdateTime + mTimeout) {
2497 curBatteryRealtime = mUpdateTime + mTimeout;
2498 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002499 return mTotalTime + (mNesting > 0
2500 ? (curBatteryRealtime - mUpdateTime)
2501 / (mTimerPool != null ? mTimerPool.size() : 1)
2502 : 0);
2503 }
2504
Evan Millarc64edde2009-04-18 12:26:32 -07002505 @Override
2506 protected int computeCurrentCountLocked() {
2507 return mCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002508 }
2509
Adam Lesinskie08af192015-03-25 16:42:59 -07002510 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002511 public boolean reset(boolean detachIfReset) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002512 boolean canDetach = mNesting <= 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002513 super.reset(canDetach && detachIfReset);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002514 if (mNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08002515 mUpdateTime = mTimeBase.getRealtime(mClocks.elapsedRealtime() * 1000);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002516 }
Bookatzceebafe2017-04-06 11:59:13 -07002517 mAcquireTime = -1; // to ensure mCount isn't decreased to -1 if timer is stopped later.
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002518 return canDetach;
2519 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002520
Adam Lesinskie08af192015-03-25 16:42:59 -07002521 @Override
Mathew Inwoodaf972c82018-08-20 14:13:20 +01002522 @UnsupportedAppUsage
Joe Onoratoabded112016-02-08 16:49:39 -08002523 public void detach() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002524 super.detach();
2525 if (mTimerPool != null) {
2526 mTimerPool.remove(this);
2527 }
2528 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002529
Adam Lesinskie08af192015-03-25 16:42:59 -07002530 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002531 public void readSummaryFromParcelLocked(Parcel in) {
Evan Millarc64edde2009-04-18 12:26:32 -07002532 super.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002533 mNesting = 0;
2534 }
Adam Lesinskie08af192015-03-25 16:42:59 -07002535
2536 /**
2537 * Set the mark so that we can query later for the total time the timer has
2538 * accumulated since this point. The timer can be running or not.
2539 *
2540 * @param elapsedRealtimeMs the current elapsed realtime in milliseconds.
2541 */
2542 public void setMark(long elapsedRealtimeMs) {
2543 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
2544 if (mNesting > 0) {
2545 // We are running.
2546 if (mTimerPool != null) {
2547 refreshTimersLocked(batteryRealtime, mTimerPool, this);
2548 } else {
2549 mTotalTime += batteryRealtime - mUpdateTime;
2550 mUpdateTime = batteryRealtime;
2551 }
2552 }
2553 mTimeBeforeMark = mTotalTime;
2554 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002555 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002556
Bookatz867c0d72017-03-07 18:23:42 -08002557 /**
2558 * State for keeping track of two DurationTimers with different TimeBases, presumably where one
2559 * TimeBase is effectively a subset of the other.
2560 */
Bookatzaa4594a2017-03-24 12:39:56 -07002561 public static class DualTimer extends DurationTimer {
2562 // This class both is a DurationTimer and also holds a second DurationTimer.
2563 // The main timer (this) typically tracks the total time. It may be pooled (but since it's a
2564 // durationTimer, it also has the unpooled getTotalDurationMsLocked() for
2565 // STATS_SINCE_CHARGED).
Bookatz867c0d72017-03-07 18:23:42 -08002566 // mSubTimer typically tracks only part of the total time, such as background time, as
2567 // determined by a subTimeBase. It is NOT pooled.
2568 private final DurationTimer mSubTimer;
2569
2570 /**
Bookatzaa4594a2017-03-24 12:39:56 -07002571 * Creates a DualTimer to hold a main timer (this) and a mSubTimer.
2572 * The main timer (this) is based on the given timeBase and timerPool.
Bookatz867c0d72017-03-07 18:23:42 -08002573 * The mSubTimer is based on the given subTimeBase. The mSubTimer is not pooled, even if
Bookatzaa4594a2017-03-24 12:39:56 -07002574 * the main timer is.
Bookatz867c0d72017-03-07 18:23:42 -08002575 */
2576 public DualTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2577 TimeBase timeBase, TimeBase subTimeBase, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07002578 super(clocks, uid, type, timerPool, timeBase, in);
Bookatz867c0d72017-03-07 18:23:42 -08002579 mSubTimer = new DurationTimer(clocks, uid, type, null, subTimeBase, in);
2580 }
2581
2582 /**
Bookatzaa4594a2017-03-24 12:39:56 -07002583 * Creates a DualTimer to hold a main timer (this) and a mSubTimer.
2584 * The main timer (this) is based on the given timeBase and timerPool.
Bookatz867c0d72017-03-07 18:23:42 -08002585 * The mSubTimer is based on the given subTimeBase. The mSubTimer is not pooled, even if
Bookatzaa4594a2017-03-24 12:39:56 -07002586 * the main timer is.
Bookatz867c0d72017-03-07 18:23:42 -08002587 */
2588 public DualTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2589 TimeBase timeBase, TimeBase subTimeBase) {
Bookatzaa4594a2017-03-24 12:39:56 -07002590 super(clocks, uid, type, timerPool, timeBase);
Bookatz867c0d72017-03-07 18:23:42 -08002591 mSubTimer = new DurationTimer(clocks, uid, type, null, subTimeBase);
2592 }
2593
Bookatz867c0d72017-03-07 18:23:42 -08002594 /** Get the secondary timer. */
Bookatzaa4594a2017-03-24 12:39:56 -07002595 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002596 public DurationTimer getSubTimer() {
2597 return mSubTimer;
2598 }
2599
Bookatzaa4594a2017-03-24 12:39:56 -07002600 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002601 public void startRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002602 super.startRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002603 mSubTimer.startRunningLocked(elapsedRealtimeMs);
2604 }
2605
Bookatzaa4594a2017-03-24 12:39:56 -07002606 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002607 public void stopRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002608 super.stopRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002609 mSubTimer.stopRunningLocked(elapsedRealtimeMs);
2610 }
2611
Bookatzaa4594a2017-03-24 12:39:56 -07002612 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002613 public void stopAllRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002614 super.stopAllRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002615 mSubTimer.stopAllRunningLocked(elapsedRealtimeMs);
2616 }
2617
Bookatzaa4594a2017-03-24 12:39:56 -07002618 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002619 public boolean reset(boolean detachIfReset) {
2620 boolean active = false;
Bookatz4a3eda92017-04-10 13:10:46 -07002621 // Do not detach the subTimer explicitly since that'll be done by DualTimer.detach().
2622 active |= !mSubTimer.reset(false);
Bookatzaa4594a2017-03-24 12:39:56 -07002623 active |= !super.reset(detachIfReset);
Bookatz867c0d72017-03-07 18:23:42 -08002624 return !active;
2625 }
2626
Bookatzaa4594a2017-03-24 12:39:56 -07002627 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002628 public void detach() {
Bookatz867c0d72017-03-07 18:23:42 -08002629 mSubTimer.detach();
Bookatz4a3eda92017-04-10 13:10:46 -07002630 super.detach();
Bookatz867c0d72017-03-07 18:23:42 -08002631 }
2632
Bookatzaa4594a2017-03-24 12:39:56 -07002633 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002634 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002635 super.writeToParcel(out, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08002636 mSubTimer.writeToParcel(out, elapsedRealtimeUs);
2637 }
2638
Bookatzaa4594a2017-03-24 12:39:56 -07002639 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002640 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002641 super.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08002642 mSubTimer.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
2643 }
2644
Bookatzaa4594a2017-03-24 12:39:56 -07002645 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002646 public void readSummaryFromParcelLocked(Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07002647 super.readSummaryFromParcelLocked(in);
Bookatz867c0d72017-03-07 18:23:42 -08002648 mSubTimer.readSummaryFromParcelLocked(in);
2649 }
2650 }
2651
2652
Dianne Hackbornd953c532014-08-16 18:17:38 -07002653 public abstract class OverflowArrayMap<T> {
2654 private static final String OVERFLOW_NAME = "*overflow*";
2655
Dianne Hackborn657153b2016-07-29 14:54:14 -07002656 final int mUid;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002657 final ArrayMap<String, T> mMap = new ArrayMap<>();
2658 T mCurOverflow;
2659 ArrayMap<String, MutableInt> mActiveOverflow;
Dianne Hackborn657153b2016-07-29 14:54:14 -07002660 long mLastOverflowTime;
2661 long mLastOverflowFinishTime;
2662 long mLastClearTime;
2663 long mLastCleanupTime;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002664
Dianne Hackborn657153b2016-07-29 14:54:14 -07002665 public OverflowArrayMap(int uid) {
2666 mUid = uid;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002667 }
2668
2669 public ArrayMap<String, T> getMap() {
2670 return mMap;
2671 }
2672
2673 public void clear() {
Dianne Hackborn657153b2016-07-29 14:54:14 -07002674 mLastClearTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002675 mMap.clear();
2676 mCurOverflow = null;
2677 mActiveOverflow = null;
2678 }
2679
2680 public void add(String name, T obj) {
Joe Onorato388fc332016-04-12 17:06:47 -07002681 if (name == null) {
2682 name = "";
2683 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002684 mMap.put(name, obj);
2685 if (OVERFLOW_NAME.equals(name)) {
2686 mCurOverflow = obj;
2687 }
2688 }
2689
2690 public void cleanup() {
Dianne Hackborn657153b2016-07-29 14:54:14 -07002691 mLastCleanupTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002692 if (mActiveOverflow != null) {
2693 if (mActiveOverflow.size() == 0) {
2694 mActiveOverflow = null;
2695 }
2696 }
2697 if (mActiveOverflow == null) {
2698 // There is no currently active overflow, so we should no longer have
2699 // an overflow entry.
2700 if (mMap.containsKey(OVERFLOW_NAME)) {
2701 Slog.wtf(TAG, "Cleaning up with no active overflow, but have overflow entry "
2702 + mMap.get(OVERFLOW_NAME));
2703 mMap.remove(OVERFLOW_NAME);
2704 }
2705 mCurOverflow = null;
2706 } else {
2707 // There is currently active overflow, so we should still have an overflow entry.
2708 if (mCurOverflow == null || !mMap.containsKey(OVERFLOW_NAME)) {
2709 Slog.wtf(TAG, "Cleaning up with active overflow, but no overflow entry: cur="
2710 + mCurOverflow + " map=" + mMap.get(OVERFLOW_NAME));
2711 }
2712 }
2713 }
2714
2715 public T startObject(String name) {
Joe Onorato388fc332016-04-12 17:06:47 -07002716 if (name == null) {
2717 name = "";
2718 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002719 T obj = mMap.get(name);
2720 if (obj != null) {
2721 return obj;
2722 }
2723
2724 // No object exists for the given name, but do we currently have it
2725 // running as part of the overflow?
2726 if (mActiveOverflow != null) {
2727 MutableInt over = mActiveOverflow.get(name);
2728 if (over != null) {
2729 // We are already actively counting this name in the overflow object.
2730 obj = mCurOverflow;
2731 if (obj == null) {
2732 // Shouldn't be here, but we'll try to recover.
2733 Slog.wtf(TAG, "Have active overflow " + name + " but null overflow");
2734 obj = mCurOverflow = instantiateObject();
2735 mMap.put(OVERFLOW_NAME, obj);
2736 }
2737 over.value++;
2738 return obj;
2739 }
2740 }
2741
2742 // No object exists for given name nor in the overflow; we need to make
2743 // a new one.
2744 final int N = mMap.size();
2745 if (N >= MAX_WAKELOCKS_PER_UID) {
2746 // Went over the limit on number of objects to track; this one goes
2747 // in to the overflow.
2748 obj = mCurOverflow;
2749 if (obj == null) {
2750 // Need to start overflow now...
2751 obj = mCurOverflow = instantiateObject();
2752 mMap.put(OVERFLOW_NAME, obj);
2753 }
2754 if (mActiveOverflow == null) {
2755 mActiveOverflow = new ArrayMap<>();
2756 }
2757 mActiveOverflow.put(name, new MutableInt(1));
Dianne Hackborn657153b2016-07-29 14:54:14 -07002758 mLastOverflowTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002759 return obj;
2760 }
2761
2762 // Normal case where we just need to make a new object.
2763 obj = instantiateObject();
2764 mMap.put(name, obj);
2765 return obj;
2766 }
2767
2768 public T stopObject(String name) {
Joe Onorato388fc332016-04-12 17:06:47 -07002769 if (name == null) {
2770 name = "";
2771 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002772 T obj = mMap.get(name);
2773 if (obj != null) {
2774 return obj;
2775 }
2776
2777 // No object exists for the given name, but do we currently have it
2778 // running as part of the overflow?
2779 if (mActiveOverflow != null) {
2780 MutableInt over = mActiveOverflow.get(name);
2781 if (over != null) {
2782 // We are already actively counting this name in the overflow object.
2783 obj = mCurOverflow;
2784 if (obj != null) {
2785 over.value--;
2786 if (over.value <= 0) {
2787 mActiveOverflow.remove(name);
Dianne Hackborn657153b2016-07-29 14:54:14 -07002788 mLastOverflowFinishTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002789 }
2790 return obj;
2791 }
2792 }
2793 }
2794
2795 // Huh, they are stopping an active operation but we can't find one!
2796 // That's not good.
Dianne Hackborn657153b2016-07-29 14:54:14 -07002797 StringBuilder sb = new StringBuilder();
2798 sb.append("Unable to find object for ");
2799 sb.append(name);
2800 sb.append(" in uid ");
2801 sb.append(mUid);
2802 sb.append(" mapsize=");
2803 sb.append(mMap.size());
2804 sb.append(" activeoverflow=");
2805 sb.append(mActiveOverflow);
2806 sb.append(" curoverflow=");
2807 sb.append(mCurOverflow);
2808 long now = SystemClock.elapsedRealtime();
2809 if (mLastOverflowTime != 0) {
2810 sb.append(" lastOverflowTime=");
2811 TimeUtils.formatDuration(mLastOverflowTime-now, sb);
2812 }
2813 if (mLastOverflowFinishTime != 0) {
2814 sb.append(" lastOverflowFinishTime=");
2815 TimeUtils.formatDuration(mLastOverflowFinishTime-now, sb);
2816 }
2817 if (mLastClearTime != 0) {
2818 sb.append(" lastClearTime=");
2819 TimeUtils.formatDuration(mLastClearTime-now, sb);
2820 }
2821 if (mLastCleanupTime != 0) {
2822 sb.append(" lastCleanupTime=");
2823 TimeUtils.formatDuration(mLastCleanupTime-now, sb);
2824 }
2825 Slog.wtf(TAG, sb.toString());
Dianne Hackbornd953c532014-08-16 18:17:38 -07002826 return null;
2827 }
2828
2829 public abstract T instantiateObject();
2830 }
2831
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002832 public static class ControllerActivityCounterImpl extends ControllerActivityCounter
2833 implements Parcelable {
2834 private final LongSamplingCounter mIdleTimeMillis;
Siddharth Rayb50a6842017-12-14 15:15:28 -08002835 private final LongSamplingCounter mScanTimeMillis;
Siddharth Rayed754702018-02-15 12:44:37 -08002836 private final LongSamplingCounter mSleepTimeMillis;
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002837 private final LongSamplingCounter mRxTimeMillis;
2838 private final LongSamplingCounter[] mTxTimeMillis;
2839 private final LongSamplingCounter mPowerDrainMaMs;
Blake Kragtencb308d92019-01-28 10:54:13 -08002840 private final LongSamplingCounter mMonitoredRailChargeConsumedMaMs;
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002841
2842 public ControllerActivityCounterImpl(TimeBase timeBase, int numTxStates) {
2843 mIdleTimeMillis = new LongSamplingCounter(timeBase);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002844 mScanTimeMillis = new LongSamplingCounter(timeBase);
Siddharth Rayed754702018-02-15 12:44:37 -08002845 mSleepTimeMillis = new LongSamplingCounter(timeBase);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002846 mRxTimeMillis = new LongSamplingCounter(timeBase);
2847 mTxTimeMillis = new LongSamplingCounter[numTxStates];
2848 for (int i = 0; i < numTxStates; i++) {
2849 mTxTimeMillis[i] = new LongSamplingCounter(timeBase);
2850 }
2851 mPowerDrainMaMs = new LongSamplingCounter(timeBase);
Blake Kragtencb308d92019-01-28 10:54:13 -08002852 mMonitoredRailChargeConsumedMaMs = new LongSamplingCounter(timeBase);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002853 }
2854
2855 public ControllerActivityCounterImpl(TimeBase timeBase, int numTxStates, Parcel in) {
2856 mIdleTimeMillis = new LongSamplingCounter(timeBase, in);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002857 mScanTimeMillis = new LongSamplingCounter(timeBase, in);
Siddharth Rayed754702018-02-15 12:44:37 -08002858 mSleepTimeMillis = new LongSamplingCounter(timeBase, in);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002859 mRxTimeMillis = new LongSamplingCounter(timeBase, in);
2860 final int recordedTxStates = in.readInt();
2861 if (recordedTxStates != numTxStates) {
2862 throw new ParcelFormatException("inconsistent tx state lengths");
2863 }
2864
2865 mTxTimeMillis = new LongSamplingCounter[numTxStates];
2866 for (int i = 0; i < numTxStates; i++) {
2867 mTxTimeMillis[i] = new LongSamplingCounter(timeBase, in);
2868 }
2869 mPowerDrainMaMs = new LongSamplingCounter(timeBase, in);
Blake Kragtencb308d92019-01-28 10:54:13 -08002870 mMonitoredRailChargeConsumedMaMs = new LongSamplingCounter(timeBase, in);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002871 }
2872
2873 public void readSummaryFromParcel(Parcel in) {
2874 mIdleTimeMillis.readSummaryFromParcelLocked(in);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002875 mScanTimeMillis.readSummaryFromParcelLocked(in);
Siddharth Rayed754702018-02-15 12:44:37 -08002876 mSleepTimeMillis.readSummaryFromParcelLocked(in);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002877 mRxTimeMillis.readSummaryFromParcelLocked(in);
2878 final int recordedTxStates = in.readInt();
2879 if (recordedTxStates != mTxTimeMillis.length) {
2880 throw new ParcelFormatException("inconsistent tx state lengths");
2881 }
2882 for (LongSamplingCounter counter : mTxTimeMillis) {
2883 counter.readSummaryFromParcelLocked(in);
2884 }
2885 mPowerDrainMaMs.readSummaryFromParcelLocked(in);
Blake Kragtencb308d92019-01-28 10:54:13 -08002886 mMonitoredRailChargeConsumedMaMs.readSummaryFromParcelLocked(in);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002887 }
2888
2889 @Override
2890 public int describeContents() {
2891 return 0;
2892 }
2893
2894 public void writeSummaryToParcel(Parcel dest) {
2895 mIdleTimeMillis.writeSummaryFromParcelLocked(dest);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002896 mScanTimeMillis.writeSummaryFromParcelLocked(dest);
Siddharth Rayed754702018-02-15 12:44:37 -08002897 mSleepTimeMillis.writeSummaryFromParcelLocked(dest);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002898 mRxTimeMillis.writeSummaryFromParcelLocked(dest);
2899 dest.writeInt(mTxTimeMillis.length);
2900 for (LongSamplingCounter counter : mTxTimeMillis) {
2901 counter.writeSummaryFromParcelLocked(dest);
2902 }
2903 mPowerDrainMaMs.writeSummaryFromParcelLocked(dest);
Blake Kragtencb308d92019-01-28 10:54:13 -08002904 mMonitoredRailChargeConsumedMaMs.writeSummaryFromParcelLocked(dest);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002905 }
2906
2907 @Override
2908 public void writeToParcel(Parcel dest, int flags) {
2909 mIdleTimeMillis.writeToParcel(dest);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002910 mScanTimeMillis.writeToParcel(dest);
Siddharth Rayed754702018-02-15 12:44:37 -08002911 mSleepTimeMillis.writeToParcel(dest);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002912 mRxTimeMillis.writeToParcel(dest);
2913 dest.writeInt(mTxTimeMillis.length);
2914 for (LongSamplingCounter counter : mTxTimeMillis) {
2915 counter.writeToParcel(dest);
2916 }
2917 mPowerDrainMaMs.writeToParcel(dest);
Blake Kragtencb308d92019-01-28 10:54:13 -08002918 mMonitoredRailChargeConsumedMaMs.writeToParcel(dest);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002919 }
2920
2921 public void reset(boolean detachIfReset) {
2922 mIdleTimeMillis.reset(detachIfReset);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002923 mScanTimeMillis.reset(detachIfReset);
Siddharth Rayed754702018-02-15 12:44:37 -08002924 mSleepTimeMillis.reset(detachIfReset);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002925 mRxTimeMillis.reset(detachIfReset);
2926 for (LongSamplingCounter counter : mTxTimeMillis) {
2927 counter.reset(detachIfReset);
2928 }
2929 mPowerDrainMaMs.reset(detachIfReset);
Blake Kragtencb308d92019-01-28 10:54:13 -08002930 mMonitoredRailChargeConsumedMaMs.reset(detachIfReset);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002931 }
2932
2933 public void detach() {
2934 mIdleTimeMillis.detach();
Siddharth Rayb50a6842017-12-14 15:15:28 -08002935 mScanTimeMillis.detach();
Siddharth Rayed754702018-02-15 12:44:37 -08002936 mSleepTimeMillis.detach();
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002937 mRxTimeMillis.detach();
2938 for (LongSamplingCounter counter : mTxTimeMillis) {
2939 counter.detach();
2940 }
2941 mPowerDrainMaMs.detach();
Blake Kragtencb308d92019-01-28 10:54:13 -08002942 mMonitoredRailChargeConsumedMaMs.detach();
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002943 }
2944
2945 /**
2946 * @return a LongSamplingCounter, measuring time spent in the idle state in
2947 * milliseconds.
2948 */
2949 @Override
2950 public LongSamplingCounter getIdleTimeCounter() {
Roshan Pius81643302016-03-14 16:45:55 -07002951 return mIdleTimeMillis;
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002952 }
2953
2954 /**
Siddharth Rayb50a6842017-12-14 15:15:28 -08002955 * @return a LongSamplingCounter, measuring time spent in the scan state in
2956 * milliseconds.
2957 */
2958 @Override
2959 public LongSamplingCounter getScanTimeCounter() {
2960 return mScanTimeMillis;
2961 }
2962
2963 /**
Siddharth Rayed754702018-02-15 12:44:37 -08002964 * @return a LongSamplingCounter, measuring time spent in the sleep state in
2965 * milliseconds.
2966 */
2967 @Override
2968 public LongSamplingCounter getSleepTimeCounter() {
2969 return mSleepTimeMillis;
2970 }
2971
2972 /**
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002973 * @return a LongSamplingCounter, measuring time spent in the receive state in
2974 * milliseconds.
2975 */
2976 @Override
2977 public LongSamplingCounter getRxTimeCounter() {
2978 return mRxTimeMillis;
2979 }
2980
2981 /**
2982 * @return a LongSamplingCounter[], measuring time spent in various transmit states in
2983 * milliseconds.
2984 */
2985 @Override
2986 public LongSamplingCounter[] getTxTimeCounters() {
2987 return mTxTimeMillis;
2988 }
2989
2990 /**
2991 * @return a LongSamplingCounter, measuring power use in milli-ampere milliseconds (mAmS).
2992 */
2993 @Override
2994 public LongSamplingCounter getPowerCounter() {
2995 return mPowerDrainMaMs;
2996 }
Blake Kragtencb308d92019-01-28 10:54:13 -08002997
2998 /**
2999 * @return a LongSamplingCounter, measuring actual monitored rail energy consumed
3000 * milli-ampere milli-seconds (mAmS).
3001 */
3002 @Override
3003 public LongSamplingCounter getMonitoredRailChargeConsumedMaMs() {
3004 return mMonitoredRailChargeConsumedMaMs;
3005 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08003006 }
3007
Bookatz50df7112017-08-04 14:53:26 -07003008 /** Get Resource Power Manager stats. Create a new one if it doesn't already exist. */
3009 public SamplingTimer getRpmTimerLocked(String name) {
3010 SamplingTimer rpmt = mRpmStats.get(name);
3011 if (rpmt == null) {
3012 rpmt = new SamplingTimer(mClocks, mOnBatteryTimeBase);
3013 mRpmStats.put(name, rpmt);
3014 }
3015 return rpmt;
3016 }
3017
3018 /** Get Screen-off Resource Power Manager stats. Create new one if it doesn't already exist. */
3019 public SamplingTimer getScreenOffRpmTimerLocked(String name) {
3020 SamplingTimer rpmt = mScreenOffRpmStats.get(name);
3021 if (rpmt == null) {
3022 rpmt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
3023 mScreenOffRpmStats.put(name, rpmt);
3024 }
3025 return rpmt;
3026 }
3027
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003028 /*
3029 * Get the wakeup reason counter, and create a new one if one
3030 * doesn't already exist.
3031 */
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07003032 public SamplingTimer getWakeupReasonTimerLocked(String name) {
3033 SamplingTimer timer = mWakeupReasonStats.get(name);
3034 if (timer == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07003035 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07003036 mWakeupReasonStats.put(name, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003037 }
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07003038 return timer;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003039 }
3040
Evan Millarc64edde2009-04-18 12:26:32 -07003041 /*
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003042 * Get the KernelWakelockTimer associated with name, and create a new one if one
Evan Millarc64edde2009-04-18 12:26:32 -07003043 * doesn't already exist.
3044 */
3045 public SamplingTimer getKernelWakelockTimerLocked(String name) {
3046 SamplingTimer kwlt = mKernelWakelockStats.get(name);
3047 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07003048 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Evan Millarc64edde2009-04-18 12:26:32 -07003049 mKernelWakelockStats.put(name, kwlt);
3050 }
3051 return kwlt;
3052 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07003053
James Carr3a226052016-07-01 14:49:52 -07003054 public SamplingTimer getKernelMemoryTimerLocked(long bucket) {
3055 SamplingTimer kmt = mKernelMemoryStats.get(bucket);
3056 if (kmt == null) {
3057 kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase);
3058 mKernelMemoryStats.put(bucket, kmt);
3059 }
3060 return kmt;
3061 }
3062
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003063 private int writeHistoryTag(HistoryTag tag) {
3064 Integer idxObj = mHistoryTagPool.get(tag);
3065 int idx;
3066 if (idxObj != null) {
3067 idx = idxObj;
3068 } else {
3069 idx = mNextHistoryTagIdx;
3070 HistoryTag key = new HistoryTag();
3071 key.setTo(tag);
3072 tag.poolIdx = idx;
3073 mHistoryTagPool.put(key, idx);
3074 mNextHistoryTagIdx++;
3075 mNumHistoryTagChars += key.string.length() + 1;
3076 }
3077 return idx;
3078 }
3079
3080 private void readHistoryTag(int index, HistoryTag tag) {
Hui Yu0ed84f12018-06-20 19:07:56 -07003081 if (index < mReadHistoryStrings.length) {
3082 tag.string = mReadHistoryStrings[index];
3083 tag.uid = mReadHistoryUids[index];
3084 } else {
3085 tag.string = null;
3086 tag.uid = 0;
3087 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003088 tag.poolIdx = index;
3089 }
3090
Adam Lesinski926969b2016-04-28 17:31:12 -07003091 /*
3092 The history delta format uses flags to denote further data in subsequent ints in the parcel.
3093
3094 There is always the first token, which may contain the delta time, or an indicator of
3095 the length of the time (int or long) following this token.
3096
3097 First token: always present,
3098 31 23 15 7 0
3099 â–ˆ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â–ˆ
3100
3101 T: the delta time if it is <= 0x7fffd. Otherwise 0x7fffe indicates an int immediately
3102 follows containing the time, and 0x7ffff indicates a long immediately follows with the
3103 delta time.
3104 A: battery level changed and an int follows with battery data.
3105 B: state changed and an int follows with state change data.
3106 C: state2 has changed and an int follows with state2 change data.
3107 D: wakelock/wakereason has changed and an wakelock/wakereason struct follows.
3108 E: event data has changed and an event struct follows.
3109 F: battery charge in coulombs has changed and an int with the charge follows.
3110 G: state flag denoting that the mobile radio was active.
3111 H: state flag denoting that the wifi radio was active.
3112 I: state flag denoting that a wifi scan occurred.
3113 J: state flag denoting that a wifi full lock was held.
3114 K: state flag denoting that the gps was on.
3115 L: state flag denoting that a wakelock was held.
3116 M: state flag denoting that the cpu was running.
3117
3118 Time int/long: if T in the first token is 0x7ffff or 0x7fffe, then an int or long follows
3119 with the time delta.
3120
3121 Battery level int: if A in the first token is set,
3122 31 23 15 7 0
3123 â–ˆ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â–ˆ
3124
3125 D: indicates that extra history details follow.
3126 V: the battery voltage.
3127 T: the battery temperature.
3128 L: the battery level (out of 100).
3129
3130 State change int: if B in the first token is set,
3131 31 23 15 7 0
3132 â–ˆS|S|S|H|H|H|P|Pâ–ˆF|E|D|C|B| | |Aâ–ˆ | | | | | | | â–ˆ | | | | | | | â–ˆ
3133
3134 A: wifi multicast was on.
3135 B: battery was plugged in.
3136 C: screen was on.
3137 D: phone was scanning for signal.
3138 E: audio was on.
3139 F: a sensor was active.
3140
3141 State2 change int: if C in the first token is set,
3142 31 23 15 7 0
3143 â–ˆM|L|K|J|I|H|H|Gâ–ˆF|E|D|C| | | | â–ˆ | | | | | | | â–ˆ |B|B|B|A|A|A|Aâ–ˆ
3144
3145 A: 4 bits indicating the wifi supplicant state: {@link BatteryStats#WIFI_SUPPL_STATE_NAMES}.
3146 B: 3 bits indicating the wifi signal strength: 0, 1, 2, 3, 4.
3147 C: a bluetooth scan was active.
3148 D: the camera was active.
3149 E: bluetooth was on.
3150 F: a phone call was active.
3151 G: the device was charging.
3152 H: 2 bits indicating the device-idle (doze) state: off, light, full
3153 I: the flashlight was on.
3154 J: wifi was on.
3155 K: wifi was running.
3156 L: video was playing.
3157 M: power save mode was on.
3158
3159 Wakelock/wakereason struct: if D in the first token is set,
3160 TODO(adamlesinski): describe wakelock/wakereason struct.
3161
3162 Event struct: if E in the first token is set,
3163 TODO(adamlesinski): describe the event struct.
3164
3165 History step details struct: if D in the battery level int is set,
3166 TODO(adamlesinski): describe the history step details struct.
3167
3168 Battery charge int: if F in the first token is set, an int representing the battery charge
3169 in coulombs follows.
3170 */
3171
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003172 // Part of initial delta int that specifies the time delta.
Dianne Hackborne13c4c02014-02-11 17:18:35 -08003173 static final int DELTA_TIME_MASK = 0x7ffff;
3174 static final int DELTA_TIME_LONG = 0x7ffff; // The delta is a following long
3175 static final int DELTA_TIME_INT = 0x7fffe; // The delta is a following int
3176 static final int DELTA_TIME_ABS = 0x7fffd; // Following is an entire abs update.
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003177 // Flag in delta int: a new battery level int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003178 static final int DELTA_BATTERY_LEVEL_FLAG = 0x00080000;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003179 // Flag in delta int: a new full state and battery status int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003180 static final int DELTA_STATE_FLAG = 0x00100000;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08003181 // Flag in delta int: a new full state2 int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003182 static final int DELTA_STATE2_FLAG = 0x00200000;
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003183 // Flag in delta int: contains a wakelock or wakeReason tag.
Adam Lesinski926969b2016-04-28 17:31:12 -07003184 static final int DELTA_WAKELOCK_FLAG = 0x00400000;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003185 // Flag in delta int: contains an event description.
Adam Lesinski926969b2016-04-28 17:31:12 -07003186 static final int DELTA_EVENT_FLAG = 0x00800000;
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003187 // Flag in delta int: contains the battery charge count in uAh.
3188 static final int DELTA_BATTERY_CHARGE_FLAG = 0x01000000;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003189 // These upper bits are the frequently changing state bits.
Adam Lesinski926969b2016-04-28 17:31:12 -07003190 static final int DELTA_STATE_MASK = 0xfe000000;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003191
3192 // These are the pieces of battery state that are packed in to the upper bits of
3193 // the state int that have been packed in to the first delta int. They must fit
Adam Lesinski926969b2016-04-28 17:31:12 -07003194 // in STATE_BATTERY_MASK.
3195 static final int STATE_BATTERY_MASK = 0xff000000;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003196 static final int STATE_BATTERY_STATUS_MASK = 0x00000007;
3197 static final int STATE_BATTERY_STATUS_SHIFT = 29;
3198 static final int STATE_BATTERY_HEALTH_MASK = 0x00000007;
3199 static final int STATE_BATTERY_HEALTH_SHIFT = 26;
3200 static final int STATE_BATTERY_PLUG_MASK = 0x00000003;
3201 static final int STATE_BATTERY_PLUG_SHIFT = 24;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003202
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003203 // We use the low bit of the battery state int to indicate that we have full details
3204 // from a battery level change.
3205 static final int BATTERY_DELTA_LEVEL_FLAG = 0x00000001;
3206
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003207 public void writeHistoryDelta(Parcel dest, HistoryItem cur, HistoryItem last) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003208 if (last == null || cur.cmd != HistoryItem.CMD_UPDATE) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003209 dest.writeInt(DELTA_TIME_ABS);
3210 cur.writeToParcel(dest, 0);
3211 return;
3212 }
3213
3214 final long deltaTime = cur.time - last.time;
3215 final int lastBatteryLevelInt = buildBatteryLevelInt(last);
3216 final int lastStateInt = buildStateInt(last);
3217
3218 int deltaTimeToken;
3219 if (deltaTime < 0 || deltaTime > Integer.MAX_VALUE) {
3220 deltaTimeToken = DELTA_TIME_LONG;
3221 } else if (deltaTime >= DELTA_TIME_ABS) {
3222 deltaTimeToken = DELTA_TIME_INT;
3223 } else {
3224 deltaTimeToken = (int)deltaTime;
3225 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003226 int firstToken = deltaTimeToken | (cur.states&DELTA_STATE_MASK);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003227 final int includeStepDetails = mLastHistoryStepLevel > cur.batteryLevel
3228 ? BATTERY_DELTA_LEVEL_FLAG : 0;
3229 final boolean computeStepDetails = includeStepDetails != 0
3230 || mLastHistoryStepDetails == null;
3231 final int batteryLevelInt = buildBatteryLevelInt(cur) | includeStepDetails;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003232 final boolean batteryLevelIntChanged = batteryLevelInt != lastBatteryLevelInt;
3233 if (batteryLevelIntChanged) {
3234 firstToken |= DELTA_BATTERY_LEVEL_FLAG;
3235 }
3236 final int stateInt = buildStateInt(cur);
3237 final boolean stateIntChanged = stateInt != lastStateInt;
3238 if (stateIntChanged) {
3239 firstToken |= DELTA_STATE_FLAG;
3240 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003241 final boolean state2IntChanged = cur.states2 != last.states2;
3242 if (state2IntChanged) {
3243 firstToken |= DELTA_STATE2_FLAG;
3244 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003245 if (cur.wakelockTag != null || cur.wakeReasonTag != null) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003246 firstToken |= DELTA_WAKELOCK_FLAG;
3247 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003248 if (cur.eventCode != HistoryItem.EVENT_NONE) {
3249 firstToken |= DELTA_EVENT_FLAG;
3250 }
Adam Lesinski926969b2016-04-28 17:31:12 -07003251
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003252 final boolean batteryChargeChanged = cur.batteryChargeUAh != last.batteryChargeUAh;
3253 if (batteryChargeChanged) {
3254 firstToken |= DELTA_BATTERY_CHARGE_FLAG;
Adam Lesinski926969b2016-04-28 17:31:12 -07003255 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003256 dest.writeInt(firstToken);
3257 if (DEBUG) Slog.i(TAG, "WRITE DELTA: firstToken=0x" + Integer.toHexString(firstToken)
3258 + " deltaTime=" + deltaTime);
3259
3260 if (deltaTimeToken >= DELTA_TIME_INT) {
3261 if (deltaTimeToken == DELTA_TIME_INT) {
3262 if (DEBUG) Slog.i(TAG, "WRITE DELTA: int deltaTime=" + (int)deltaTime);
3263 dest.writeInt((int)deltaTime);
3264 } else {
3265 if (DEBUG) Slog.i(TAG, "WRITE DELTA: long deltaTime=" + deltaTime);
3266 dest.writeLong(deltaTime);
3267 }
3268 }
3269 if (batteryLevelIntChanged) {
3270 dest.writeInt(batteryLevelInt);
3271 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryToken=0x"
3272 + Integer.toHexString(batteryLevelInt)
3273 + " batteryLevel=" + cur.batteryLevel
3274 + " batteryTemp=" + cur.batteryTemperature
3275 + " batteryVolt=" + (int)cur.batteryVoltage);
3276 }
3277 if (stateIntChanged) {
3278 dest.writeInt(stateInt);
3279 if (DEBUG) Slog.i(TAG, "WRITE DELTA: stateToken=0x"
3280 + Integer.toHexString(stateInt)
3281 + " batteryStatus=" + cur.batteryStatus
3282 + " batteryHealth=" + cur.batteryHealth
3283 + " batteryPlugType=" + cur.batteryPlugType
3284 + " states=0x" + Integer.toHexString(cur.states));
3285 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003286 if (state2IntChanged) {
3287 dest.writeInt(cur.states2);
3288 if (DEBUG) Slog.i(TAG, "WRITE DELTA: states2=0x"
3289 + Integer.toHexString(cur.states2));
3290 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003291 if (cur.wakelockTag != null || cur.wakeReasonTag != null) {
3292 int wakeLockIndex;
3293 int wakeReasonIndex;
3294 if (cur.wakelockTag != null) {
3295 wakeLockIndex = writeHistoryTag(cur.wakelockTag);
3296 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx
3297 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string);
3298 } else {
3299 wakeLockIndex = 0xffff;
3300 }
3301 if (cur.wakeReasonTag != null) {
3302 wakeReasonIndex = writeHistoryTag(cur.wakeReasonTag);
3303 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx
3304 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string);
3305 } else {
3306 wakeReasonIndex = 0xffff;
3307 }
3308 dest.writeInt((wakeReasonIndex<<16) | wakeLockIndex);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003309 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003310 if (cur.eventCode != HistoryItem.EVENT_NONE) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003311 int index = writeHistoryTag(cur.eventTag);
3312 int codeAndIndex = (cur.eventCode&0xffff) | (index<<16);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003313 dest.writeInt(codeAndIndex);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003314 if (DEBUG) Slog.i(TAG, "WRITE DELTA: event=" + cur.eventCode + " tag=#"
3315 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":"
3316 + cur.eventTag.string);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003317 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003318 if (computeStepDetails) {
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07003319 if (mPlatformIdleStateCallback != null) {
3320 mCurHistoryStepDetails.statPlatformIdleState =
3321 mPlatformIdleStateCallback.getPlatformLowPowerStats();
3322 if (DEBUG) Slog.i(TAG, "WRITE PlatformIdleState:" +
3323 mCurHistoryStepDetails.statPlatformIdleState);
Ahmed ElArabawyd8b44112017-05-23 21:25:02 +00003324
3325 mCurHistoryStepDetails.statSubsystemPowerState =
3326 mPlatformIdleStateCallback.getSubsystemLowPowerStats();
3327 if (DEBUG) Slog.i(TAG, "WRITE SubsystemPowerState:" +
3328 mCurHistoryStepDetails.statSubsystemPowerState);
3329
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07003330 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003331 computeHistoryStepDetails(mCurHistoryStepDetails, mLastHistoryStepDetails);
3332 if (includeStepDetails != 0) {
3333 mCurHistoryStepDetails.writeToParcel(dest);
3334 }
3335 cur.stepDetails = mCurHistoryStepDetails;
3336 mLastHistoryStepDetails = mCurHistoryStepDetails;
3337 } else {
3338 cur.stepDetails = null;
3339 }
3340 if (mLastHistoryStepLevel < cur.batteryLevel) {
3341 mLastHistoryStepDetails = null;
3342 }
3343 mLastHistoryStepLevel = cur.batteryLevel;
Adam Lesinski926969b2016-04-28 17:31:12 -07003344
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003345 if (batteryChargeChanged) {
3346 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryChargeUAh=" + cur.batteryChargeUAh);
3347 dest.writeInt(cur.batteryChargeUAh);
Adam Lesinski926969b2016-04-28 17:31:12 -07003348 }
Blake Kragtencb308d92019-01-28 10:54:13 -08003349 dest.writeDouble(cur.modemRailChargeMah);
3350 dest.writeDouble(cur.wifiRailChargeMah);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003351 }
3352
3353 private int buildBatteryLevelInt(HistoryItem h) {
3354 return ((((int)h.batteryLevel)<<25)&0xfe000000)
Adam Lesinski3944c812015-11-13 15:54:59 -08003355 | ((((int)h.batteryTemperature)<<15)&0x01ff8000)
3356 | ((((int)h.batteryVoltage)<<1)&0x00007ffe);
3357 }
3358
3359 private void readBatteryLevelInt(int batteryLevelInt, HistoryItem out) {
3360 out.batteryLevel = (byte)((batteryLevelInt & 0xfe000000) >>> 25);
3361 out.batteryTemperature = (short)((batteryLevelInt & 0x01ff8000) >>> 15);
3362 out.batteryVoltage = (char)((batteryLevelInt & 0x00007ffe) >>> 1);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003363 }
3364
3365 private int buildStateInt(HistoryItem h) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003366 int plugType = 0;
3367 if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_AC) != 0) {
3368 plugType = 1;
3369 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_USB) != 0) {
3370 plugType = 2;
3371 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_WIRELESS) != 0) {
3372 plugType = 3;
3373 }
3374 return ((h.batteryStatus&STATE_BATTERY_STATUS_MASK)<<STATE_BATTERY_STATUS_SHIFT)
3375 | ((h.batteryHealth&STATE_BATTERY_HEALTH_MASK)<<STATE_BATTERY_HEALTH_SHIFT)
3376 | ((plugType&STATE_BATTERY_PLUG_MASK)<<STATE_BATTERY_PLUG_SHIFT)
Adam Lesinski926969b2016-04-28 17:31:12 -07003377 | (h.states&(~STATE_BATTERY_MASK));
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003378 }
3379
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003380 private void computeHistoryStepDetails(final HistoryStepDetails out,
3381 final HistoryStepDetails last) {
3382 final HistoryStepDetails tmp = last != null ? mTmpHistoryStepDetails : out;
3383
3384 // Perform a CPU update right after we do this collection, so we have started
3385 // collecting good data for the next step.
3386 requestImmediateCpuUpdate();
3387
3388 if (last == null) {
3389 // We are not generating a delta, so all we need to do is reset the stats
3390 // we will later be doing a delta from.
3391 final int NU = mUidStats.size();
3392 for (int i=0; i<NU; i++) {
3393 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
3394 uid.mLastStepUserTime = uid.mCurStepUserTime;
3395 uid.mLastStepSystemTime = uid.mCurStepSystemTime;
3396 }
3397 mLastStepCpuUserTime = mCurStepCpuUserTime;
3398 mLastStepCpuSystemTime = mCurStepCpuSystemTime;
3399 mLastStepStatUserTime = mCurStepStatUserTime;
3400 mLastStepStatSystemTime = mCurStepStatSystemTime;
3401 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime;
3402 mLastStepStatIrqTime = mCurStepStatIrqTime;
3403 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime;
3404 mLastStepStatIdleTime = mCurStepStatIdleTime;
3405 tmp.clear();
3406 return;
3407 }
3408 if (DEBUG) {
3409 Slog.d(TAG, "Step stats last: user=" + mLastStepCpuUserTime + " sys="
3410 + mLastStepStatSystemTime + " io=" + mLastStepStatIOWaitTime
3411 + " irq=" + mLastStepStatIrqTime + " sirq="
3412 + mLastStepStatSoftIrqTime + " idle=" + mLastStepStatIdleTime);
3413 Slog.d(TAG, "Step stats cur: user=" + mCurStepCpuUserTime + " sys="
3414 + mCurStepStatSystemTime + " io=" + mCurStepStatIOWaitTime
3415 + " irq=" + mCurStepStatIrqTime + " sirq="
3416 + mCurStepStatSoftIrqTime + " idle=" + mCurStepStatIdleTime);
3417 }
3418 out.userTime = (int)(mCurStepCpuUserTime - mLastStepCpuUserTime);
3419 out.systemTime = (int)(mCurStepCpuSystemTime - mLastStepCpuSystemTime);
3420 out.statUserTime = (int)(mCurStepStatUserTime - mLastStepStatUserTime);
3421 out.statSystemTime = (int)(mCurStepStatSystemTime - mLastStepStatSystemTime);
3422 out.statIOWaitTime = (int)(mCurStepStatIOWaitTime - mLastStepStatIOWaitTime);
3423 out.statIrqTime = (int)(mCurStepStatIrqTime - mLastStepStatIrqTime);
3424 out.statSoftIrqTime = (int)(mCurStepStatSoftIrqTime - mLastStepStatSoftIrqTime);
3425 out.statIdlTime = (int)(mCurStepStatIdleTime - mLastStepStatIdleTime);
3426 out.appCpuUid1 = out.appCpuUid2 = out.appCpuUid3 = -1;
3427 out.appCpuUTime1 = out.appCpuUTime2 = out.appCpuUTime3 = 0;
3428 out.appCpuSTime1 = out.appCpuSTime2 = out.appCpuSTime3 = 0;
3429 final int NU = mUidStats.size();
3430 for (int i=0; i<NU; i++) {
3431 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
3432 final int totalUTime = (int)(uid.mCurStepUserTime - uid.mLastStepUserTime);
3433 final int totalSTime = (int)(uid.mCurStepSystemTime - uid.mLastStepSystemTime);
3434 final int totalTime = totalUTime + totalSTime;
3435 uid.mLastStepUserTime = uid.mCurStepUserTime;
3436 uid.mLastStepSystemTime = uid.mCurStepSystemTime;
3437 if (totalTime <= (out.appCpuUTime3+out.appCpuSTime3)) {
3438 continue;
3439 }
3440 if (totalTime <= (out.appCpuUTime2+out.appCpuSTime2)) {
3441 out.appCpuUid3 = uid.mUid;
3442 out.appCpuUTime3 = totalUTime;
3443 out.appCpuSTime3 = totalSTime;
3444 } else {
3445 out.appCpuUid3 = out.appCpuUid2;
3446 out.appCpuUTime3 = out.appCpuUTime2;
3447 out.appCpuSTime3 = out.appCpuSTime2;
3448 if (totalTime <= (out.appCpuUTime1+out.appCpuSTime1)) {
3449 out.appCpuUid2 = uid.mUid;
3450 out.appCpuUTime2 = totalUTime;
3451 out.appCpuSTime2 = totalSTime;
3452 } else {
3453 out.appCpuUid2 = out.appCpuUid1;
3454 out.appCpuUTime2 = out.appCpuUTime1;
3455 out.appCpuSTime2 = out.appCpuSTime1;
3456 out.appCpuUid1 = uid.mUid;
3457 out.appCpuUTime1 = totalUTime;
3458 out.appCpuSTime1 = totalSTime;
3459 }
3460 }
3461 }
3462 mLastStepCpuUserTime = mCurStepCpuUserTime;
3463 mLastStepCpuSystemTime = mCurStepCpuSystemTime;
3464 mLastStepStatUserTime = mCurStepStatUserTime;
3465 mLastStepStatSystemTime = mCurStepStatSystemTime;
3466 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime;
3467 mLastStepStatIrqTime = mCurStepStatIrqTime;
3468 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime;
3469 mLastStepStatIdleTime = mCurStepStatIdleTime;
3470 }
3471
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003472 public void readHistoryDelta(Parcel src, HistoryItem cur) {
3473 int firstToken = src.readInt();
3474 int deltaTimeToken = firstToken&DELTA_TIME_MASK;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003475 cur.cmd = HistoryItem.CMD_UPDATE;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003476 cur.numReadInts = 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003477 if (DEBUG) Slog.i(TAG, "READ DELTA: firstToken=0x" + Integer.toHexString(firstToken)
3478 + " deltaTimeToken=" + deltaTimeToken);
3479
3480 if (deltaTimeToken < DELTA_TIME_ABS) {
3481 cur.time += deltaTimeToken;
3482 } else if (deltaTimeToken == DELTA_TIME_ABS) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003483 cur.readFromParcel(src);
Hui Yucb996102019-06-28 18:24:38 -07003484 if (DEBUG) Slog.i(TAG, "READ DELTA: ABS time=" + cur.time);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003485 return;
3486 } else if (deltaTimeToken == DELTA_TIME_INT) {
3487 int delta = src.readInt();
3488 cur.time += delta;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003489 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003490 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time);
3491 } else {
3492 long delta = src.readLong();
3493 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time);
3494 cur.time += delta;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003495 cur.numReadInts += 2;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003496 }
3497
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003498 final int batteryLevelInt;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003499 if ((firstToken&DELTA_BATTERY_LEVEL_FLAG) != 0) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003500 batteryLevelInt = src.readInt();
Adam Lesinski3944c812015-11-13 15:54:59 -08003501 readBatteryLevelInt(batteryLevelInt, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003502 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003503 if (DEBUG) Slog.i(TAG, "READ DELTA: batteryToken=0x"
3504 + Integer.toHexString(batteryLevelInt)
3505 + " batteryLevel=" + cur.batteryLevel
3506 + " batteryTemp=" + cur.batteryTemperature
3507 + " batteryVolt=" + (int)cur.batteryVoltage);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003508 } else {
3509 batteryLevelInt = 0;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003510 }
3511
3512 if ((firstToken&DELTA_STATE_FLAG) != 0) {
3513 int stateInt = src.readInt();
Adam Lesinski926969b2016-04-28 17:31:12 -07003514 cur.states = (firstToken&DELTA_STATE_MASK) | (stateInt&(~STATE_BATTERY_MASK));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003515 cur.batteryStatus = (byte)((stateInt>>STATE_BATTERY_STATUS_SHIFT)
3516 & STATE_BATTERY_STATUS_MASK);
3517 cur.batteryHealth = (byte)((stateInt>>STATE_BATTERY_HEALTH_SHIFT)
3518 & STATE_BATTERY_HEALTH_MASK);
3519 cur.batteryPlugType = (byte)((stateInt>>STATE_BATTERY_PLUG_SHIFT)
3520 & STATE_BATTERY_PLUG_MASK);
3521 switch (cur.batteryPlugType) {
3522 case 1:
3523 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_AC;
3524 break;
3525 case 2:
3526 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_USB;
3527 break;
3528 case 3:
3529 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_WIRELESS;
3530 break;
3531 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003532 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003533 if (DEBUG) Slog.i(TAG, "READ DELTA: stateToken=0x"
3534 + Integer.toHexString(stateInt)
3535 + " batteryStatus=" + cur.batteryStatus
3536 + " batteryHealth=" + cur.batteryHealth
3537 + " batteryPlugType=" + cur.batteryPlugType
3538 + " states=0x" + Integer.toHexString(cur.states));
3539 } else {
Adam Lesinski926969b2016-04-28 17:31:12 -07003540 cur.states = (firstToken&DELTA_STATE_MASK) | (cur.states&(~STATE_BATTERY_MASK));
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003541 }
3542
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003543 if ((firstToken&DELTA_STATE2_FLAG) != 0) {
3544 cur.states2 = src.readInt();
3545 if (DEBUG) Slog.i(TAG, "READ DELTA: states2=0x"
3546 + Integer.toHexString(cur.states2));
3547 }
3548
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003549 if ((firstToken&DELTA_WAKELOCK_FLAG) != 0) {
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003550 int indexes = src.readInt();
3551 int wakeLockIndex = indexes&0xffff;
3552 int wakeReasonIndex = (indexes>>16)&0xffff;
3553 if (wakeLockIndex != 0xffff) {
3554 cur.wakelockTag = cur.localWakelockTag;
3555 readHistoryTag(wakeLockIndex, cur.wakelockTag);
3556 if (DEBUG) Slog.i(TAG, "READ DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx
3557 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string);
3558 } else {
3559 cur.wakelockTag = null;
3560 }
3561 if (wakeReasonIndex != 0xffff) {
3562 cur.wakeReasonTag = cur.localWakeReasonTag;
3563 readHistoryTag(wakeReasonIndex, cur.wakeReasonTag);
3564 if (DEBUG) Slog.i(TAG, "READ DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx
3565 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string);
3566 } else {
3567 cur.wakeReasonTag = null;
3568 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003569 cur.numReadInts += 1;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003570 } else {
3571 cur.wakelockTag = null;
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003572 cur.wakeReasonTag = null;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003573 }
3574
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003575 if ((firstToken&DELTA_EVENT_FLAG) != 0) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003576 cur.eventTag = cur.localEventTag;
3577 final int codeAndIndex = src.readInt();
Dianne Hackborn099bc622014-01-22 13:39:16 -08003578 cur.eventCode = (codeAndIndex&0xffff);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003579 final int index = ((codeAndIndex>>16)&0xffff);
3580 readHistoryTag(index, cur.eventTag);
3581 cur.numReadInts += 1;
3582 if (DEBUG) Slog.i(TAG, "READ DELTA: event=" + cur.eventCode + " tag=#"
3583 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":"
3584 + cur.eventTag.string);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003585 } else {
3586 cur.eventCode = HistoryItem.EVENT_NONE;
3587 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003588
3589 if ((batteryLevelInt&BATTERY_DELTA_LEVEL_FLAG) != 0) {
3590 cur.stepDetails = mReadHistoryStepDetails;
3591 cur.stepDetails.readFromParcel(src);
3592 } else {
3593 cur.stepDetails = null;
3594 }
Adam Lesinski926969b2016-04-28 17:31:12 -07003595
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003596 if ((firstToken&DELTA_BATTERY_CHARGE_FLAG) != 0) {
3597 cur.batteryChargeUAh = src.readInt();
Adam Lesinski926969b2016-04-28 17:31:12 -07003598 }
Blake Kragtencb308d92019-01-28 10:54:13 -08003599 cur.modemRailChargeMah = src.readDouble();
3600 cur.wifiRailChargeMah = src.readDouble();
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003601 }
3602
Dianne Hackbornfc064132014-06-02 12:42:12 -07003603 @Override
3604 public void commitCurrentHistoryBatchLocked() {
3605 mHistoryLastWritten.cmd = HistoryItem.CMD_NULL;
3606 }
3607
Hui Yu0ed84f12018-06-20 19:07:56 -07003608 public void createFakeHistoryEvents(long numEvents) {
3609 for(long i = 0; i < numEvents; i++) {
Hui Yu5b4edd62019-06-13 10:42:48 -07003610 noteLongPartialWakelockStart("name1", "historyName1", 1000);
3611 noteLongPartialWakelockFinish("name1", "historyName1", 1000);
Hui Yu0ed84f12018-06-20 19:07:56 -07003612 }
3613 }
3614
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003615 void addHistoryBufferLocked(long elapsedRealtimeMs, HistoryItem cur) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003616 if (!mHaveBatteryLevel || !mRecordingHistory) {
3617 return;
3618 }
3619
Dianne Hackborn40c87252014-03-19 16:55:40 -07003620 final long timeDiff = (mHistoryBaseTime+elapsedRealtimeMs) - mHistoryLastWritten.time;
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003621 final int diffStates = mHistoryLastWritten.states^(cur.states&mActiveHistoryStates);
3622 final int diffStates2 = mHistoryLastWritten.states2^(cur.states2&mActiveHistoryStates2);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003623 final int lastDiffStates = mHistoryLastWritten.states^mHistoryLastLastWritten.states;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003624 final int lastDiffStates2 = mHistoryLastWritten.states2^mHistoryLastLastWritten.states2;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003625 if (DEBUG) Slog.i(TAG, "ADD: tdelta=" + timeDiff + " diff="
3626 + Integer.toHexString(diffStates) + " lastDiff="
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003627 + Integer.toHexString(lastDiffStates) + " diff2="
3628 + Integer.toHexString(diffStates2) + " lastDiff2="
3629 + Integer.toHexString(lastDiffStates2));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003630 if (mHistoryBufferLastPos >= 0 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003631 && timeDiff < 1000 && (diffStates&lastDiffStates) == 0
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003632 && (diffStates2&lastDiffStates2) == 0
3633 && (mHistoryLastWritten.wakelockTag == null || cur.wakelockTag == null)
3634 && (mHistoryLastWritten.wakeReasonTag == null || cur.wakeReasonTag == null)
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003635 && mHistoryLastWritten.stepDetails == null
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003636 && (mHistoryLastWritten.eventCode == HistoryItem.EVENT_NONE
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003637 || cur.eventCode == HistoryItem.EVENT_NONE)
3638 && mHistoryLastWritten.batteryLevel == cur.batteryLevel
3639 && mHistoryLastWritten.batteryStatus == cur.batteryStatus
3640 && mHistoryLastWritten.batteryHealth == cur.batteryHealth
3641 && mHistoryLastWritten.batteryPlugType == cur.batteryPlugType
3642 && mHistoryLastWritten.batteryTemperature == cur.batteryTemperature
3643 && mHistoryLastWritten.batteryVoltage == cur.batteryVoltage) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003644 // We can merge this new change in with the last one. Merging is
Dianne Hackborn40c87252014-03-19 16:55:40 -07003645 // allowed as long as only the states have changed, and within those states
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003646 // as long as no bit has changed both between now and the last entry, as
3647 // well as the last entry and the one before it (so we capture any toggles).
3648 if (DEBUG) Slog.i(TAG, "ADD: rewinding back to " + mHistoryBufferLastPos);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003649 mHistoryBuffer.setDataSize(mHistoryBufferLastPos);
3650 mHistoryBuffer.setDataPosition(mHistoryBufferLastPos);
3651 mHistoryBufferLastPos = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003652 elapsedRealtimeMs = mHistoryLastWritten.time - mHistoryBaseTime;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003653 // If the last written history had a wakelock tag, we need to retain it.
3654 // Note that the condition above made sure that we aren't in a case where
3655 // both it and the current history item have a wakelock tag.
3656 if (mHistoryLastWritten.wakelockTag != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003657 cur.wakelockTag = cur.localWakelockTag;
3658 cur.wakelockTag.setTo(mHistoryLastWritten.wakelockTag);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003659 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003660 // If the last written history had a wake reason tag, we need to retain it.
3661 // Note that the condition above made sure that we aren't in a case where
3662 // both it and the current history item have a wakelock tag.
3663 if (mHistoryLastWritten.wakeReasonTag != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003664 cur.wakeReasonTag = cur.localWakeReasonTag;
3665 cur.wakeReasonTag.setTo(mHistoryLastWritten.wakeReasonTag);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003666 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003667 // If the last written history had an event, we need to retain it.
3668 // Note that the condition above made sure that we aren't in a case where
3669 // both it and the current history item have an event.
3670 if (mHistoryLastWritten.eventCode != HistoryItem.EVENT_NONE) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003671 cur.eventCode = mHistoryLastWritten.eventCode;
3672 cur.eventTag = cur.localEventTag;
3673 cur.eventTag.setTo(mHistoryLastWritten.eventTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003674 }
Dianne Hackborn1fadab52011-04-14 17:57:33 -07003675 mHistoryLastWritten.setTo(mHistoryLastLastWritten);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003676 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003677 final int dataSize = mHistoryBuffer.dataSize();
Adam Lesinski45489782016-12-15 23:45:17 -08003678
Hui Yu0ed84f12018-06-20 19:07:56 -07003679 if (dataSize >= mConstants.MAX_HISTORY_BUFFER) {
3680 //open a new history file.
3681 final long start = SystemClock.uptimeMillis();
3682 writeHistoryLocked(true);
3683 if (DEBUG) {
3684 Slog.d(TAG, "addHistoryBufferLocked writeHistoryLocked takes ms:"
3685 + (SystemClock.uptimeMillis() - start));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003686 }
Hui Yue40781e2019-05-31 15:14:43 -07003687 mBatteryStatsHistory.startNextFile();
Hui Yu0ed84f12018-06-20 19:07:56 -07003688 mHistoryBuffer.setDataSize(0);
3689 mHistoryBuffer.setDataPosition(0);
3690 mHistoryBuffer.setDataCapacity(mConstants.MAX_HISTORY_BUFFER / 2);
3691 mHistoryBufferLastPos = -1;
3692 final long elapsedRealtime = mClocks.elapsedRealtime();
3693 final long uptime = mClocks.uptimeMillis();
Hui Yu5b4edd62019-06-13 10:42:48 -07003694 HistoryItem newItem = new HistoryItem();
3695 newItem.setTo(cur);
Hui Yu0ed84f12018-06-20 19:07:56 -07003696 startRecordingHistory(elapsedRealtime, uptime, false);
Hui Yu5b4edd62019-06-13 10:42:48 -07003697 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, newItem);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003698 return;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003699 }
3700
Hui Yu0ed84f12018-06-20 19:07:56 -07003701 if (dataSize == 0) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003702 // The history is currently empty; we need it to start with a time stamp.
3703 cur.currentTime = System.currentTimeMillis();
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003704 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_RESET, cur);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003705 }
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003706 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003707 }
3708
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003709 private void addHistoryBufferLocked(long elapsedRealtimeMs, byte cmd, HistoryItem cur) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003710 if (mIteratingHistory) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003711 throw new IllegalStateException("Can't do this while iterating history!");
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003712 }
3713 mHistoryBufferLastPos = mHistoryBuffer.dataPosition();
3714 mHistoryLastLastWritten.setTo(mHistoryLastWritten);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003715 mHistoryLastWritten.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003716 mHistoryLastWritten.states &= mActiveHistoryStates;
3717 mHistoryLastWritten.states2 &= mActiveHistoryStates2;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003718 writeHistoryDelta(mHistoryBuffer, mHistoryLastWritten, mHistoryLastLastWritten);
Dianne Hackborn40c87252014-03-19 16:55:40 -07003719 mLastHistoryElapsedRealtime = elapsedRealtimeMs;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003720 cur.wakelockTag = null;
3721 cur.wakeReasonTag = null;
3722 cur.eventCode = HistoryItem.EVENT_NONE;
3723 cur.eventTag = null;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003724 if (DEBUG_HISTORY) Slog.i(TAG, "Writing history buffer: was " + mHistoryBufferLastPos
3725 + " now " + mHistoryBuffer.dataPosition()
3726 + " size is now " + mHistoryBuffer.dataSize());
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003727 }
3728
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003729 int mChangedStates = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003730 int mChangedStates2 = 0;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003731
Dianne Hackborn40c87252014-03-19 16:55:40 -07003732 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003733 if (mTrackRunningHistoryElapsedRealtime != 0) {
3734 final long diffElapsed = elapsedRealtimeMs - mTrackRunningHistoryElapsedRealtime;
3735 final long diffUptime = uptimeMs - mTrackRunningHistoryUptime;
3736 if (diffUptime < (diffElapsed-20)) {
3737 final long wakeElapsedTime = elapsedRealtimeMs - (diffElapsed - diffUptime);
3738 mHistoryAddTmp.setTo(mHistoryLastWritten);
3739 mHistoryAddTmp.wakelockTag = null;
3740 mHistoryAddTmp.wakeReasonTag = null;
3741 mHistoryAddTmp.eventCode = HistoryItem.EVENT_NONE;
3742 mHistoryAddTmp.states &= ~HistoryItem.STATE_CPU_RUNNING_FLAG;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003743 addHistoryRecordInnerLocked(wakeElapsedTime, mHistoryAddTmp);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003744 }
3745 }
3746 mHistoryCur.states |= HistoryItem.STATE_CPU_RUNNING_FLAG;
3747 mTrackRunningHistoryElapsedRealtime = elapsedRealtimeMs;
3748 mTrackRunningHistoryUptime = uptimeMs;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003749 addHistoryRecordInnerLocked(elapsedRealtimeMs, mHistoryCur);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003750 }
3751
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003752 void addHistoryRecordInnerLocked(long elapsedRealtimeMs, HistoryItem cur) {
3753 addHistoryBufferLocked(elapsedRealtimeMs, cur);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003754
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003755 if (!USE_OLD_HISTORY) {
3756 return;
3757 }
3758
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003759 if (!mHaveBatteryLevel || !mRecordingHistory) {
3760 return;
3761 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003762
3763 // If the current time is basically the same as the last time,
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003764 // and no states have since the last recorded entry changed and
3765 // are now resetting back to their original value, then just collapse
3766 // into one record.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003767 if (mHistoryEnd != null && mHistoryEnd.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn40c87252014-03-19 16:55:40 -07003768 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+1000)
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003769 && ((mHistoryEnd.states^cur.states)&mChangedStates&mActiveHistoryStates) == 0
3770 && ((mHistoryEnd.states2^cur.states2)&mChangedStates2&mActiveHistoryStates2) == 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003771 // If the current is the same as the one before, then we no
3772 // longer need the entry.
3773 if (mHistoryLastEnd != null && mHistoryLastEnd.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn40c87252014-03-19 16:55:40 -07003774 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+500)
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003775 && mHistoryLastEnd.sameNonEvent(cur)) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003776 mHistoryLastEnd.next = null;
3777 mHistoryEnd.next = mHistoryCache;
3778 mHistoryCache = mHistoryEnd;
3779 mHistoryEnd = mHistoryLastEnd;
3780 mHistoryLastEnd = null;
3781 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003782 mChangedStates |= mHistoryEnd.states^(cur.states&mActiveHistoryStates);
3783 mChangedStates2 |= mHistoryEnd.states^(cur.states2&mActiveHistoryStates2);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003784 mHistoryEnd.setTo(mHistoryEnd.time, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003785 }
3786 return;
3787 }
3788
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003789 mChangedStates = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003790 mChangedStates2 = 0;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003791 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003792 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003793
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003794 public void addHistoryEventLocked(long elapsedRealtimeMs, long uptimeMs, int code,
Dianne Hackborn40c87252014-03-19 16:55:40 -07003795 String name, int uid) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003796 mHistoryCur.eventCode = code;
3797 mHistoryCur.eventTag = mHistoryCur.localEventTag;
3798 mHistoryCur.eventTag.string = name;
3799 mHistoryCur.eventTag.uid = uid;
Dianne Hackborn4590e522014-03-24 13:36:46 -07003800 addHistoryRecordLocked(elapsedRealtimeMs, uptimeMs);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003801 }
3802
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003803 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs, byte cmd, HistoryItem cur) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003804 HistoryItem rec = mHistoryCache;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003805 if (rec != null) {
3806 mHistoryCache = rec.next;
3807 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003808 rec = new HistoryItem();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003809 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003810 rec.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003811
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003812 addHistoryRecordLocked(rec);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003813 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003814
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003815 void addHistoryRecordLocked(HistoryItem rec) {
3816 mNumHistoryItems++;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003817 rec.next = null;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003818 mHistoryLastEnd = mHistoryEnd;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003819 if (mHistoryEnd != null) {
3820 mHistoryEnd.next = rec;
3821 mHistoryEnd = rec;
3822 } else {
3823 mHistory = mHistoryEnd = rec;
3824 }
3825 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003826
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003827 void clearHistoryLocked() {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003828 if (DEBUG_HISTORY) Slog.i(TAG, "********** CLEARING HISTORY!");
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003829 if (USE_OLD_HISTORY) {
3830 if (mHistory != null) {
3831 mHistoryEnd.next = mHistoryCache;
3832 mHistoryCache = mHistory;
3833 mHistory = mHistoryLastEnd = mHistoryEnd = null;
3834 }
3835 mNumHistoryItems = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003836 }
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003837
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003838 mHistoryBaseTime = 0;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003839 mLastHistoryElapsedRealtime = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003840 mTrackRunningHistoryElapsedRealtime = 0;
3841 mTrackRunningHistoryUptime = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003842
3843 mHistoryBuffer.setDataSize(0);
3844 mHistoryBuffer.setDataPosition(0);
Hui Yu0ed84f12018-06-20 19:07:56 -07003845 mHistoryBuffer.setDataCapacity(mConstants.MAX_HISTORY_BUFFER / 2);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003846 mHistoryLastLastWritten.clear();
3847 mHistoryLastWritten.clear();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003848 mHistoryTagPool.clear();
3849 mNextHistoryTagIdx = 0;
3850 mNumHistoryTagChars = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003851 mHistoryBufferLastPos = -1;
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003852 mActiveHistoryStates = 0xffffffff;
3853 mActiveHistoryStates2 = 0xffffffff;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003854 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003855
Andreas Gampe3f24e692018-02-05 13:24:28 -08003856 @GuardedBy("this")
Mike Mac2f518a2017-09-19 16:06:03 -07003857 public void updateTimeBasesLocked(boolean unplugged, int screenState, long uptime,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003858 long realtime) {
Mike Maa7724752017-10-10 15:29:25 -07003859 final boolean screenOff = !isScreenOn(screenState);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003860 final boolean updateOnBatteryTimeBase = unplugged != mOnBatteryTimeBase.isRunning();
3861 final boolean updateOnBatteryScreenOffTimeBase =
3862 (unplugged && screenOff) != mOnBatteryScreenOffTimeBase.isRunning();
Bookatz867c0d72017-03-07 18:23:42 -08003863
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003864 if (updateOnBatteryScreenOffTimeBase || updateOnBatteryTimeBase) {
3865 if (updateOnBatteryScreenOffTimeBase) {
3866 updateKernelWakelocksLocked();
3867 updateBatteryPropertiesLocked();
Bookatz867c0d72017-03-07 18:23:42 -08003868 }
Bookatz82b341172017-09-07 19:06:08 -07003869 // This if{} is only necessary due to SCREEN_OFF_RPM_STATS_ENABLED, which exists because
3870 // updateRpmStatsLocked is too slow to run each screen change. When the speed is
3871 // improved, remove the surrounding if{}.
3872 if (SCREEN_OFF_RPM_STATS_ENABLED || updateOnBatteryTimeBase) {
3873 updateRpmStatsLocked(); // if either OnBattery or OnBatteryScreenOff timebase changes.
3874 }
Adam Lesinski72478f02015-06-17 15:39:43 -07003875 if (DEBUG_ENERGY_CPU) {
Mike Mac2f518a2017-09-19 16:06:03 -07003876 Slog.d(TAG, "Updating cpu time because screen is now "
3877 + Display.stateToString(screenState)
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003878 + " and battery is " + (unplugged ? "on" : "off"));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003879 }
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003880
3881 mOnBatteryTimeBase.setRunning(unplugged, uptime, realtime);
Mike Mac2f518a2017-09-19 16:06:03 -07003882 if (updateOnBatteryTimeBase) {
3883 for (int i = mUidStats.size() - 1; i >= 0; --i) {
3884 mUidStats.valueAt(i).updateOnBatteryBgTimeBase(uptime, realtime);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003885 }
Mike Mac2f518a2017-09-19 16:06:03 -07003886 }
3887 if (updateOnBatteryScreenOffTimeBase) {
3888 mOnBatteryScreenOffTimeBase.setRunning(unplugged && screenOff, uptime, realtime);
3889 for (int i = mUidStats.size() - 1; i >= 0; --i) {
3890 mUidStats.valueAt(i).updateOnBatteryScreenOffBgTimeBase(uptime, realtime);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003891 }
Bookatzc8c44962017-05-11 12:12:54 -07003892 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003893 }
3894 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07003895
Adam Lesinskie1f480d2017-02-15 18:51:23 -08003896 private void updateBatteryPropertiesLocked() {
3897 try {
3898 IBatteryPropertiesRegistrar registrar = IBatteryPropertiesRegistrar.Stub.asInterface(
3899 ServiceManager.getService("batteryproperties"));
Mike Ma31cdfb42018-06-29 12:18:27 -07003900 if (registrar != null) {
3901 registrar.scheduleUpdate();
3902 }
Adam Lesinskie1f480d2017-02-15 18:51:23 -08003903 } catch (RemoteException e) {
3904 // Ignore.
3905 }
3906 }
3907
Dianne Hackborn099bc622014-01-22 13:39:16 -08003908 public void addIsolatedUidLocked(int isolatedUid, int appUid) {
3909 mIsolatedUids.put(isolatedUid, appUid);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08003910 final Uid u = getUidStatsLocked(appUid);
3911 u.addIsolatedUid(isolatedUid);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003912 }
3913
Adam Lesinski61db88f2015-07-01 15:05:07 -07003914 /**
3915 * Schedules a read of the latest cpu times before removing the isolated UID.
3916 * @see #removeIsolatedUidLocked(int)
3917 */
3918 public void scheduleRemoveIsolatedUidLocked(int isolatedUid, int appUid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08003919 int curUid = mIsolatedUids.get(isolatedUid, -1);
3920 if (curUid == appUid) {
Adam Lesinski61db88f2015-07-01 15:05:07 -07003921 if (mExternalSync != null) {
3922 mExternalSync.scheduleCpuSyncDueToRemovedUid(isolatedUid);
3923 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08003924 }
3925 }
3926
Adam Lesinski61db88f2015-07-01 15:05:07 -07003927 /**
3928 * This should only be called after the cpu times have been read.
3929 * @see #scheduleRemoveIsolatedUidLocked(int, int)
3930 */
Andreas Gampe3f24e692018-02-05 13:24:28 -08003931 @GuardedBy("this")
Adam Lesinski61db88f2015-07-01 15:05:07 -07003932 public void removeIsolatedUidLocked(int isolatedUid) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08003933 final int idx = mIsolatedUids.indexOfKey(isolatedUid);
3934 if (idx >= 0) {
3935 final int ownerUid = mIsolatedUids.valueAt(idx);
3936 final Uid u = getUidStatsLocked(ownerUid);
3937 u.removeIsolatedUid(isolatedUid);
3938 mIsolatedUids.removeAt(idx);
3939 }
Mike Ma234d1822018-03-13 18:53:21 -07003940 mPendingRemovedUids.add(new UidToRemove(isolatedUid, mClocks.elapsedRealtime()));
Adam Lesinski61db88f2015-07-01 15:05:07 -07003941 }
3942
Dianne Hackborn099bc622014-01-22 13:39:16 -08003943 public int mapUid(int uid) {
3944 int isolated = mIsolatedUids.get(uid, -1);
3945 return isolated > 0 ? isolated : uid;
3946 }
3947
3948 public void noteEventLocked(int code, String name, int uid) {
3949 uid = mapUid(uid);
Dianne Hackborn37de0982014-05-09 09:32:18 -07003950 if (!mActiveEvents.updateState(code, name, uid, 0)) {
3951 return;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003952 }
Joe Onoratoabded112016-02-08 16:49:39 -08003953 final long elapsedRealtime = mClocks.elapsedRealtime();
3954 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -07003955 addHistoryEventLocked(elapsedRealtime, uptime, code, name, uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003956 }
3957
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003958 public void noteCurrentTimeChangedLocked() {
3959 final long currentTime = System.currentTimeMillis();
Joe Onoratoabded112016-02-08 16:49:39 -08003960 final long elapsedRealtime = mClocks.elapsedRealtime();
3961 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003962 recordCurrentTimeChangeLocked(currentTime, elapsedRealtime, uptime);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003963 }
3964
Dianne Hackborn61659e52014-07-09 16:13:01 -07003965 public void noteProcessStartLocked(String name, int uid) {
3966 uid = mapUid(uid);
3967 if (isOnBattery()) {
3968 Uid u = getUidStatsLocked(uid);
3969 u.getProcessStatsLocked(name).incStartsLocked();
3970 }
3971 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_START, name, uid, 0)) {
3972 return;
3973 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003974 if (!mRecordAllHistory) {
3975 return;
3976 }
Joe Onoratoabded112016-02-08 16:49:39 -08003977 final long elapsedRealtime = mClocks.elapsedRealtime();
3978 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn61659e52014-07-09 16:13:01 -07003979 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_START, name, uid);
3980 }
3981
Dianne Hackborn1e01d162014-12-04 17:46:42 -08003982 public void noteProcessCrashLocked(String name, int uid) {
3983 uid = mapUid(uid);
3984 if (isOnBattery()) {
3985 Uid u = getUidStatsLocked(uid);
3986 u.getProcessStatsLocked(name).incNumCrashesLocked();
3987 }
3988 }
3989
3990 public void noteProcessAnrLocked(String name, int uid) {
3991 uid = mapUid(uid);
3992 if (isOnBattery()) {
3993 Uid u = getUidStatsLocked(uid);
3994 u.getProcessStatsLocked(name).incNumAnrsLocked();
3995 }
3996 }
3997
Dianne Hackborna8d10942015-11-19 17:55:19 -08003998 public void noteUidProcessStateLocked(int uid, int state) {
Amith Yamasanifd3caf62017-07-26 11:48:35 -07003999 int parentUid = mapUid(uid);
4000 if (uid != parentUid) {
4001 // Isolated UIDs process state is already rolled up into parent, so no need to track
4002 // Otherwise the parent's process state will get downgraded incorrectly
4003 return;
4004 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08004005 getUidStatsLocked(uid).updateUidProcessStateLocked(state);
Dianne Hackborn61659e52014-07-09 16:13:01 -07004006 }
4007
4008 public void noteProcessFinishLocked(String name, int uid) {
4009 uid = mapUid(uid);
4010 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_FINISH, name, uid, 0)) {
4011 return;
4012 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004013 if (!mRecordAllHistory) {
4014 return;
4015 }
Joe Onoratoabded112016-02-08 16:49:39 -08004016 final long elapsedRealtime = mClocks.elapsedRealtime();
4017 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004018 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_FINISH, name, uid);
Dianne Hackborn61659e52014-07-09 16:13:01 -07004019 }
4020
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004021 public void noteSyncStartLocked(String name, int uid) {
4022 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004023 final long elapsedRealtime = mClocks.elapsedRealtime();
4024 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004025 getUidStatsLocked(uid).noteStartSyncLocked(name, elapsedRealtime);
4026 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_START, name, uid, 0)) {
4027 return;
4028 }
4029 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_START, name, uid);
4030 }
4031
4032 public void noteSyncFinishLocked(String name, int uid) {
4033 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004034 final long elapsedRealtime = mClocks.elapsedRealtime();
4035 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004036 getUidStatsLocked(uid).noteStopSyncLocked(name, elapsedRealtime);
4037 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_FINISH, name, uid, 0)) {
4038 return;
4039 }
4040 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_FINISH, name, uid);
4041 }
4042
4043 public void noteJobStartLocked(String name, int uid) {
4044 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004045 final long elapsedRealtime = mClocks.elapsedRealtime();
4046 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004047 getUidStatsLocked(uid).noteStartJobLocked(name, elapsedRealtime);
4048 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_START, name, uid, 0)) {
4049 return;
4050 }
4051 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_START, name, uid);
4052 }
4053
Dianne Hackborn94326cb2017-06-28 16:17:20 -07004054 public void noteJobFinishLocked(String name, int uid, int stopReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004055 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004056 final long elapsedRealtime = mClocks.elapsedRealtime();
4057 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07004058 getUidStatsLocked(uid).noteStopJobLocked(name, elapsedRealtime, stopReason);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004059 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_FINISH, name, uid, 0)) {
4060 return;
4061 }
4062 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_FINISH, name, uid);
4063 }
4064
Amith Yamasani977e11f2018-02-16 11:29:54 -08004065 public void noteJobsDeferredLocked(int uid, int numDeferred, long sinceLast) {
4066 uid = mapUid(uid);
4067 getUidStatsLocked(uid).noteJobsDeferredLocked(numDeferred, sinceLast);
4068 }
4069
Narayan Kamath695cf722017-12-21 18:32:47 +00004070 public void noteAlarmStartLocked(String name, WorkSource workSource, int uid) {
4071 noteAlarmStartOrFinishLocked(HistoryItem.EVENT_ALARM_START, name, workSource, uid);
Dianne Hackborn1e383822015-04-10 14:02:33 -07004072 }
4073
Narayan Kamath695cf722017-12-21 18:32:47 +00004074 public void noteAlarmFinishLocked(String name, WorkSource workSource, int uid) {
4075 noteAlarmStartOrFinishLocked(HistoryItem.EVENT_ALARM_FINISH, name, workSource, uid);
4076 }
4077
4078 private void noteAlarmStartOrFinishLocked(int historyItem, String name, WorkSource workSource,
4079 int uid) {
Dianne Hackborn1e383822015-04-10 14:02:33 -07004080 if (!mRecordAllHistory) {
4081 return;
4082 }
Narayan Kamath695cf722017-12-21 18:32:47 +00004083
Joe Onoratoabded112016-02-08 16:49:39 -08004084 final long elapsedRealtime = mClocks.elapsedRealtime();
4085 final long uptime = mClocks.uptimeMillis();
Narayan Kamath695cf722017-12-21 18:32:47 +00004086
4087 if (workSource != null) {
4088 for (int i = 0; i < workSource.size(); ++i) {
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -08004089 uid = mapUid(workSource.getUid(i));
Narayan Kamath695cf722017-12-21 18:32:47 +00004090 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4091 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4092 }
4093 }
4094
4095 List<WorkChain> workChains = workSource.getWorkChains();
4096 if (workChains != null) {
4097 for (int i = 0; i < workChains.size(); ++i) {
4098 uid = mapUid(workChains.get(i).getAttributionUid());
4099 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4100 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4101 }
4102 }
4103 }
4104 } else {
4105 uid = mapUid(uid);
4106
4107 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4108 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4109 }
4110 }
4111 }
4112
4113 public void noteWakupAlarmLocked(String packageName, int uid, WorkSource workSource,
4114 String tag) {
Narayan Kamath695cf722017-12-21 18:32:47 +00004115 if (workSource != null) {
4116 for (int i = 0; i < workSource.size(); ++i) {
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -08004117 uid = workSource.getUid(i);
4118 final String workSourceName = workSource.getPackageName(i);
Narayan Kamath695cf722017-12-21 18:32:47 +00004119
Tej Singh6f724c42018-01-03 20:02:03 -08004120 if (isOnBattery()) {
4121 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid,
4122 workSourceName != null ? workSourceName : packageName);
4123 pkg.noteWakeupAlarmLocked(tag);
4124 }
Narayan Kamath695cf722017-12-21 18:32:47 +00004125 }
4126
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -08004127 List<WorkChain> workChains = workSource.getWorkChains();
Narayan Kamath695cf722017-12-21 18:32:47 +00004128 if (workChains != null) {
4129 for (int i = 0; i < workChains.size(); ++i) {
4130 final WorkChain wc = workChains.get(i);
4131 uid = wc.getAttributionUid();
4132
Tej Singh6f724c42018-01-03 20:02:03 -08004133 if (isOnBattery()) {
4134 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid, packageName);
4135 pkg.noteWakeupAlarmLocked(tag);
4136 }
Narayan Kamath695cf722017-12-21 18:32:47 +00004137 }
4138 }
4139 } else {
Tej Singh6f724c42018-01-03 20:02:03 -08004140 if (isOnBattery()) {
4141 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid, packageName);
4142 pkg.noteWakeupAlarmLocked(tag);
4143 }
Narayan Kamath695cf722017-12-21 18:32:47 +00004144 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07004145 }
4146
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004147 private void requestWakelockCpuUpdate() {
Sudheer Shankac57729a2018-02-09 15:44:42 -08004148 mExternalSync.scheduleCpuSyncDueToWakelockChange(DELAY_UPDATE_WAKELOCKS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004149 }
4150
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004151 private void requestImmediateCpuUpdate() {
Sudheer Shankac57729a2018-02-09 15:44:42 -08004152 mExternalSync.scheduleCpuSyncDueToWakelockChange(0 /* delayMillis */);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004153 }
4154
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004155 public void setRecordAllHistoryLocked(boolean enabled) {
4156 mRecordAllHistory = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004157 if (!enabled) {
4158 // Clear out any existing state.
4159 mActiveEvents.removeEvents(HistoryItem.EVENT_WAKE_LOCK);
Dianne Hackborn1e383822015-04-10 14:02:33 -07004160 mActiveEvents.removeEvents(HistoryItem.EVENT_ALARM);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004161 // Record the currently running processes as stopping, now that we are no
4162 // longer tracking them.
4163 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
4164 HistoryItem.EVENT_PROC);
4165 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08004166 long mSecRealtime = mClocks.elapsedRealtime();
4167 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004168 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
4169 SparseIntArray uids = ent.getValue();
4170 for (int j=0; j<uids.size(); j++) {
4171 addHistoryEventLocked(mSecRealtime, mSecUptime,
4172 HistoryItem.EVENT_PROC_FINISH, ent.getKey(), uids.keyAt(j));
4173 }
4174 }
4175 }
4176 } else {
4177 // Record the currently running processes as starting, now that we are tracking them.
4178 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
4179 HistoryItem.EVENT_PROC);
4180 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08004181 long mSecRealtime = mClocks.elapsedRealtime();
4182 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004183 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
4184 SparseIntArray uids = ent.getValue();
4185 for (int j=0; j<uids.size(); j++) {
4186 addHistoryEventLocked(mSecRealtime, mSecUptime,
4187 HistoryItem.EVENT_PROC_START, ent.getKey(), uids.keyAt(j));
4188 }
4189 }
4190 }
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004191 }
4192 }
4193
Dianne Hackborn9a755432014-05-15 17:05:22 -07004194 public void setNoAutoReset(boolean enabled) {
4195 mNoAutoReset = enabled;
4196 }
4197
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004198 public void setPretendScreenOff(boolean pretendScreenOff) {
Mike Mac2f518a2017-09-19 16:06:03 -07004199 if (mPretendScreenOff != pretendScreenOff) {
4200 mPretendScreenOff = pretendScreenOff;
4201 noteScreenStateLocked(pretendScreenOff ? Display.STATE_OFF : Display.STATE_ON);
4202 }
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004203 }
4204
Dianne Hackborn9a755432014-05-15 17:05:22 -07004205 private String mInitialAcquireWakeName;
4206 private int mInitialAcquireWakeUid = -1;
4207
Narayan Kamath81822022017-12-08 11:56:01 +00004208 public void noteStartWakeLocked(int uid, int pid, WorkChain wc, String name, String historyName,
4209 int type, boolean unimportantForLogging, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004210 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004211 if (type == WAKE_TYPE_PARTIAL) {
4212 // Only care about partial wake locks, since full wake locks
4213 // will be canceled when the user puts the screen to sleep.
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004214 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07004215 if (historyName == null) {
4216 historyName = name;
4217 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004218 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07004219 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_START, historyName,
4220 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07004221 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07004222 HistoryItem.EVENT_WAKE_LOCK_START, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07004223 }
4224 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004225 if (mWakeLockNesting == 0) {
4226 mHistoryCur.states |= HistoryItem.STATE_WAKE_LOCK_FLAG;
4227 if (DEBUG_HISTORY) Slog.v(TAG, "Start wake lock to: "
4228 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08004229 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004230 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07004231 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004232 mWakeLockImportant = !unimportantForLogging;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004233 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07004234 } else if (!mWakeLockImportant && !unimportantForLogging
4235 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004236 if (mHistoryLastWritten.wakelockTag != null) {
4237 // We'll try to update the last tag.
4238 mHistoryLastWritten.wakelockTag = null;
4239 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004240 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07004241 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004242 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004243 }
4244 mWakeLockImportant = true;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004245 }
4246 mWakeLockNesting++;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004247 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004248 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07004249 if (mOnBatteryScreenOffTimeBase.isRunning()) {
4250 // We only update the cpu time when a wake lock is acquired if the screen is off.
4251 // If the screen is on, we don't distribute the power amongst partial wakelocks.
4252 if (DEBUG_ENERGY_CPU) {
4253 Slog.d(TAG, "Updating cpu time because of +wake_lock");
4254 }
4255 requestWakelockCpuUpdate();
4256 }
Narayan Kamath81822022017-12-08 11:56:01 +00004257
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004258 getUidStatsLocked(uid).noteStartWakeLocked(pid, name, type, elapsedRealtime);
Narayan Kamath81822022017-12-08 11:56:01 +00004259
Yangster-mac20877162017-12-22 17:19:39 -08004260 if (wc != null) {
Bookatz1a1b0462018-01-12 11:47:03 -08004261 StatsLog.write(StatsLog.WAKELOCK_STATE_CHANGED, wc.getUids(), wc.getTags(),
Bookatz90867622018-01-31 15:05:57 -08004262 getPowerManagerWakeLockLevel(type), name,
4263 StatsLog.WAKELOCK_STATE_CHANGED__STATE__ACQUIRE);
Yangster-macafad8c62018-01-05 22:30:49 -08004264 } else {
Bookatz1a1b0462018-01-12 11:47:03 -08004265 StatsLog.write_non_chained(StatsLog.WAKELOCK_STATE_CHANGED, uid, null,
Bookatz90867622018-01-31 15:05:57 -08004266 getPowerManagerWakeLockLevel(type), name,
4267 StatsLog.WAKELOCK_STATE_CHANGED__STATE__ACQUIRE);
Narayan Kamath81822022017-12-08 11:56:01 +00004268 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004269 }
4270 }
4271
Narayan Kamath81822022017-12-08 11:56:01 +00004272 public void noteStopWakeLocked(int uid, int pid, WorkChain wc, String name, String historyName,
4273 int type, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004274 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004275 if (type == WAKE_TYPE_PARTIAL) {
4276 mWakeLockNesting--;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004277 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07004278 if (historyName == null) {
4279 historyName = name;
4280 }
4281 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName,
4282 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07004283 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07004284 HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07004285 }
4286 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004287 if (mWakeLockNesting == 0) {
4288 mHistoryCur.states &= ~HistoryItem.STATE_WAKE_LOCK_FLAG;
4289 if (DEBUG_HISTORY) Slog.v(TAG, "Stop wake lock to: "
4290 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn37de0982014-05-09 09:32:18 -07004291 mInitialAcquireWakeName = null;
4292 mInitialAcquireWakeUid = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004293 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004294 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004295 }
4296 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07004297 if (mOnBatteryScreenOffTimeBase.isRunning()) {
4298 if (DEBUG_ENERGY_CPU) {
4299 Slog.d(TAG, "Updating cpu time because of -wake_lock");
4300 }
4301 requestWakelockCpuUpdate();
4302 }
Narayan Kamath81822022017-12-08 11:56:01 +00004303
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004304 getUidStatsLocked(uid).noteStopWakeLocked(pid, name, type, elapsedRealtime);
Yangster-mac20877162017-12-22 17:19:39 -08004305 if (wc != null) {
Bookatz1a1b0462018-01-12 11:47:03 -08004306 StatsLog.write(StatsLog.WAKELOCK_STATE_CHANGED, wc.getUids(), wc.getTags(),
Bookatz90867622018-01-31 15:05:57 -08004307 getPowerManagerWakeLockLevel(type), name,
4308 StatsLog.WAKELOCK_STATE_CHANGED__STATE__RELEASE);
Yangster-macafad8c62018-01-05 22:30:49 -08004309 } else {
Bookatz1a1b0462018-01-12 11:47:03 -08004310 StatsLog.write_non_chained(StatsLog.WAKELOCK_STATE_CHANGED, uid, null,
Bookatz90867622018-01-31 15:05:57 -08004311 getPowerManagerWakeLockLevel(type), name,
4312 StatsLog.WAKELOCK_STATE_CHANGED__STATE__RELEASE);
Narayan Kamath81822022017-12-08 11:56:01 +00004313 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004314 }
4315 }
4316
Bookatz1a1b0462018-01-12 11:47:03 -08004317 /**
4318 * Converts BatteryStats wakelock types back into PowerManager wakelock levels.
4319 * This is the inverse map of Notifier.getBatteryStatsWakeLockMonitorType().
4320 * These are estimations, since batterystats loses some of the original data.
4321 * TODO: Delete this. Instead, StatsLog.write should be called from PowerManager's Notifier.
4322 */
4323 private int getPowerManagerWakeLockLevel(int battertStatsWakelockType) {
4324 switch (battertStatsWakelockType) {
4325 // PowerManager.PARTIAL_WAKE_LOCK or PROXIMITY_SCREEN_OFF_WAKE_LOCK
4326 case BatteryStats.WAKE_TYPE_PARTIAL:
4327 return PowerManager.PARTIAL_WAKE_LOCK;
4328
4329 // PowerManager.SCREEN_DIM_WAKE_LOCK or SCREEN_BRIGHT_WAKE_LOCK
4330 case BatteryStats.WAKE_TYPE_FULL:
4331 return PowerManager.FULL_WAKE_LOCK;
4332
4333 case BatteryStats.WAKE_TYPE_DRAW:
4334 return PowerManager.DRAW_WAKE_LOCK;
4335
4336 // It appears that nothing can ever make a Window and PowerManager lacks an equivalent.
4337 case BatteryStats.WAKE_TYPE_WINDOW:
4338 Slog.e(TAG, "Illegal window wakelock type observed in batterystats.");
4339 return -1;
4340
4341 default:
4342 Slog.e(TAG, "Illegal wakelock type in batterystats: " + battertStatsWakelockType);
4343 return -1;
4344 }
4345 }
4346
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004347 public void noteStartWakeFromSourceLocked(WorkSource ws, int pid, String name,
4348 String historyName, int type, boolean unimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08004349 final long elapsedRealtime = mClocks.elapsedRealtime();
4350 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004351 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004352 for (int i=0; i<N; i++) {
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -08004353 noteStartWakeLocked(ws.getUid(i), pid, null, name, historyName, type,
Narayan Kamath81822022017-12-08 11:56:01 +00004354 unimportantForLogging, elapsedRealtime, uptime);
4355 }
4356
4357 List<WorkChain> wcs = ws.getWorkChains();
4358 if (wcs != null) {
4359 for (int i = 0; i < wcs.size(); ++i) {
4360 final WorkChain wc = wcs.get(i);
4361 noteStartWakeLocked(wc.getAttributionUid(), pid, wc, name, historyName, type,
4362 unimportantForLogging, elapsedRealtime, uptime);
4363 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004364 }
4365 }
4366
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004367 public void noteChangeWakelockFromSourceLocked(WorkSource ws, int pid, String name,
4368 String historyName, int type, WorkSource newWs, int newPid, String newName,
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004369 String newHistoryName, int newType, boolean newUnimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08004370 final long elapsedRealtime = mClocks.elapsedRealtime();
4371 final long uptime = mClocks.uptimeMillis();
Narayan Kamath81822022017-12-08 11:56:01 +00004372
4373 List<WorkChain>[] wcs = WorkSource.diffChains(ws, newWs);
4374
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004375 // For correct semantics, we start the need worksources first, so that we won't
4376 // make inappropriate history items as if all wake locks went away and new ones
4377 // appeared. This is okay because tracking of wake locks allows nesting.
Narayan Kamath81822022017-12-08 11:56:01 +00004378 //
4379 // First the starts :
Dianne Hackborn40c87252014-03-19 16:55:40 -07004380 final int NN = newWs.size();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004381 for (int i=0; i<NN; i++) {
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -08004382 noteStartWakeLocked(newWs.getUid(i), newPid, null, newName, newHistoryName, newType,
Dianne Hackborn40c87252014-03-19 16:55:40 -07004383 newUnimportantForLogging, elapsedRealtime, uptime);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004384 }
Narayan Kamath81822022017-12-08 11:56:01 +00004385 if (wcs != null) {
4386 List<WorkChain> newChains = wcs[0];
4387 if (newChains != null) {
4388 for (int i = 0; i < newChains.size(); ++i) {
4389 final WorkChain newChain = newChains.get(i);
4390 noteStartWakeLocked(newChain.getAttributionUid(), newPid, newChain, newName,
4391 newHistoryName, newType, newUnimportantForLogging, elapsedRealtime,
4392 uptime);
4393 }
4394 }
4395 }
4396
4397 // Then the stops :
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004398 final int NO = ws.size();
4399 for (int i=0; i<NO; i++) {
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -08004400 noteStopWakeLocked(ws.getUid(i), pid, null, name, historyName, type, elapsedRealtime,
Narayan Kamath81822022017-12-08 11:56:01 +00004401 uptime);
4402 }
4403 if (wcs != null) {
4404 List<WorkChain> goneChains = wcs[1];
4405 if (goneChains != null) {
4406 for (int i = 0; i < goneChains.size(); ++i) {
4407 final WorkChain goneChain = goneChains.get(i);
4408 noteStopWakeLocked(goneChain.getAttributionUid(), pid, goneChain, name,
4409 historyName, type, elapsedRealtime, uptime);
4410 }
4411 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004412 }
4413 }
4414
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004415 public void noteStopWakeFromSourceLocked(WorkSource ws, int pid, String name,
4416 String historyName, int type) {
Joe Onoratoabded112016-02-08 16:49:39 -08004417 final long elapsedRealtime = mClocks.elapsedRealtime();
4418 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004419 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004420 for (int i=0; i<N; i++) {
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -08004421 noteStopWakeLocked(ws.getUid(i), pid, null, name, historyName, type, elapsedRealtime,
Narayan Kamath81822022017-12-08 11:56:01 +00004422 uptime);
4423 }
4424
4425 List<WorkChain> wcs = ws.getWorkChains();
4426 if (wcs != null) {
4427 for (int i = 0; i < wcs.size(); ++i) {
4428 final WorkChain wc = wcs.get(i);
4429 noteStopWakeLocked(wc.getAttributionUid(), pid, wc, name, historyName, type,
4430 elapsedRealtime, uptime);
4431 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004432 }
4433 }
4434
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004435 public void noteLongPartialWakelockStart(String name, String historyName, int uid) {
4436 uid = mapUid(uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004437 noteLongPartialWakeLockStartInternal(name, historyName, uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004438 }
4439
4440 public void noteLongPartialWakelockStartFromSource(String name, String historyName,
4441 WorkSource workSource) {
4442 final int N = workSource.size();
4443 for (int i = 0; i < N; ++i) {
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -08004444 final int uid = mapUid(workSource.getUid(i));
Narayan Kamath96a92562018-01-02 18:57:17 +00004445 noteLongPartialWakeLockStartInternal(name, historyName, uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004446 }
4447
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -08004448 final List<WorkChain> workChains = workSource.getWorkChains();
Narayan Kamath96a92562018-01-02 18:57:17 +00004449 if (workChains != null) {
4450 for (int i = 0; i < workChains.size(); ++i) {
4451 final WorkChain workChain = workChains.get(i);
4452 final int uid = workChain.getAttributionUid();
4453 noteLongPartialWakeLockStartInternal(name, historyName, uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004454 }
4455 }
4456 }
4457
4458 private void noteLongPartialWakeLockStartInternal(String name, String historyName, int uid) {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004459 final long elapsedRealtime = mClocks.elapsedRealtime();
4460 final long uptime = mClocks.uptimeMillis();
4461 if (historyName == null) {
4462 historyName = name;
4463 }
4464 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_START, historyName, uid,
4465 0)) {
4466 return;
4467 }
4468 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_START,
4469 historyName, uid);
4470 }
4471
4472 public void noteLongPartialWakelockFinish(String name, String historyName, int uid) {
4473 uid = mapUid(uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004474 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004475 }
4476
4477 public void noteLongPartialWakelockFinishFromSource(String name, String historyName,
4478 WorkSource workSource) {
4479 final int N = workSource.size();
4480 for (int i = 0; i < N; ++i) {
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -08004481 final int uid = mapUid(workSource.getUid(i));
Narayan Kamath96a92562018-01-02 18:57:17 +00004482 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004483 }
4484
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -08004485 final List<WorkChain> workChains = workSource.getWorkChains();
Narayan Kamath96a92562018-01-02 18:57:17 +00004486 if (workChains != null) {
4487 for (int i = 0; i < workChains.size(); ++i) {
4488 final WorkChain workChain = workChains.get(i);
4489 final int uid = workChain.getAttributionUid();
Narayan Kamath96a92562018-01-02 18:57:17 +00004490 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004491 }
4492 }
4493 }
4494
4495 private void noteLongPartialWakeLockFinishInternal(String name, String historyName, int uid) {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004496 final long elapsedRealtime = mClocks.elapsedRealtime();
4497 final long uptime = mClocks.uptimeMillis();
4498 if (historyName == null) {
4499 historyName = name;
4500 }
4501 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH, historyName, uid,
4502 0)) {
4503 return;
4504 }
4505 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH,
4506 historyName, uid);
4507 }
4508
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004509 void aggregateLastWakeupUptimeLocked(long uptimeMs) {
4510 if (mLastWakeupReason != null) {
4511 long deltaUptime = uptimeMs - mLastWakeupUptimeMs;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004512 SamplingTimer timer = getWakeupReasonTimerLocked(mLastWakeupReason);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07004513 timer.add(deltaUptime * 1000, 1); // time in in microseconds
Bookatz90867622018-01-31 15:05:57 -08004514 StatsLog.write(StatsLog.KERNEL_WAKEUP_REPORTED, mLastWakeupReason,
4515 /* duration_usec */ deltaUptime * 1000);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004516 mLastWakeupReason = null;
4517 }
4518 }
4519
4520 public void noteWakeupReasonLocked(String reason) {
Joe Onoratoabded112016-02-08 16:49:39 -08004521 final long elapsedRealtime = mClocks.elapsedRealtime();
4522 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004523 if (DEBUG_HISTORY) Slog.v(TAG, "Wakeup reason \"" + reason +"\": "
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004524 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004525 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004526 mHistoryCur.wakeReasonTag = mHistoryCur.localWakeReasonTag;
4527 mHistoryCur.wakeReasonTag.string = reason;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004528 mHistoryCur.wakeReasonTag.uid = 0;
4529 mLastWakeupReason = reason;
4530 mLastWakeupUptimeMs = uptime;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004531 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004532 }
4533
Adam Lesinski72478f02015-06-17 15:39:43 -07004534 public boolean startAddingCpuLocked() {
Sudheer Shankac57729a2018-02-09 15:44:42 -08004535 mExternalSync.cancelCpuSyncDueToWakelockChange();
Adam Lesinski72478f02015-06-17 15:39:43 -07004536 return mOnBatteryInternal;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004537 }
4538
Adam Lesinski72478f02015-06-17 15:39:43 -07004539 public void finishAddingCpuLocked(int totalUTime, int totalSTime, int statUserTime,
4540 int statSystemTime, int statIOWaitTime, int statIrqTime,
4541 int statSoftIrqTime, int statIdleTime) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004542 if (DEBUG) Slog.d(TAG, "Adding cpu: tuser=" + totalUTime + " tsys=" + totalSTime
4543 + " user=" + statUserTime + " sys=" + statSystemTime
4544 + " io=" + statIOWaitTime + " irq=" + statIrqTime
4545 + " sirq=" + statSoftIrqTime + " idle=" + statIdleTime);
4546 mCurStepCpuUserTime += totalUTime;
4547 mCurStepCpuSystemTime += totalSTime;
4548 mCurStepStatUserTime += statUserTime;
4549 mCurStepStatSystemTime += statSystemTime;
4550 mCurStepStatIOWaitTime += statIOWaitTime;
4551 mCurStepStatIrqTime += statIrqTime;
4552 mCurStepStatSoftIrqTime += statSoftIrqTime;
4553 mCurStepStatIdleTime += statIdleTime;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004554 }
4555
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004556 public void noteProcessDiedLocked(int uid, int pid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004557 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004558 Uid u = mUidStats.get(uid);
4559 if (u != null) {
4560 u.mPids.remove(pid);
4561 }
4562 }
4563
4564 public long getProcessWakeTime(int uid, int pid, long realtime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004565 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004566 Uid u = mUidStats.get(uid);
4567 if (u != null) {
4568 Uid.Pid p = u.mPids.get(pid);
4569 if (p != null) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004570 return p.mWakeSumMs + (p.mWakeNesting > 0 ? (realtime - p.mWakeStartMs) : 0);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004571 }
4572 }
4573 return 0;
4574 }
4575
Dianne Hackborn287952c2010-09-22 22:34:31 -07004576 public void reportExcessiveCpuLocked(int uid, String proc, long overTime, long usedTime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004577 uid = mapUid(uid);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004578 Uid u = mUidStats.get(uid);
4579 if (u != null) {
4580 u.reportExcessiveCpuLocked(proc, overTime, usedTime);
4581 }
4582 }
4583
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004584 int mSensorNesting;
4585
4586 public void noteStartSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004587 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004588 final long elapsedRealtime = mClocks.elapsedRealtime();
4589 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004590 if (mSensorNesting == 0) {
4591 mHistoryCur.states |= HistoryItem.STATE_SENSOR_ON_FLAG;
4592 if (DEBUG_HISTORY) Slog.v(TAG, "Start sensor to: "
4593 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004594 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004595 }
4596 mSensorNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004597 getUidStatsLocked(uid).noteStartSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004598 }
4599
4600 public void noteStopSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004601 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004602 final long elapsedRealtime = mClocks.elapsedRealtime();
4603 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004604 mSensorNesting--;
4605 if (mSensorNesting == 0) {
4606 mHistoryCur.states &= ~HistoryItem.STATE_SENSOR_ON_FLAG;
4607 if (DEBUG_HISTORY) Slog.v(TAG, "Stop sensor to: "
4608 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004609 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004610 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004611 getUidStatsLocked(uid).noteStopSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004612 }
4613
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004614 int mGpsNesting;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004615
Narayan Kamath32684dd2018-01-08 17:32:51 +00004616 public void noteGpsChangedLocked(WorkSource oldWs, WorkSource newWs) {
4617 for (int i = 0; i < newWs.size(); ++i) {
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -08004618 noteStartGpsLocked(newWs.getUid(i), null);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004619 }
4620
4621 for (int i = 0; i < oldWs.size(); ++i) {
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -08004622 noteStopGpsLocked((oldWs.getUid(i)), null);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004623 }
4624
4625 List<WorkChain>[] wcs = WorkSource.diffChains(oldWs, newWs);
4626 if (wcs != null) {
4627 if (wcs[0] != null) {
4628 final List<WorkChain> newChains = wcs[0];
4629 for (int i = 0; i < newChains.size(); ++i) {
4630 noteStartGpsLocked(-1, newChains.get(i));
4631 }
4632 }
4633
4634 if (wcs[1] != null) {
4635 final List<WorkChain> goneChains = wcs[1];
4636 for (int i = 0; i < goneChains.size(); ++i) {
4637 noteStopGpsLocked(-1, goneChains.get(i));
4638 }
4639 }
4640 }
4641 }
4642
4643 private void noteStartGpsLocked(int uid, WorkChain workChain) {
4644 uid = getAttributionUid(uid, workChain);
Joe Onoratoabded112016-02-08 16:49:39 -08004645 final long elapsedRealtime = mClocks.elapsedRealtime();
4646 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004647 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004648 mHistoryCur.states |= HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004649 if (DEBUG_HISTORY) Slog.v(TAG, "Start GPS to: "
4650 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004651 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004652 }
4653 mGpsNesting++;
Narayan Kamath32684dd2018-01-08 17:32:51 +00004654
4655 if (workChain == null) {
Bookatz90867622018-01-31 15:05:57 -08004656 StatsLog.write_non_chained(StatsLog.GPS_SCAN_STATE_CHANGED, uid, null,
4657 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004658 } else {
4659 StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004660 workChain.getUids(), workChain.getTags(),
4661 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004662 }
4663
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004664 getUidStatsLocked(uid).noteStartGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004665 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004666
Narayan Kamath32684dd2018-01-08 17:32:51 +00004667 private void noteStopGpsLocked(int uid, WorkChain workChain) {
4668 uid = getAttributionUid(uid, workChain);
Joe Onoratoabded112016-02-08 16:49:39 -08004669 final long elapsedRealtime = mClocks.elapsedRealtime();
4670 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004671 mGpsNesting--;
4672 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004673 mHistoryCur.states &= ~HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004674 if (DEBUG_HISTORY) Slog.v(TAG, "Stop GPS to: "
4675 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004676 addHistoryRecordLocked(elapsedRealtime, uptime);
Siddharth Ray78ccaf52017-12-23 16:16:21 -08004677 stopAllGpsSignalQualityTimersLocked(-1);
4678 mGpsSignalQualityBin = -1;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004679 }
Narayan Kamath32684dd2018-01-08 17:32:51 +00004680
4681 if (workChain == null) {
Bookatz90867622018-01-31 15:05:57 -08004682 StatsLog.write_non_chained(StatsLog.GPS_SCAN_STATE_CHANGED, uid, null,
4683 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004684 } else {
4685 StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED, workChain.getUids(),
Bookatz90867622018-01-31 15:05:57 -08004686 workChain.getTags(), StatsLog.GPS_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004687 }
4688
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004689 getUidStatsLocked(uid).noteStopGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004690 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07004691
Siddharth Ray78ccaf52017-12-23 16:16:21 -08004692 public void noteGpsSignalQualityLocked(int signalLevel) {
4693 if (mGpsNesting == 0) {
4694 return;
4695 }
4696 if (signalLevel < 0 || signalLevel >= GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS) {
4697 stopAllGpsSignalQualityTimersLocked(-1);
4698 return;
4699 }
4700 final long elapsedRealtime = mClocks.elapsedRealtime();
4701 final long uptime = mClocks.uptimeMillis();
4702 if (mGpsSignalQualityBin != signalLevel) {
4703 if (mGpsSignalQualityBin >= 0) {
4704 mGpsSignalQualityTimer[mGpsSignalQualityBin].stopRunningLocked(elapsedRealtime);
4705 }
4706 if(!mGpsSignalQualityTimer[signalLevel].isRunningLocked()) {
4707 mGpsSignalQualityTimer[signalLevel].startRunningLocked(elapsedRealtime);
4708 }
4709 mHistoryCur.states2 = (mHistoryCur.states2&~HistoryItem.STATE2_GPS_SIGNAL_QUALITY_MASK)
4710 | (signalLevel << HistoryItem.STATE2_GPS_SIGNAL_QUALITY_SHIFT);
4711 addHistoryRecordLocked(elapsedRealtime, uptime);
4712 mGpsSignalQualityBin = signalLevel;
4713 }
4714 return;
4715 }
4716
Andreas Gampe3f24e692018-02-05 13:24:28 -08004717 @GuardedBy("this")
Jeff Browne95c3cd2014-05-02 16:59:26 -07004718 public void noteScreenStateLocked(int state) {
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004719 state = mPretendScreenOff ? Display.STATE_OFF : state;
Santos Cordone94f0502017-02-24 12:31:20 -08004720
4721 // Battery stats relies on there being 4 states. To accommodate this, new states beyond the
4722 // original 4 are mapped to one of the originals.
4723 if (state > MAX_TRACKED_SCREEN_STATE) {
4724 switch (state) {
4725 case Display.STATE_VR:
4726 state = Display.STATE_ON;
4727 break;
4728 default:
4729 Slog.wtf(TAG, "Unknown screen state (not mapped): " + state);
4730 break;
4731 }
4732 }
4733
Jeff Browne95c3cd2014-05-02 16:59:26 -07004734 if (mScreenState != state) {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08004735 recordDailyStatsIfNeededLocked(true);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004736 final int oldState = mScreenState;
4737 mScreenState = state;
4738 if (DEBUG) Slog.v(TAG, "Screen state: oldState=" + Display.stateToString(oldState)
4739 + ", newState=" + Display.stateToString(state));
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004740
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004741 if (state != Display.STATE_UNKNOWN) {
4742 int stepState = state-1;
Santos Cordone94f0502017-02-24 12:31:20 -08004743 if ((stepState & STEP_LEVEL_MODE_SCREEN_STATE) == stepState) {
4744 mModStepMode |= (mCurStepMode & STEP_LEVEL_MODE_SCREEN_STATE) ^ stepState;
4745 mCurStepMode = (mCurStepMode & ~STEP_LEVEL_MODE_SCREEN_STATE) | stepState;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004746 } else {
4747 Slog.wtf(TAG, "Unexpected screen state: " + state);
4748 }
4749 }
4750
Mike Mac2f518a2017-09-19 16:06:03 -07004751 final long elapsedRealtime = mClocks.elapsedRealtime();
4752 final long uptime = mClocks.uptimeMillis();
4753
4754 boolean updateHistory = false;
zhuguangqingf052e8e2019-07-31 11:51:23 +08004755 if (isScreenDoze(state) && !isScreenDoze(oldState)) {
Mike Mac2f518a2017-09-19 16:06:03 -07004756 mHistoryCur.states |= HistoryItem.STATE_SCREEN_DOZE_FLAG;
4757 mScreenDozeTimer.startRunningLocked(elapsedRealtime);
4758 updateHistory = true;
zhuguangqingf052e8e2019-07-31 11:51:23 +08004759 } else if (isScreenDoze(oldState) && !isScreenDoze(state)) {
Mike Mac2f518a2017-09-19 16:06:03 -07004760 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_DOZE_FLAG;
4761 mScreenDozeTimer.stopRunningLocked(elapsedRealtime);
4762 updateHistory = true;
4763 }
4764 if (isScreenOn(state)) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07004765 mHistoryCur.states |= HistoryItem.STATE_SCREEN_ON_FLAG;
4766 if (DEBUG_HISTORY) Slog.v(TAG, "Screen on to: "
4767 + Integer.toHexString(mHistoryCur.states));
Jeff Browne95c3cd2014-05-02 16:59:26 -07004768 mScreenOnTimer.startRunningLocked(elapsedRealtime);
4769 if (mScreenBrightnessBin >= 0) {
4770 mScreenBrightnessTimer[mScreenBrightnessBin].startRunningLocked(elapsedRealtime);
4771 }
Mike Mac2f518a2017-09-19 16:06:03 -07004772 updateHistory = true;
4773 } else if (isScreenOn(oldState)) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07004774 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_ON_FLAG;
4775 if (DEBUG_HISTORY) Slog.v(TAG, "Screen off to: "
4776 + Integer.toHexString(mHistoryCur.states));
Jeff Browne95c3cd2014-05-02 16:59:26 -07004777 mScreenOnTimer.stopRunningLocked(elapsedRealtime);
4778 if (mScreenBrightnessBin >= 0) {
4779 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
4780 }
Mike Mac2f518a2017-09-19 16:06:03 -07004781 updateHistory = true;
4782 }
4783 if (updateHistory) {
4784 if (DEBUG_HISTORY) Slog.v(TAG, "Screen state to: "
4785 + Display.stateToString(state));
4786 addHistoryRecordLocked(elapsedRealtime, uptime);
4787 }
Sudheer Shankac57729a2018-02-09 15:44:42 -08004788 mExternalSync.scheduleCpuSyncDueToScreenStateChange(
4789 mOnBatteryTimeBase.isRunning(), mOnBatteryScreenOffTimeBase.isRunning());
Mike Mac2f518a2017-09-19 16:06:03 -07004790 if (isScreenOn(state)) {
4791 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), state,
4792 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
4793 // Fake a wake lock, so we consider the device waked as long as the screen is on.
Narayan Kamath81822022017-12-08 11:56:01 +00004794 noteStartWakeLocked(-1, -1, null, "screen", null, WAKE_TYPE_PARTIAL, false,
Mike Mac2f518a2017-09-19 16:06:03 -07004795 elapsedRealtime, uptime);
4796 } else if (isScreenOn(oldState)) {
Narayan Kamath81822022017-12-08 11:56:01 +00004797 noteStopWakeLocked(-1, -1, null, "screen", "screen", WAKE_TYPE_PARTIAL,
Jeff Browne95c3cd2014-05-02 16:59:26 -07004798 elapsedRealtime, uptime);
Mike Mac2f518a2017-09-19 16:06:03 -07004799 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), state,
Joe Onoratoabded112016-02-08 16:49:39 -08004800 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
Mike Mac2f518a2017-09-19 16:06:03 -07004801 }
4802 // Update discharge amounts.
4803 if (mOnBatteryInternal) {
4804 updateDischargeScreenLevelsLocked(oldState, state);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08004805 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07004806 }
4807 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004808
Mathew Inwoodaf972c82018-08-20 14:13:20 +01004809 @UnsupportedAppUsage
Dianne Hackborn617f8772009-03-31 15:04:46 -07004810 public void noteScreenBrightnessLocked(int brightness) {
4811 // Bin the brightness.
4812 int bin = brightness / (256/NUM_SCREEN_BRIGHTNESS_BINS);
4813 if (bin < 0) bin = 0;
4814 else if (bin >= NUM_SCREEN_BRIGHTNESS_BINS) bin = NUM_SCREEN_BRIGHTNESS_BINS-1;
4815 if (mScreenBrightnessBin != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08004816 final long elapsedRealtime = mClocks.elapsedRealtime();
4817 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004818 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_BRIGHTNESS_MASK)
4819 | (bin << HistoryItem.STATE_BRIGHTNESS_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004820 if (DEBUG_HISTORY) Slog.v(TAG, "Screen brightness " + bin + " to: "
4821 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004822 addHistoryRecordLocked(elapsedRealtime, uptime);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004823 if (mScreenState == Display.STATE_ON) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07004824 if (mScreenBrightnessBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004825 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07004826 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004827 mScreenBrightnessTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07004828 }
4829 mScreenBrightnessBin = bin;
4830 }
4831 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004832
Mathew Inwoodaf972c82018-08-20 14:13:20 +01004833 @UnsupportedAppUsage
Dianne Hackborn617f8772009-03-31 15:04:46 -07004834 public void noteUserActivityLocked(int uid, int event) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08004835 if (mOnBatteryInternal) {
4836 uid = mapUid(uid);
4837 getUidStatsLocked(uid).noteUserActivityLocked(event);
4838 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004839 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004840
Dianne Hackborn280a64e2015-07-13 14:48:08 -07004841 public void noteWakeUpLocked(String reason, int reasonUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004842 final long elapsedRealtime = mClocks.elapsedRealtime();
4843 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn280a64e2015-07-13 14:48:08 -07004844 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SCREEN_WAKE_UP,
4845 reason, reasonUid);
4846 }
4847
Jeff Browne95c3cd2014-05-02 16:59:26 -07004848 public void noteInteractiveLocked(boolean interactive) {
4849 if (mInteractive != interactive) {
Joe Onoratoabded112016-02-08 16:49:39 -08004850 final long elapsedRealtime = mClocks.elapsedRealtime();
Jeff Browne95c3cd2014-05-02 16:59:26 -07004851 mInteractive = interactive;
4852 if (DEBUG) Slog.v(TAG, "Interactive: " + interactive);
4853 if (interactive) {
4854 mInteractiveTimer.startRunningLocked(elapsedRealtime);
4855 } else {
4856 mInteractiveTimer.stopRunningLocked(elapsedRealtime);
4857 }
4858 }
4859 }
4860
Dianne Hackborn1e01d162014-12-04 17:46:42 -08004861 public void noteConnectivityChangedLocked(int type, String extra) {
Joe Onoratoabded112016-02-08 16:49:39 -08004862 final long elapsedRealtime = mClocks.elapsedRealtime();
4863 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08004864 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_CONNECTIVITY_CHANGED,
4865 extra, type);
4866 mNumConnectivityChange++;
4867 }
4868
Adam Lesinski5f056f62016-07-14 16:56:08 -07004869 private void noteMobileRadioApWakeupLocked(final long elapsedRealtimeMillis,
4870 final long uptimeMillis, int uid) {
4871 uid = mapUid(uid);
4872 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
4873 uid);
4874 getUidStatsLocked(uid).noteMobileRadioApWakeupLocked();
4875 }
4876
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004877 /**
4878 * Updates the radio power state and returns true if an external stats collection should occur.
4879 */
4880 public boolean noteMobileRadioPowerStateLocked(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004881 final long elapsedRealtime = mClocks.elapsedRealtime();
4882 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004883 if (mMobileRadioPowerState != powerState) {
4884 long realElapsedRealtimeMs;
4885 final boolean active =
4886 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
4887 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
4888 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07004889 if (uid > 0) {
4890 noteMobileRadioApWakeupLocked(elapsedRealtime, uptime, uid);
4891 }
4892
Adam Lesinski9acfd812016-04-19 18:29:50 -07004893 mMobileRadioActiveStartTime = realElapsedRealtimeMs = timestampNs / (1000 * 1000);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004894 mHistoryCur.states |= HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
4895 } else {
4896 realElapsedRealtimeMs = timestampNs / (1000*1000);
Dianne Hackbornf7097a52014-05-13 09:56:14 -07004897 long lastUpdateTimeMs = mMobileRadioActiveStartTime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004898 if (realElapsedRealtimeMs < lastUpdateTimeMs) {
4899 Slog.wtf(TAG, "Data connection inactive timestamp " + realElapsedRealtimeMs
4900 + " is before start time " + lastUpdateTimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004901 realElapsedRealtimeMs = elapsedRealtime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004902 } else if (realElapsedRealtimeMs < elapsedRealtime) {
4903 mMobileRadioActiveAdjustedTime.addCountLocked(elapsedRealtime
4904 - realElapsedRealtimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004905 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004906 mHistoryCur.states &= ~HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
4907 }
4908 if (DEBUG_HISTORY) Slog.v(TAG, "Mobile network active " + active + " to: "
4909 + Integer.toHexString(mHistoryCur.states));
4910 addHistoryRecordLocked(elapsedRealtime, uptime);
4911 mMobileRadioPowerState = powerState;
4912 if (active) {
4913 mMobileRadioActiveTimer.startRunningLocked(elapsedRealtime);
4914 mMobileRadioActivePerAppTimer.startRunningLocked(elapsedRealtime);
4915 } else {
4916 mMobileRadioActiveTimer.stopRunningLocked(realElapsedRealtimeMs);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004917 mMobileRadioActivePerAppTimer.stopRunningLocked(realElapsedRealtimeMs);
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004918 // Tell the caller to collect radio network/power stats.
4919 return true;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004920 }
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004921 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004922 return false;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004923 }
4924
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004925 public void notePowerSaveModeLocked(boolean enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004926 if (mPowerSaveModeEnabled != enabled) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004927 int stepState = enabled ? STEP_LEVEL_MODE_POWER_SAVE : 0;
4928 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_POWER_SAVE) ^ stepState;
4929 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_POWER_SAVE) | stepState;
Joe Onoratoabded112016-02-08 16:49:39 -08004930 final long elapsedRealtime = mClocks.elapsedRealtime();
4931 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004932 mPowerSaveModeEnabled = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004933 if (enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004934 mHistoryCur.states2 |= HistoryItem.STATE2_POWER_SAVE_FLAG;
4935 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode enabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004936 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004937 mPowerSaveModeEnabledTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004938 } else {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004939 mHistoryCur.states2 &= ~HistoryItem.STATE2_POWER_SAVE_FLAG;
4940 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode disabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004941 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004942 mPowerSaveModeEnabledTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004943 }
4944 addHistoryRecordLocked(elapsedRealtime, uptime);
Bookatz90867622018-01-31 15:05:57 -08004945 StatsLog.write(StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED, enabled ?
4946 StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED__STATE__ON :
4947 StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED__STATE__OFF);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004948 }
4949 }
4950
Bookatzddccf0a2017-11-28 16:48:14 -08004951 public void noteDeviceIdleModeLocked(final int mode, String activeReason, int activeUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004952 final long elapsedRealtime = mClocks.elapsedRealtime();
4953 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07004954 boolean nowIdling = mode == DEVICE_IDLE_MODE_DEEP;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004955 if (mDeviceIdling && !nowIdling && activeReason == null) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004956 // We don't go out of general idling mode until explicitly taken out of
4957 // device idle through going active or significant motion.
4958 nowIdling = true;
4959 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004960 boolean nowLightIdling = mode == DEVICE_IDLE_MODE_LIGHT;
4961 if (mDeviceLightIdling && !nowLightIdling && !nowIdling && activeReason == null) {
4962 // We don't go out of general light idling mode until explicitly taken out of
4963 // device idle through going active or significant motion.
4964 nowLightIdling = true;
4965 }
4966 if (activeReason != null && (mDeviceIdling || mDeviceLightIdling)) {
4967 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_ACTIVE,
4968 activeReason, activeUid);
4969 }
Bookatzddccf0a2017-11-28 16:48:14 -08004970 if (mDeviceIdling != nowIdling || mDeviceLightIdling != nowLightIdling) {
4971 int statsmode;
4972 if (nowIdling) statsmode = DEVICE_IDLE_MODE_DEEP;
4973 else if (nowLightIdling) statsmode = DEVICE_IDLE_MODE_LIGHT;
4974 else statsmode = DEVICE_IDLE_MODE_OFF;
4975 StatsLog.write(StatsLog.DEVICE_IDLING_MODE_STATE_CHANGED, statsmode);
4976 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004977 if (mDeviceIdling != nowIdling) {
4978 mDeviceIdling = nowIdling;
4979 int stepState = nowIdling ? STEP_LEVEL_MODE_DEVICE_IDLE : 0;
4980 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_DEVICE_IDLE) ^ stepState;
4981 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_DEVICE_IDLE) | stepState;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004982 if (nowIdling) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004983 mDeviceIdlingTimer.startRunningLocked(elapsedRealtime);
4984 } else {
4985 mDeviceIdlingTimer.stopRunningLocked(elapsedRealtime);
4986 }
4987 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004988 if (mDeviceLightIdling != nowLightIdling) {
4989 mDeviceLightIdling = nowLightIdling;
4990 if (nowLightIdling) {
4991 mDeviceLightIdlingTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004992 } else {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004993 mDeviceLightIdlingTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004994 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004995 }
4996 if (mDeviceIdleMode != mode) {
4997 mHistoryCur.states2 = (mHistoryCur.states2 & ~HistoryItem.STATE2_DEVICE_IDLE_MASK)
4998 | (mode << HistoryItem.STATE2_DEVICE_IDLE_SHIFT);
4999 if (DEBUG_HISTORY) Slog.v(TAG, "Device idle mode changed to: "
5000 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005001 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005002 long lastDuration = elapsedRealtime - mLastIdleTimeStart;
5003 mLastIdleTimeStart = elapsedRealtime;
5004 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
5005 if (lastDuration > mLongestLightIdleTime) {
5006 mLongestLightIdleTime = lastDuration;
5007 }
5008 mDeviceIdleModeLightTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005009 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005010 if (lastDuration > mLongestFullIdleTime) {
5011 mLongestFullIdleTime = lastDuration;
5012 }
5013 mDeviceIdleModeFullTimer.stopRunningLocked(elapsedRealtime);
5014 }
5015 if (mode == DEVICE_IDLE_MODE_LIGHT) {
5016 mDeviceIdleModeLightTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005017 } else if (mode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005018 mDeviceIdleModeFullTimer.startRunningLocked(elapsedRealtime);
5019 }
5020 mDeviceIdleMode = mode;
Bookatzddccf0a2017-11-28 16:48:14 -08005021 StatsLog.write(StatsLog.DEVICE_IDLE_MODE_STATE_CHANGED, mode);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005022 }
5023 }
5024
Dianne Hackborn3accca02013-09-20 09:32:11 -07005025 public void notePackageInstalledLocked(String pkgName, long versionCode) {
Joe Onoratoabded112016-02-08 16:49:39 -08005026 final long elapsedRealtime = mClocks.elapsedRealtime();
5027 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3accca02013-09-20 09:32:11 -07005028 // XXX need to figure out what to do with long version codes.
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005029 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_INSTALLED,
Dianne Hackborn3accca02013-09-20 09:32:11 -07005030 pkgName, (int)versionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005031 PackageChange pc = new PackageChange();
5032 pc.mPackageName = pkgName;
5033 pc.mUpdate = true;
5034 pc.mVersionCode = versionCode;
5035 addPackageChange(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005036 }
5037
5038 public void notePackageUninstalledLocked(String pkgName) {
Joe Onoratoabded112016-02-08 16:49:39 -08005039 final long elapsedRealtime = mClocks.elapsedRealtime();
5040 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005041 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_UNINSTALLED,
5042 pkgName, 0);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005043 PackageChange pc = new PackageChange();
5044 pc.mPackageName = pkgName;
5045 pc.mUpdate = true;
5046 addPackageChange(pc);
5047 }
5048
5049 private void addPackageChange(PackageChange pc) {
5050 if (mDailyPackageChanges == null) {
5051 mDailyPackageChanges = new ArrayList<>();
5052 }
5053 mDailyPackageChanges.add(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005054 }
5055
Siddharth Ray78ccaf52017-12-23 16:16:21 -08005056 void stopAllGpsSignalQualityTimersLocked(int except) {
5057 final long elapsedRealtime = mClocks.elapsedRealtime();
5058 for (int i = 0; i < GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
5059 if (i == except) {
5060 continue;
5061 }
5062 while (mGpsSignalQualityTimer[i].isRunningLocked()) {
5063 mGpsSignalQualityTimer[i].stopRunningLocked(elapsedRealtime);
5064 }
5065 }
5066 }
5067
Mathew Inwoodaf972c82018-08-20 14:13:20 +01005068 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005069 public void notePhoneOnLocked() {
5070 if (!mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005071 final long elapsedRealtime = mClocks.elapsedRealtime();
5072 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005073 mHistoryCur.states2 |= HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005074 if (DEBUG_HISTORY) Slog.v(TAG, "Phone on to: "
5075 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005076 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005077 mPhoneOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005078 mPhoneOnTimer.startRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005079 }
5080 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005081
Mathew Inwoodaf972c82018-08-20 14:13:20 +01005082 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005083 public void notePhoneOffLocked() {
5084 if (mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005085 final long elapsedRealtime = mClocks.elapsedRealtime();
5086 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005087 mHistoryCur.states2 &= ~HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005088 if (DEBUG_HISTORY) Slog.v(TAG, "Phone off to: "
5089 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005090 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005091 mPhoneOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005092 mPhoneOnTimer.stopRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005093 }
5094 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07005095
Mike Mafbc01fc2018-04-02 10:28:28 -07005096 private void registerUsbStateReceiver(Context context) {
5097 final IntentFilter usbStateFilter = new IntentFilter();
5098 usbStateFilter.addAction(UsbManager.ACTION_USB_STATE);
5099 context.registerReceiver(new BroadcastReceiver() {
5100 @Override
5101 public void onReceive(Context context, Intent intent) {
5102 final boolean state = intent.getBooleanExtra(UsbManager.USB_CONNECTED, false);
5103 synchronized (BatteryStatsImpl.this) {
5104 noteUsbConnectionStateLocked(state);
5105 }
5106 }
5107 }, usbStateFilter);
5108 synchronized (this) {
5109 if (mUsbDataState == USB_DATA_UNKNOWN) {
5110 final Intent usbState = context.registerReceiver(null, usbStateFilter);
5111 final boolean initState = usbState != null && usbState.getBooleanExtra(
5112 UsbManager.USB_CONNECTED, false);
5113 noteUsbConnectionStateLocked(initState);
5114 }
5115 }
5116 }
5117
5118 private void noteUsbConnectionStateLocked(boolean connected) {
5119 int newState = connected ? USB_DATA_CONNECTED : USB_DATA_DISCONNECTED;
Mike Ma926a97c2018-03-25 02:32:35 -07005120 if (mUsbDataState != newState) {
5121 mUsbDataState = newState;
5122 if (connected) {
5123 mHistoryCur.states2 |= HistoryItem.STATE2_USB_DATA_LINK_FLAG;
5124 } else {
5125 mHistoryCur.states2 &= ~HistoryItem.STATE2_USB_DATA_LINK_FLAG;
5126 }
5127 addHistoryRecordLocked(mClocks.elapsedRealtime(), mClocks.uptimeMillis());
5128 }
5129 }
5130
Dianne Hackborn3251b902014-06-20 14:40:53 -07005131 void stopAllPhoneSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005132 final long elapsedRealtime = mClocks.elapsedRealtime();
Wink Saville52840902011-02-18 12:40:47 -08005133 for (int i = 0; i < SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005134 if (i == except) {
5135 continue;
5136 }
5137 while (mPhoneSignalStrengthsTimer[i].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005138 mPhoneSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005139 }
5140 }
5141 }
5142
Dianne Hackborne4a59512010-12-07 11:08:07 -08005143 private int fixPhoneServiceState(int state, int signalBin) {
5144 if (mPhoneSimStateRaw == TelephonyManager.SIM_STATE_ABSENT) {
5145 // In this case we will always be STATE_OUT_OF_SERVICE, so need
5146 // to infer that we are scanning from other data.
5147 if (state == ServiceState.STATE_OUT_OF_SERVICE
Wink Saville52840902011-02-18 12:40:47 -08005148 && signalBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005149 state = ServiceState.STATE_IN_SERVICE;
5150 }
5151 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005152
Dianne Hackborne4a59512010-12-07 11:08:07 -08005153 return state;
5154 }
5155
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005156 private void updateAllPhoneStateLocked(int state, int simState, int strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005157 boolean scanning = false;
5158 boolean newHistory = false;
5159
5160 mPhoneServiceStateRaw = state;
5161 mPhoneSimStateRaw = simState;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005162 mPhoneSignalStrengthBinRaw = strengthBin;
5163
Joe Onoratoabded112016-02-08 16:49:39 -08005164 final long elapsedRealtime = mClocks.elapsedRealtime();
5165 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne4a59512010-12-07 11:08:07 -08005166
5167 if (simState == TelephonyManager.SIM_STATE_ABSENT) {
5168 // In this case we will always be STATE_OUT_OF_SERVICE, so need
5169 // to infer that we are scanning from other data.
5170 if (state == ServiceState.STATE_OUT_OF_SERVICE
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005171 && strengthBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005172 state = ServiceState.STATE_IN_SERVICE;
5173 }
5174 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005175
5176 // If the phone is powered off, stop all timers.
5177 if (state == ServiceState.STATE_POWER_OFF) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005178 strengthBin = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -07005179
Dianne Hackborne4a59512010-12-07 11:08:07 -08005180 // If we are in service, make sure the correct signal string timer is running.
5181 } else if (state == ServiceState.STATE_IN_SERVICE) {
5182 // Bin will be changed below.
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005183
5184 // If we're out of service, we are in the lowest signal strength
5185 // bin and have the scanning bit set.
Amith Yamasanif37447b2009-10-08 18:28:01 -07005186 } else if (state == ServiceState.STATE_OUT_OF_SERVICE) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005187 scanning = true;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005188 strengthBin = SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN;
Amith Yamasanif37447b2009-10-08 18:28:01 -07005189 if (!mPhoneSignalScanningTimer.isRunningLocked()) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005190 mHistoryCur.states |= HistoryItem.STATE_PHONE_SCANNING_FLAG;
Dianne Hackborne4a59512010-12-07 11:08:07 -08005191 newHistory = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005192 if (DEBUG_HISTORY) Slog.v(TAG, "Phone started scanning to: "
5193 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005194 mPhoneSignalScanningTimer.startRunningLocked(elapsedRealtime);
Yangster4ccebea2018-10-09 17:09:02 -07005195 StatsLog.write(StatsLog.PHONE_SERVICE_STATE_CHANGED, state, simState, strengthBin);
Amith Yamasanif37447b2009-10-08 18:28:01 -07005196 }
5197 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005198
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005199 if (!scanning) {
5200 // If we are no longer scanning, then stop the scanning timer.
5201 if (mPhoneSignalScanningTimer.isRunningLocked()) {
5202 mHistoryCur.states &= ~HistoryItem.STATE_PHONE_SCANNING_FLAG;
5203 if (DEBUG_HISTORY) Slog.v(TAG, "Phone stopped scanning to: "
5204 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08005205 newHistory = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005206 mPhoneSignalScanningTimer.stopRunningLocked(elapsedRealtime);
Yangster4ccebea2018-10-09 17:09:02 -07005207 StatsLog.write(StatsLog.PHONE_SERVICE_STATE_CHANGED, state, simState, strengthBin);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005208 }
5209 }
5210
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005211 if (mPhoneServiceState != state) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005212 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_STATE_MASK)
5213 | (state << HistoryItem.STATE_PHONE_STATE_SHIFT);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005214 if (DEBUG_HISTORY) Slog.v(TAG, "Phone state " + state + " to: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005215 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08005216 newHistory = true;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005217 mPhoneServiceState = state;
5218 }
Dianne Hackborne4a59512010-12-07 11:08:07 -08005219
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005220 if (mPhoneSignalStrengthBin != strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005221 if (mPhoneSignalStrengthBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005222 mPhoneSignalStrengthsTimer[mPhoneSignalStrengthBin].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005223 elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005224 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005225 if (strengthBin >= 0) {
5226 if (!mPhoneSignalStrengthsTimer[strengthBin].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005227 mPhoneSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005228 }
Dianne Hackborn3251b902014-06-20 14:40:53 -07005229 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_MASK)
5230 | (strengthBin << HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_SHIFT);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005231 if (DEBUG_HISTORY) Slog.v(TAG, "Signal strength " + strengthBin + " to: "
Dianne Hackborne4a59512010-12-07 11:08:07 -08005232 + Integer.toHexString(mHistoryCur.states));
5233 newHistory = true;
Bookatze5885242017-10-24 20:10:31 -07005234 StatsLog.write(StatsLog.PHONE_SIGNAL_STRENGTH_CHANGED, strengthBin);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005235 } else {
Dianne Hackborn3251b902014-06-20 14:40:53 -07005236 stopAllPhoneSignalStrengthTimersLocked(-1);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005237 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005238 mPhoneSignalStrengthBin = strengthBin;
Dianne Hackborne4a59512010-12-07 11:08:07 -08005239 }
5240
5241 if (newHistory) {
Dianne Hackborn40c87252014-03-19 16:55:40 -07005242 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005243 }
5244 }
5245
5246 /**
5247 * Telephony stack updates the phone state.
5248 * @param state phone state from ServiceState.getState()
5249 */
5250 public void notePhoneStateLocked(int state, int simState) {
5251 updateAllPhoneStateLocked(state, simState, mPhoneSignalStrengthBinRaw);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07005252 }
5253
Mathew Inwoodaf972c82018-08-20 14:13:20 +01005254 @UnsupportedAppUsage
Wink Savillee9b06d72009-05-18 21:47:50 -07005255 public void notePhoneSignalStrengthLocked(SignalStrength signalStrength) {
Dianne Hackborn627bba72009-03-24 22:32:56 -07005256 // Bin the strength.
Wink Saville52840902011-02-18 12:40:47 -08005257 int bin = signalStrength.getLevel();
Dianne Hackborne4a59512010-12-07 11:08:07 -08005258 updateAllPhoneStateLocked(mPhoneServiceStateRaw, mPhoneSimStateRaw, bin);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005259 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005260
Mathew Inwoodaf972c82018-08-20 14:13:20 +01005261 @UnsupportedAppUsage
Blake Kragten6bf8ef52019-03-20 17:14:58 -07005262 public void notePhoneDataConnectionStateLocked(int dataType, boolean hasData, int serviceType) {
Tej Singheee317b2018-03-07 19:28:05 -08005263 // BatteryStats uses 0 to represent no network type.
5264 // Telephony does not have a concept of no network type, and uses 0 to represent unknown.
5265 // Unknown is included in DATA_CONNECTION_OTHER.
Blake Kragten6bf8ef52019-03-20 17:14:58 -07005266 int bin = DATA_CONNECTION_OUT_OF_SERVICE;
Dianne Hackborn627bba72009-03-24 22:32:56 -07005267 if (hasData) {
Tej Singheee317b2018-03-07 19:28:05 -08005268 if (dataType > 0 && dataType <= TelephonyManager.MAX_NETWORK_TYPE) {
5269 bin = dataType;
5270 } else {
Blake Kragten6bf8ef52019-03-20 17:14:58 -07005271 switch (serviceType) {
5272 case ServiceState.STATE_OUT_OF_SERVICE:
5273 bin = DATA_CONNECTION_OUT_OF_SERVICE;
5274 break;
5275 case ServiceState.STATE_EMERGENCY_ONLY:
5276 bin = DATA_CONNECTION_EMERGENCY_SERVICE;
5277 break;
5278 default:
5279 bin = DATA_CONNECTION_OTHER;
5280 break;
5281 }
Dianne Hackborn627bba72009-03-24 22:32:56 -07005282 }
5283 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07005284 if (DEBUG) Log.i(TAG, "Phone Data Connection -> " + dataType + " = " + hasData);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005285 if (mPhoneDataConnectionType != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005286 final long elapsedRealtime = mClocks.elapsedRealtime();
5287 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005288 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_DATA_CONNECTION_MASK)
5289 | (bin << HistoryItem.STATE_DATA_CONNECTION_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005290 if (DEBUG_HISTORY) Slog.v(TAG, "Data connection " + bin + " to: "
5291 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005292 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005293 if (mPhoneDataConnectionType >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005294 mPhoneDataConnectionsTimer[mPhoneDataConnectionType].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005295 elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005296 }
5297 mPhoneDataConnectionType = bin;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005298 mPhoneDataConnectionsTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005299 }
5300 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005301
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005302 public void noteWifiOnLocked() {
The Android Open Source Project10592532009-03-18 17:39:46 -07005303 if (!mWifiOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005304 final long elapsedRealtime = mClocks.elapsedRealtime();
5305 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005306 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005307 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI on to: "
5308 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005309 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005310 mWifiOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005311 mWifiOnTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005312 scheduleSyncExternalStatsLocked("wifi-off", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07005313 }
5314 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005315
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005316 public void noteWifiOffLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08005317 final long elapsedRealtime = mClocks.elapsedRealtime();
5318 final long uptime = mClocks.uptimeMillis();
The Android Open Source Project10592532009-03-18 17:39:46 -07005319 if (mWifiOn) {
Dianne Hackborn3251b902014-06-20 14:40:53 -07005320 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005321 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI off to: "
5322 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005323 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005324 mWifiOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005325 mWifiOnTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005326 scheduleSyncExternalStatsLocked("wifi-on", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07005327 }
5328 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005329
Mathew Inwoodaf972c82018-08-20 14:13:20 +01005330 @UnsupportedAppUsage
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005331 public void noteAudioOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005332 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005333 final long elapsedRealtime = mClocks.elapsedRealtime();
5334 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005335 if (mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005336 mHistoryCur.states |= HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005337 if (DEBUG_HISTORY) Slog.v(TAG, "Audio on to: "
5338 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005339 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005340 mAudioOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005341 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005342 mAudioOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005343 getUidStatsLocked(uid).noteAudioTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005344 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005345
Mathew Inwoodaf972c82018-08-20 14:13:20 +01005346 @UnsupportedAppUsage
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005347 public void noteAudioOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005348 if (mAudioOnNesting == 0) {
5349 return;
5350 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08005351 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005352 final long elapsedRealtime = mClocks.elapsedRealtime();
5353 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005354 if (--mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005355 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005356 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
5357 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005358 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005359 mAudioOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005360 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005361 getUidStatsLocked(uid).noteAudioTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005362 }
5363
Mathew Inwoodaf972c82018-08-20 14:13:20 +01005364 @UnsupportedAppUsage
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005365 public void noteVideoOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005366 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005367 final long elapsedRealtime = mClocks.elapsedRealtime();
5368 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005369 if (mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005370 mHistoryCur.states2 |= HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005371 if (DEBUG_HISTORY) Slog.v(TAG, "Video on to: "
5372 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005373 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005374 mVideoOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005375 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005376 mVideoOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005377 getUidStatsLocked(uid).noteVideoTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005378 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005379
Mathew Inwoodaf972c82018-08-20 14:13:20 +01005380 @UnsupportedAppUsage
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005381 public void noteVideoOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005382 if (mVideoOnNesting == 0) {
5383 return;
5384 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08005385 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005386 final long elapsedRealtime = mClocks.elapsedRealtime();
5387 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005388 if (--mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005389 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005390 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
5391 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005392 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005393 mVideoOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005394 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005395 getUidStatsLocked(uid).noteVideoTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005396 }
5397
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005398 public void noteResetAudioLocked() {
5399 if (mAudioOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005400 final long elapsedRealtime = mClocks.elapsedRealtime();
5401 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005402 mAudioOnNesting = 0;
5403 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
5404 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
5405 + Integer.toHexString(mHistoryCur.states));
5406 addHistoryRecordLocked(elapsedRealtime, uptime);
5407 mAudioOnTimer.stopAllRunningLocked(elapsedRealtime);
5408 for (int i=0; i<mUidStats.size(); i++) {
5409 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5410 uid.noteResetAudioLocked(elapsedRealtime);
5411 }
5412 }
5413 }
5414
5415 public void noteResetVideoLocked() {
5416 if (mVideoOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005417 final long elapsedRealtime = mClocks.elapsedRealtime();
5418 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005419 mAudioOnNesting = 0;
5420 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
5421 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
5422 + Integer.toHexString(mHistoryCur.states));
5423 addHistoryRecordLocked(elapsedRealtime, uptime);
5424 mVideoOnTimer.stopAllRunningLocked(elapsedRealtime);
5425 for (int i=0; i<mUidStats.size(); i++) {
5426 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5427 uid.noteResetVideoLocked(elapsedRealtime);
5428 }
5429 }
5430 }
5431
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005432 public void noteActivityResumedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005433 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005434 getUidStatsLocked(uid).noteActivityResumedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005435 }
5436
5437 public void noteActivityPausedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005438 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005439 getUidStatsLocked(uid).noteActivityPausedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005440 }
5441
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005442 public void noteVibratorOnLocked(int uid, long durationMillis) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005443 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005444 getUidStatsLocked(uid).noteVibratorOnLocked(durationMillis);
5445 }
5446
5447 public void noteVibratorOffLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005448 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005449 getUidStatsLocked(uid).noteVibratorOffLocked();
5450 }
5451
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005452 public void noteFlashlightOnLocked(int uid) {
5453 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005454 final long elapsedRealtime = mClocks.elapsedRealtime();
5455 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005456 if (mFlashlightOnNesting++ == 0) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005457 mHistoryCur.states2 |= HistoryItem.STATE2_FLASHLIGHT_FLAG;
5458 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight on to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005459 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005460 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005461 mFlashlightOnTimer.startRunningLocked(elapsedRealtime);
5462 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005463 getUidStatsLocked(uid).noteFlashlightTurnedOnLocked(elapsedRealtime);
5464 }
5465
5466 public void noteFlashlightOffLocked(int uid) {
5467 if (mFlashlightOnNesting == 0) {
5468 return;
5469 }
5470 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005471 final long elapsedRealtime = mClocks.elapsedRealtime();
5472 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005473 if (--mFlashlightOnNesting == 0) {
5474 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
5475 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
5476 + Integer.toHexString(mHistoryCur.states2));
5477 addHistoryRecordLocked(elapsedRealtime, uptime);
5478 mFlashlightOnTimer.stopRunningLocked(elapsedRealtime);
5479 }
5480 getUidStatsLocked(uid).noteFlashlightTurnedOffLocked(elapsedRealtime);
5481 }
5482
5483 public void noteCameraOnLocked(int uid) {
5484 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005485 final long elapsedRealtime = mClocks.elapsedRealtime();
5486 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005487 if (mCameraOnNesting++ == 0) {
5488 mHistoryCur.states2 |= HistoryItem.STATE2_CAMERA_FLAG;
5489 if (DEBUG_HISTORY) Slog.v(TAG, "Camera on to: "
5490 + Integer.toHexString(mHistoryCur.states2));
5491 addHistoryRecordLocked(elapsedRealtime, uptime);
5492 mCameraOnTimer.startRunningLocked(elapsedRealtime);
5493 }
5494 getUidStatsLocked(uid).noteCameraTurnedOnLocked(elapsedRealtime);
5495 }
5496
5497 public void noteCameraOffLocked(int uid) {
5498 if (mCameraOnNesting == 0) {
5499 return;
5500 }
5501 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005502 final long elapsedRealtime = mClocks.elapsedRealtime();
5503 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005504 if (--mCameraOnNesting == 0) {
5505 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
5506 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
5507 + Integer.toHexString(mHistoryCur.states2));
5508 addHistoryRecordLocked(elapsedRealtime, uptime);
5509 mCameraOnTimer.stopRunningLocked(elapsedRealtime);
5510 }
5511 getUidStatsLocked(uid).noteCameraTurnedOffLocked(elapsedRealtime);
5512 }
5513
5514 public void noteResetCameraLocked() {
5515 if (mCameraOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005516 final long elapsedRealtime = mClocks.elapsedRealtime();
5517 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005518 mCameraOnNesting = 0;
5519 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
5520 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
5521 + Integer.toHexString(mHistoryCur.states2));
5522 addHistoryRecordLocked(elapsedRealtime, uptime);
5523 mCameraOnTimer.stopAllRunningLocked(elapsedRealtime);
5524 for (int i=0; i<mUidStats.size(); i++) {
5525 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5526 uid.noteResetCameraLocked(elapsedRealtime);
5527 }
5528 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005529 }
5530
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005531 public void noteResetFlashlightLocked() {
5532 if (mFlashlightOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005533 final long elapsedRealtime = mClocks.elapsedRealtime();
5534 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005535 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005536 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
5537 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005538 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005539 addHistoryRecordLocked(elapsedRealtime, uptime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005540 mFlashlightOnTimer.stopAllRunningLocked(elapsedRealtime);
5541 for (int i=0; i<mUidStats.size(); i++) {
5542 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5543 uid.noteResetFlashlightLocked(elapsedRealtime);
5544 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005545 }
5546 }
5547
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005548 private void noteBluetoothScanStartedLocked(WorkChain workChain, int uid,
5549 boolean isUnoptimized) {
5550 uid = getAttributionUid(uid, workChain);
Bookatz867c0d72017-03-07 18:23:42 -08005551 final long elapsedRealtime = mClocks.elapsedRealtime();
5552 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005553 if (mBluetoothScanNesting == 0) {
5554 mHistoryCur.states2 |= HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5555 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan started for: "
5556 + Integer.toHexString(mHistoryCur.states2));
5557 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005558 mBluetoothScanTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005559 }
5560 mBluetoothScanNesting++;
Bookatzb1f04f32017-05-19 13:57:32 -07005561 getUidStatsLocked(uid).noteBluetoothScanStartedLocked(elapsedRealtime, isUnoptimized);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005562 }
5563
Bookatzb1f04f32017-05-19 13:57:32 -07005564 public void noteBluetoothScanStartedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005565 final int N = ws.size();
5566 for (int i = 0; i < N; i++) {
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -08005567 noteBluetoothScanStartedLocked(null, ws.getUid(i), isUnoptimized);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005568 }
5569
5570 final List<WorkChain> workChains = ws.getWorkChains();
5571 if (workChains != null) {
5572 for (int i = 0; i < workChains.size(); ++i) {
5573 noteBluetoothScanStartedLocked(workChains.get(i), -1, isUnoptimized);
5574 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005575 }
5576 }
5577
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005578 private void noteBluetoothScanStoppedLocked(WorkChain workChain, int uid,
5579 boolean isUnoptimized) {
5580 uid = getAttributionUid(uid, workChain);
Bookatz867c0d72017-03-07 18:23:42 -08005581 final long elapsedRealtime = mClocks.elapsedRealtime();
5582 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005583 mBluetoothScanNesting--;
5584 if (mBluetoothScanNesting == 0) {
5585 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5586 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan stopped for: "
5587 + Integer.toHexString(mHistoryCur.states2));
5588 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005589 mBluetoothScanTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005590 }
Bookatz94c5a312017-07-11 16:49:17 -07005591 getUidStatsLocked(uid).noteBluetoothScanStoppedLocked(elapsedRealtime, isUnoptimized);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005592 }
5593
5594 private int getAttributionUid(int uid, WorkChain workChain) {
5595 if (workChain != null) {
5596 return mapUid(workChain.getAttributionUid());
5597 }
5598
5599 return mapUid(uid);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005600 }
5601
Bookatz94c5a312017-07-11 16:49:17 -07005602 public void noteBluetoothScanStoppedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005603 final int N = ws.size();
5604 for (int i = 0; i < N; i++) {
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -08005605 noteBluetoothScanStoppedLocked(null, ws.getUid(i), isUnoptimized);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005606 }
5607
5608 final List<WorkChain> workChains = ws.getWorkChains();
5609 if (workChains != null) {
5610 for (int i = 0; i < workChains.size(); ++i) {
5611 noteBluetoothScanStoppedLocked(workChains.get(i), -1, isUnoptimized);
5612 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005613 }
5614 }
5615
5616 public void noteResetBluetoothScanLocked() {
5617 if (mBluetoothScanNesting > 0) {
Bookatz867c0d72017-03-07 18:23:42 -08005618 final long elapsedRealtime = mClocks.elapsedRealtime();
5619 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005620 mBluetoothScanNesting = 0;
5621 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5622 if (DEBUG_HISTORY) Slog.v(TAG, "BLE can stopped for: "
5623 + Integer.toHexString(mHistoryCur.states2));
5624 addHistoryRecordLocked(elapsedRealtime, uptime);
5625 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtime);
5626 for (int i=0; i<mUidStats.size(); i++) {
5627 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5628 uid.noteResetBluetoothScanLocked(elapsedRealtime);
5629 }
5630 }
5631 }
5632
Bookatz4ebc0642017-05-11 12:21:19 -07005633 public void noteBluetoothScanResultsFromSourceLocked(WorkSource ws, int numNewResults) {
Bookatz956f36bf2017-04-28 09:48:17 -07005634 final int N = ws.size();
5635 for (int i = 0; i < N; i++) {
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -08005636 int uid = mapUid(ws.getUid(i));
Bookatz4ebc0642017-05-11 12:21:19 -07005637 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005638 }
5639
5640 final List<WorkChain> workChains = ws.getWorkChains();
5641 if (workChains != null) {
5642 for (int i = 0; i < workChains.size(); ++i) {
5643 final WorkChain wc = workChains.get(i);
5644 int uid = mapUid(wc.getAttributionUid());
5645 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005646 }
Bookatz956f36bf2017-04-28 09:48:17 -07005647 }
5648 }
5649
Adam Lesinski5f056f62016-07-14 16:56:08 -07005650 private void noteWifiRadioApWakeupLocked(final long elapsedRealtimeMillis,
5651 final long uptimeMillis, int uid) {
5652 uid = mapUid(uid);
5653 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
5654 uid);
5655 getUidStatsLocked(uid).noteWifiRadioApWakeupLocked();
5656 }
5657
5658 public void noteWifiRadioPowerState(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005659 final long elapsedRealtime = mClocks.elapsedRealtime();
5660 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005661 if (mWifiRadioPowerState != powerState) {
5662 final boolean active =
5663 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
5664 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
5665 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07005666 if (uid > 0) {
5667 noteWifiRadioApWakeupLocked(elapsedRealtime, uptime, uid);
5668 }
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005669 mHistoryCur.states |= HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
Siddharth Rayb50a6842017-12-14 15:15:28 -08005670 mWifiActiveTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005671 } else {
5672 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
Siddharth Rayb50a6842017-12-14 15:15:28 -08005673 mWifiActiveTimer.stopRunningLocked(
5674 timestampNs / (1000 * 1000));
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005675 }
5676 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi network active " + active + " to: "
5677 + Integer.toHexString(mHistoryCur.states));
5678 addHistoryRecordLocked(elapsedRealtime, uptime);
5679 mWifiRadioPowerState = powerState;
5680 }
5681 }
5682
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005683 public void noteWifiRunningLocked(WorkSource ws) {
5684 if (!mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005685 final long elapsedRealtime = mClocks.elapsedRealtime();
5686 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005687 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005688 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI running to: "
5689 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005690 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005691 mGlobalWifiRunning = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005692 mGlobalWifiRunningTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005693 int N = ws.size();
5694 for (int i=0; i<N; i++) {
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -08005695 int uid = mapUid(ws.getUid(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005696 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005697 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005698
5699 List<WorkChain> workChains = ws.getWorkChains();
5700 if (workChains != null) {
5701 for (int i = 0; i < workChains.size(); ++i) {
5702 int uid = mapUid(workChains.get(i).getAttributionUid());
5703 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
5704 }
5705 }
5706
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005707 scheduleSyncExternalStatsLocked("wifi-running", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005708 } else {
5709 Log.w(TAG, "noteWifiRunningLocked -- called while WIFI running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005710 }
5711 }
5712
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005713 public void noteWifiRunningChangedLocked(WorkSource oldWs, WorkSource newWs) {
5714 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005715 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005716 int N = oldWs.size();
5717 for (int i=0; i<N; i++) {
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -08005718 int uid = mapUid(oldWs.getUid(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005719 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005720 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005721
5722 List<WorkChain> workChains = oldWs.getWorkChains();
5723 if (workChains != null) {
5724 for (int i = 0; i < workChains.size(); ++i) {
5725 int uid = mapUid(workChains.get(i).getAttributionUid());
5726 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
5727 }
5728 }
5729
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005730 N = newWs.size();
5731 for (int i=0; i<N; i++) {
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -08005732 int uid = mapUid(newWs.getUid(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005733 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005734 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005735
5736 workChains = newWs.getWorkChains();
5737 if (workChains != null) {
5738 for (int i = 0; i < workChains.size(); ++i) {
5739 int uid = mapUid(workChains.get(i).getAttributionUid());
5740 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
5741 }
5742 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005743 } else {
5744 Log.w(TAG, "noteWifiRunningChangedLocked -- called while WIFI not running");
5745 }
5746 }
5747
5748 public void noteWifiStoppedLocked(WorkSource ws) {
5749 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005750 final long elapsedRealtime = mClocks.elapsedRealtime();
5751 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005752 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005753 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI stopped to: "
5754 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005755 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005756 mGlobalWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005757 mGlobalWifiRunningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005758 int N = ws.size();
5759 for (int i=0; i<N; i++) {
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -08005760 int uid = mapUid(ws.getUid(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005761 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005762 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005763
5764 List<WorkChain> workChains = ws.getWorkChains();
5765 if (workChains != null) {
5766 for (int i = 0; i < workChains.size(); ++i) {
5767 int uid = mapUid(workChains.get(i).getAttributionUid());
5768 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
5769 }
5770 }
5771
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005772 scheduleSyncExternalStatsLocked("wifi-stopped", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005773 } else {
5774 Log.w(TAG, "noteWifiStoppedLocked -- called while WIFI not running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005775 }
5776 }
5777
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005778 public void noteWifiStateLocked(int wifiState, String accessPoint) {
5779 if (DEBUG) Log.i(TAG, "WiFi state -> " + wifiState);
5780 if (mWifiState != wifiState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005781 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005782 if (mWifiState >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005783 mWifiStateTimer[mWifiState].stopRunningLocked(elapsedRealtime);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005784 }
5785 mWifiState = wifiState;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005786 mWifiStateTimer[wifiState].startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005787 scheduleSyncExternalStatsLocked("wifi-state", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005788 }
5789 }
5790
Dianne Hackborn3251b902014-06-20 14:40:53 -07005791 public void noteWifiSupplicantStateChangedLocked(int supplState, boolean failedAuth) {
5792 if (DEBUG) Log.i(TAG, "WiFi suppl state -> " + supplState);
5793 if (mWifiSupplState != supplState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005794 final long elapsedRealtime = mClocks.elapsedRealtime();
5795 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005796 if (mWifiSupplState >= 0) {
5797 mWifiSupplStateTimer[mWifiSupplState].stopRunningLocked(elapsedRealtime);
5798 }
5799 mWifiSupplState = supplState;
5800 mWifiSupplStateTimer[supplState].startRunningLocked(elapsedRealtime);
5801 mHistoryCur.states2 =
5802 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SUPPL_STATE_MASK)
5803 | (supplState << HistoryItem.STATE2_WIFI_SUPPL_STATE_SHIFT);
5804 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi suppl state " + supplState + " to: "
5805 + Integer.toHexString(mHistoryCur.states2));
5806 addHistoryRecordLocked(elapsedRealtime, uptime);
5807 }
5808 }
5809
5810 void stopAllWifiSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005811 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005812 for (int i = 0; i < NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
5813 if (i == except) {
5814 continue;
5815 }
5816 while (mWifiSignalStrengthsTimer[i].isRunningLocked()) {
5817 mWifiSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
5818 }
5819 }
5820 }
5821
5822 public void noteWifiRssiChangedLocked(int newRssi) {
5823 int strengthBin = WifiManager.calculateSignalLevel(newRssi, NUM_WIFI_SIGNAL_STRENGTH_BINS);
5824 if (DEBUG) Log.i(TAG, "WiFi rssi -> " + newRssi + " bin=" + strengthBin);
5825 if (mWifiSignalStrengthBin != strengthBin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005826 final long elapsedRealtime = mClocks.elapsedRealtime();
5827 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005828 if (mWifiSignalStrengthBin >= 0) {
5829 mWifiSignalStrengthsTimer[mWifiSignalStrengthBin].stopRunningLocked(
5830 elapsedRealtime);
5831 }
5832 if (strengthBin >= 0) {
5833 if (!mWifiSignalStrengthsTimer[strengthBin].isRunningLocked()) {
5834 mWifiSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
5835 }
5836 mHistoryCur.states2 =
5837 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_MASK)
5838 | (strengthBin << HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_SHIFT);
5839 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi signal strength " + strengthBin + " to: "
5840 + Integer.toHexString(mHistoryCur.states2));
5841 addHistoryRecordLocked(elapsedRealtime, uptime);
5842 } else {
5843 stopAllWifiSignalStrengthTimersLocked(-1);
5844 }
5845 mWifiSignalStrengthBin = strengthBin;
5846 }
5847 }
5848
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005849 int mWifiFullLockNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005850
Mathew Inwoodaf972c82018-08-20 14:13:20 +01005851 @UnsupportedAppUsage
The Android Open Source Project10592532009-03-18 17:39:46 -07005852 public void noteFullWifiLockAcquiredLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005853 final long elapsedRealtime = mClocks.elapsedRealtime();
5854 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005855 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005856 mHistoryCur.states |= HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005857 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock on to: "
5858 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005859 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005860 }
5861 mWifiFullLockNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005862 getUidStatsLocked(uid).noteFullWifiLockAcquiredLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005863 }
5864
Mathew Inwoodaf972c82018-08-20 14:13:20 +01005865 @UnsupportedAppUsage
The Android Open Source Project10592532009-03-18 17:39:46 -07005866 public void noteFullWifiLockReleasedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005867 final long elapsedRealtime = mClocks.elapsedRealtime();
5868 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005869 mWifiFullLockNesting--;
5870 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005871 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005872 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock off to: "
5873 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005874 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005875 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005876 getUidStatsLocked(uid).noteFullWifiLockReleasedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005877 }
5878
Nick Pelly6ccaa542012-06-15 15:22:47 -07005879 int mWifiScanNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005880
Nick Pelly6ccaa542012-06-15 15:22:47 -07005881 public void noteWifiScanStartedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005882 final long elapsedRealtime = mClocks.elapsedRealtime();
5883 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07005884 if (mWifiScanNesting == 0) {
5885 mHistoryCur.states |= HistoryItem.STATE_WIFI_SCAN_FLAG;
5886 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan started for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005887 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005888 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005889 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07005890 mWifiScanNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005891 getUidStatsLocked(uid).noteWifiScanStartedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005892 }
5893
Nick Pelly6ccaa542012-06-15 15:22:47 -07005894 public void noteWifiScanStoppedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005895 final long elapsedRealtime = mClocks.elapsedRealtime();
5896 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07005897 mWifiScanNesting--;
5898 if (mWifiScanNesting == 0) {
5899 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_SCAN_FLAG;
5900 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan stopped for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005901 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005902 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005903 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005904 getUidStatsLocked(uid).noteWifiScanStoppedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005905 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005906
Robert Greenwalta029ea12013-09-25 16:38:12 -07005907 public void noteWifiBatchedScanStartedLocked(int uid, int csph) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005908 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005909 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005910 getUidStatsLocked(uid).noteWifiBatchedScanStartedLocked(csph, elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07005911 }
5912
5913 public void noteWifiBatchedScanStoppedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005914 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005915 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005916 getUidStatsLocked(uid).noteWifiBatchedScanStoppedLocked(elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07005917 }
5918
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005919 int mWifiMulticastNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005920
Mathew Inwoodaf972c82018-08-20 14:13:20 +01005921 @UnsupportedAppUsage
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005922 public void noteWifiMulticastEnabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005923 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005924 final long elapsedRealtime = mClocks.elapsedRealtime();
5925 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005926 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005927 mHistoryCur.states |= HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005928 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast on to: "
5929 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005930 addHistoryRecordLocked(elapsedRealtime, uptime);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08005931
5932 // Start Wifi Multicast overall timer
5933 if (!mWifiMulticastWakelockTimer.isRunningLocked()) {
5934 if (DEBUG_HISTORY) Slog.v(TAG, "WiFi Multicast Overall Timer Started");
5935 mWifiMulticastWakelockTimer.startRunningLocked(elapsedRealtime);
5936 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005937 }
5938 mWifiMulticastNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005939 getUidStatsLocked(uid).noteWifiMulticastEnabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005940 }
5941
Mathew Inwoodaf972c82018-08-20 14:13:20 +01005942 @UnsupportedAppUsage
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005943 public void noteWifiMulticastDisabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005944 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005945 final long elapsedRealtime = mClocks.elapsedRealtime();
5946 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005947 mWifiMulticastNesting--;
5948 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005949 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005950 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast off to: "
5951 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005952 addHistoryRecordLocked(elapsedRealtime, uptime);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08005953
5954 // Stop Wifi Multicast overall timer
5955 if (mWifiMulticastWakelockTimer.isRunningLocked()) {
5956 if (DEBUG_HISTORY) Slog.v(TAG, "Multicast Overall Timer Stopped");
5957 mWifiMulticastWakelockTimer.stopRunningLocked(elapsedRealtime);
5958 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005959 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005960 getUidStatsLocked(uid).noteWifiMulticastDisabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005961 }
5962
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005963 public void noteFullWifiLockAcquiredFromSourceLocked(WorkSource ws) {
5964 int N = ws.size();
5965 for (int i=0; i<N; i++) {
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -08005966 final int uid = mapUid(ws.getUid(i));
Narayan Kamath728c8a02017-12-28 15:48:07 +00005967 noteFullWifiLockAcquiredLocked(uid);
Narayan Kamath728c8a02017-12-28 15:48:07 +00005968 }
5969
5970 final List<WorkChain> workChains = ws.getWorkChains();
5971 if (workChains != null) {
5972 for (int i = 0; i < workChains.size(); ++i) {
5973 final WorkChain workChain = workChains.get(i);
5974 final int uid = mapUid(workChain.getAttributionUid());
5975 noteFullWifiLockAcquiredLocked(uid);
Narayan Kamath728c8a02017-12-28 15:48:07 +00005976 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005977 }
5978 }
5979
5980 public void noteFullWifiLockReleasedFromSourceLocked(WorkSource ws) {
5981 int N = ws.size();
5982 for (int i=0; i<N; i++) {
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -08005983 final int uid = mapUid(ws.getUid(i));
Narayan Kamath728c8a02017-12-28 15:48:07 +00005984 noteFullWifiLockReleasedLocked(uid);
Narayan Kamath728c8a02017-12-28 15:48:07 +00005985 }
5986
5987 final List<WorkChain> workChains = ws.getWorkChains();
5988 if (workChains != null) {
5989 for (int i = 0; i < workChains.size(); ++i) {
5990 final WorkChain workChain = workChains.get(i);
5991 final int uid = mapUid(workChain.getAttributionUid());
5992 noteFullWifiLockReleasedLocked(uid);
Narayan Kamath728c8a02017-12-28 15:48:07 +00005993 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005994 }
5995 }
5996
Nick Pelly6ccaa542012-06-15 15:22:47 -07005997 public void noteWifiScanStartedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005998 int N = ws.size();
5999 for (int i=0; i<N; i++) {
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -08006000 final int uid = mapUid(ws.getUid(i));
Narayan Kamath728c8a02017-12-28 15:48:07 +00006001 noteWifiScanStartedLocked(uid);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006002 }
6003
6004 final List<WorkChain> workChains = ws.getWorkChains();
6005 if (workChains != null) {
6006 for (int i = 0; i < workChains.size(); ++i) {
6007 final WorkChain workChain = workChains.get(i);
6008 final int uid = mapUid(workChain.getAttributionUid());
6009 noteWifiScanStartedLocked(uid);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006010 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006011 }
6012 }
6013
Nick Pelly6ccaa542012-06-15 15:22:47 -07006014 public void noteWifiScanStoppedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006015 int N = ws.size();
6016 for (int i=0; i<N; i++) {
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -08006017 final int uid = mapUid(ws.getUid(i));
Narayan Kamath728c8a02017-12-28 15:48:07 +00006018 noteWifiScanStoppedLocked(uid);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006019 }
6020
6021 final List<WorkChain> workChains = ws.getWorkChains();
6022 if (workChains != null) {
6023 for (int i = 0; i < workChains.size(); ++i) {
6024 final WorkChain workChain = workChains.get(i);
6025 final int uid = mapUid(workChain.getAttributionUid());
6026 noteWifiScanStoppedLocked(uid);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006027 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006028 }
6029 }
6030
Robert Greenwalta029ea12013-09-25 16:38:12 -07006031 public void noteWifiBatchedScanStartedFromSourceLocked(WorkSource ws, int csph) {
6032 int N = ws.size();
6033 for (int i=0; i<N; i++) {
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -08006034 noteWifiBatchedScanStartedLocked(ws.getUid(i), csph);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006035 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00006036
6037 final List<WorkChain> workChains = ws.getWorkChains();
6038 if (workChains != null) {
6039 for (int i = 0; i < workChains.size(); ++i) {
6040 noteWifiBatchedScanStartedLocked(workChains.get(i).getAttributionUid(), csph);
6041 }
6042 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006043 }
6044
6045 public void noteWifiBatchedScanStoppedFromSourceLocked(WorkSource ws) {
6046 int N = ws.size();
6047 for (int i=0; i<N; i++) {
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -08006048 noteWifiBatchedScanStoppedLocked(ws.getUid(i));
Robert Greenwalta029ea12013-09-25 16:38:12 -07006049 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00006050
6051 final List<WorkChain> workChains = ws.getWorkChains();
6052 if (workChains != null) {
6053 for (int i = 0; i < workChains.size(); ++i) {
6054 noteWifiBatchedScanStoppedLocked(workChains.get(i).getAttributionUid());
6055 }
6056 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006057 }
6058
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08006059 private static String[] includeInStringArray(String[] array, String str) {
6060 if (ArrayUtils.indexOf(array, str) >= 0) {
6061 return array;
6062 }
6063 String[] newArray = new String[array.length+1];
6064 System.arraycopy(array, 0, newArray, 0, array.length);
6065 newArray[array.length] = str;
6066 return newArray;
6067 }
6068
6069 private static String[] excludeFromStringArray(String[] array, String str) {
6070 int index = ArrayUtils.indexOf(array, str);
6071 if (index >= 0) {
6072 String[] newArray = new String[array.length-1];
6073 if (index > 0) {
6074 System.arraycopy(array, 0, newArray, 0, index);
6075 }
6076 if (index < array.length-1) {
6077 System.arraycopy(array, index+1, newArray, index, array.length-index-1);
6078 }
6079 return newArray;
6080 }
6081 return array;
6082 }
6083
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07006084 public void noteNetworkInterfaceTypeLocked(String iface, int networkType) {
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07006085 if (TextUtils.isEmpty(iface)) return;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006086
Adam Lesinski14ae39a2017-05-26 11:50:40 -07006087 synchronized (mModemNetworkLock) {
6088 if (ConnectivityManager.isNetworkTypeMobile(networkType)) {
6089 mModemIfaces = includeInStringArray(mModemIfaces, iface);
6090 if (DEBUG) Slog.d(TAG, "Note mobile iface " + iface + ": " + mModemIfaces);
6091 } else {
6092 mModemIfaces = excludeFromStringArray(mModemIfaces, iface);
6093 if (DEBUG) Slog.d(TAG, "Note non-mobile iface " + iface + ": " + mModemIfaces);
6094 }
6095 }
6096
6097 synchronized (mWifiNetworkLock) {
6098 if (ConnectivityManager.isNetworkTypeWifi(networkType)) {
6099 mWifiIfaces = includeInStringArray(mWifiIfaces, iface);
6100 if (DEBUG) Slog.d(TAG, "Note wifi iface " + iface + ": " + mWifiIfaces);
6101 } else {
6102 mWifiIfaces = excludeFromStringArray(mWifiIfaces, iface);
6103 if (DEBUG) Slog.d(TAG, "Note non-wifi iface " + iface + ": " + mWifiIfaces);
6104 }
6105 }
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07006106 }
6107
David Chenc8a43242017-10-17 16:23:28 -07006108 public String[] getWifiIfaces() {
6109 synchronized (mWifiNetworkLock) {
6110 return mWifiIfaces;
6111 }
6112 }
6113
6114 public String[] getMobileIfaces() {
6115 synchronized (mModemNetworkLock) {
6116 return mModemIfaces;
6117 }
6118 }
6119
Mathew Inwoodaf972c82018-08-20 14:13:20 +01006120 @UnsupportedAppUsage
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006121 @Override public long getScreenOnTime(long elapsedRealtimeUs, int which) {
6122 return mScreenOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006123 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006124
Dianne Hackborn77b987f2014-02-26 16:20:52 -08006125 @Override public int getScreenOnCount(int which) {
6126 return mScreenOnTimer.getCountLocked(which);
6127 }
6128
Mike Mac2f518a2017-09-19 16:06:03 -07006129 @Override public long getScreenDozeTime(long elapsedRealtimeUs, int which) {
6130 return mScreenDozeTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6131 }
6132
6133 @Override public int getScreenDozeCount(int which) {
6134 return mScreenDozeTimer.getCountLocked(which);
6135 }
6136
Mathew Inwoodaf972c82018-08-20 14:13:20 +01006137 @UnsupportedAppUsage
Dianne Hackborn617f8772009-03-31 15:04:46 -07006138 @Override public long getScreenBrightnessTime(int brightnessBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006139 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006140 return mScreenBrightnessTimer[brightnessBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006141 elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006142 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006143
Kweku Adams87b19ec2017-10-09 12:40:03 -07006144 @Override public Timer getScreenBrightnessTimer(int brightnessBin) {
6145 return mScreenBrightnessTimer[brightnessBin];
6146 }
6147
Jeff Browne95c3cd2014-05-02 16:59:26 -07006148 @Override public long getInteractiveTime(long elapsedRealtimeUs, int which) {
6149 return mInteractiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006150 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006151
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006152 @Override public long getPowerSaveModeEnabledTime(long elapsedRealtimeUs, int which) {
6153 return mPowerSaveModeEnabledTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07006154 }
6155
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006156 @Override public int getPowerSaveModeEnabledCount(int which) {
6157 return mPowerSaveModeEnabledTimer.getCountLocked(which);
6158 }
6159
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006160 @Override public long getDeviceIdleModeTime(int mode, long elapsedRealtimeUs,
6161 int which) {
6162 switch (mode) {
6163 case DEVICE_IDLE_MODE_LIGHT:
6164 return mDeviceIdleModeLightTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006165 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006166 return mDeviceIdleModeFullTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6167 }
6168 return 0;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006169 }
6170
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006171 @Override public int getDeviceIdleModeCount(int mode, int which) {
6172 switch (mode) {
6173 case DEVICE_IDLE_MODE_LIGHT:
6174 return mDeviceIdleModeLightTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006175 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006176 return mDeviceIdleModeFullTimer.getCountLocked(which);
6177 }
6178 return 0;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07006179 }
6180
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006181 @Override public long getLongestDeviceIdleModeTime(int mode) {
6182 switch (mode) {
6183 case DEVICE_IDLE_MODE_LIGHT:
6184 return mLongestLightIdleTime;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006185 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006186 return mLongestFullIdleTime;
6187 }
6188 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07006189 }
6190
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006191 @Override public long getDeviceIdlingTime(int mode, long elapsedRealtimeUs, int which) {
6192 switch (mode) {
6193 case DEVICE_IDLE_MODE_LIGHT:
6194 return mDeviceLightIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006195 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006196 return mDeviceIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6197 }
6198 return 0;
6199 }
6200
6201 @Override public int getDeviceIdlingCount(int mode, int which) {
6202 switch (mode) {
6203 case DEVICE_IDLE_MODE_LIGHT:
6204 return mDeviceLightIdlingTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006205 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006206 return mDeviceIdlingTimer.getCountLocked(which);
6207 }
6208 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07006209 }
6210
Dianne Hackborn1e01d162014-12-04 17:46:42 -08006211 @Override public int getNumConnectivityChange(int which) {
Mike Ma99e57c32018-03-15 14:40:37 -07006212 return mNumConnectivityChange;
Dianne Hackborn1e01d162014-12-04 17:46:42 -08006213 }
6214
Siddharth Ray78ccaf52017-12-23 16:16:21 -08006215 @Override public long getGpsSignalQualityTime(int strengthBin,
6216 long elapsedRealtimeUs, int which) {
6217 if (strengthBin < 0 || strengthBin >= GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS) {
6218 return 0;
6219 }
6220 return mGpsSignalQualityTimer[strengthBin].getTotalTimeLocked(
6221 elapsedRealtimeUs, which);
6222 }
6223
6224 @Override public long getGpsBatteryDrainMaMs() {
Siddharth Ray0ed2e952018-01-22 11:32:14 -08006225 final double opVolt = mPowerProfile.getAveragePower(
6226 PowerProfile.POWER_GPS_OPERATING_VOLTAGE) / 1000.0;
6227 if (opVolt == 0) {
6228 return 0;
6229 }
6230 double energyUsedMaMs = 0.0;
6231 final int which = STATS_SINCE_CHARGED;
6232 final long rawRealtime = SystemClock.elapsedRealtime() * 1000;
6233 for(int i=0; i < GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
6234 energyUsedMaMs
6235 += mPowerProfile.getAveragePower(PowerProfile.POWER_GPS_SIGNAL_QUALITY_BASED, i)
6236 * (getGpsSignalQualityTime(i, rawRealtime, which) / 1000);
6237 }
6238 return (long) energyUsedMaMs;
Siddharth Ray78ccaf52017-12-23 16:16:21 -08006239 }
6240
Mathew Inwoodaf972c82018-08-20 14:13:20 +01006241 @UnsupportedAppUsage
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006242 @Override public long getPhoneOnTime(long elapsedRealtimeUs, int which) {
6243 return mPhoneOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006244 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006245
Dianne Hackborn77b987f2014-02-26 16:20:52 -08006246 @Override public int getPhoneOnCount(int which) {
6247 return mPhoneOnTimer.getCountLocked(which);
6248 }
6249
Mathew Inwoodaf972c82018-08-20 14:13:20 +01006250 @UnsupportedAppUsage
Dianne Hackborn627bba72009-03-24 22:32:56 -07006251 @Override public long getPhoneSignalStrengthTime(int strengthBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006252 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006253 return mPhoneSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006254 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07006255 }
Amith Yamasanif37447b2009-10-08 18:28:01 -07006256
Mathew Inwoodaf972c82018-08-20 14:13:20 +01006257 @UnsupportedAppUsage
Amith Yamasanif37447b2009-10-08 18:28:01 -07006258 @Override public long getPhoneSignalScanningTime(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006259 long elapsedRealtimeUs, int which) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07006260 return mPhoneSignalScanningTimer.getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006261 elapsedRealtimeUs, which);
Amith Yamasanif37447b2009-10-08 18:28:01 -07006262 }
6263
Kweku Adams87b19ec2017-10-09 12:40:03 -07006264 @Override public Timer getPhoneSignalScanningTimer() {
6265 return mPhoneSignalScanningTimer;
6266 }
6267
Mathew Inwoodaf972c82018-08-20 14:13:20 +01006268 @UnsupportedAppUsage
Catherine Liufb900812012-07-17 14:12:56 -05006269 @Override public int getPhoneSignalStrengthCount(int strengthBin, int which) {
6270 return mPhoneSignalStrengthsTimer[strengthBin].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006271 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006272
Kweku Adams87b19ec2017-10-09 12:40:03 -07006273 @Override public Timer getPhoneSignalStrengthTimer(int strengthBin) {
6274 return mPhoneSignalStrengthsTimer[strengthBin];
6275 }
6276
Mathew Inwoodaf972c82018-08-20 14:13:20 +01006277 @UnsupportedAppUsage
Dianne Hackborn627bba72009-03-24 22:32:56 -07006278 @Override public long getPhoneDataConnectionTime(int dataType,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006279 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006280 return mPhoneDataConnectionsTimer[dataType].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006281 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07006282 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006283
Mathew Inwoodaf972c82018-08-20 14:13:20 +01006284 @UnsupportedAppUsage
Dianne Hackborn617f8772009-03-31 15:04:46 -07006285 @Override public int getPhoneDataConnectionCount(int dataType, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006286 return mPhoneDataConnectionsTimer[dataType].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006287 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006288
Kweku Adams87b19ec2017-10-09 12:40:03 -07006289 @Override public Timer getPhoneDataConnectionTimer(int dataType) {
6290 return mPhoneDataConnectionsTimer[dataType];
6291 }
6292
Mathew Inwoodaf972c82018-08-20 14:13:20 +01006293 @UnsupportedAppUsage
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006294 @Override public long getMobileRadioActiveTime(long elapsedRealtimeUs, int which) {
6295 return mMobileRadioActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborne13c4c02014-02-11 17:18:35 -08006296 }
6297
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006298 @Override public int getMobileRadioActiveCount(int which) {
6299 return mMobileRadioActiveTimer.getCountLocked(which);
6300 }
6301
Dianne Hackborna1bd7922014-03-21 11:07:11 -07006302 @Override public long getMobileRadioActiveAdjustedTime(int which) {
6303 return mMobileRadioActiveAdjustedTime.getCountLocked(which);
6304 }
6305
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006306 @Override public long getMobileRadioActiveUnknownTime(int which) {
6307 return mMobileRadioActiveUnknownTime.getCountLocked(which);
6308 }
6309
6310 @Override public int getMobileRadioActiveUnknownCount(int which) {
6311 return (int)mMobileRadioActiveUnknownCount.getCountLocked(which);
6312 }
6313
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006314 @Override public long getWifiMulticastWakelockTime(
6315 long elapsedRealtimeUs, int which) {
6316 return mWifiMulticastWakelockTimer.getTotalTimeLocked(
6317 elapsedRealtimeUs, which);
6318 }
6319
6320 @Override public int getWifiMulticastWakelockCount(int which) {
6321 return mWifiMulticastWakelockTimer.getCountLocked(which);
6322 }
6323
Mathew Inwoodaf972c82018-08-20 14:13:20 +01006324 @UnsupportedAppUsage
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006325 @Override public long getWifiOnTime(long elapsedRealtimeUs, int which) {
6326 return mWifiOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07006327 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006328
Siddharth Rayb50a6842017-12-14 15:15:28 -08006329 @Override public long getWifiActiveTime(long elapsedRealtimeUs, int which) {
6330 return mWifiActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6331 }
6332
Mathew Inwoodaf972c82018-08-20 14:13:20 +01006333 @UnsupportedAppUsage
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006334 @Override public long getGlobalWifiRunningTime(long elapsedRealtimeUs, int which) {
6335 return mGlobalWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07006336 }
6337
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006338 @Override public long getWifiStateTime(int wifiState,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006339 long elapsedRealtimeUs, int which) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006340 return mWifiStateTimer[wifiState].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006341 elapsedRealtimeUs, which);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006342 }
6343
6344 @Override public int getWifiStateCount(int wifiState, int which) {
6345 return mWifiStateTimer[wifiState].getCountLocked(which);
6346 }
6347
Kweku Adams87b19ec2017-10-09 12:40:03 -07006348 @Override public Timer getWifiStateTimer(int wifiState) {
6349 return mWifiStateTimer[wifiState];
6350 }
6351
Dianne Hackborn3251b902014-06-20 14:40:53 -07006352 @Override public long getWifiSupplStateTime(int state,
6353 long elapsedRealtimeUs, int which) {
6354 return mWifiSupplStateTimer[state].getTotalTimeLocked(
6355 elapsedRealtimeUs, which);
6356 }
6357
6358 @Override public int getWifiSupplStateCount(int state, int which) {
6359 return mWifiSupplStateTimer[state].getCountLocked(which);
6360 }
6361
Kweku Adams87b19ec2017-10-09 12:40:03 -07006362 @Override public Timer getWifiSupplStateTimer(int state) {
6363 return mWifiSupplStateTimer[state];
6364 }
6365
Dianne Hackborn3251b902014-06-20 14:40:53 -07006366 @Override public long getWifiSignalStrengthTime(int strengthBin,
6367 long elapsedRealtimeUs, int which) {
6368 return mWifiSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
6369 elapsedRealtimeUs, which);
6370 }
6371
6372 @Override public int getWifiSignalStrengthCount(int strengthBin, int which) {
6373 return mWifiSignalStrengthsTimer[strengthBin].getCountLocked(which);
6374 }
6375
Kweku Adams87b19ec2017-10-09 12:40:03 -07006376 @Override public Timer getWifiSignalStrengthTimer(int strengthBin) {
6377 return mWifiSignalStrengthsTimer[strengthBin];
6378 }
6379
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006380 @Override
6381 public ControllerActivityCounter getBluetoothControllerActivity() {
6382 return mBluetoothActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07006383 }
6384
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006385 @Override
6386 public ControllerActivityCounter getWifiControllerActivity() {
6387 return mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -07006388 }
6389
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006390 @Override
6391 public ControllerActivityCounter getModemControllerActivity() {
6392 return mModemActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07006393 }
6394
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006395 @Override
6396 public boolean hasBluetoothActivityReporting() {
6397 return mHasBluetoothReporting;
6398 }
6399
6400 @Override
6401 public boolean hasWifiActivityReporting() {
6402 return mHasWifiReporting;
6403 }
6404
6405 @Override
6406 public boolean hasModemActivityReporting() {
6407 return mHasModemReporting;
Adam Lesinski33dac552015-03-09 15:24:48 -07006408 }
6409
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006410 @Override
6411 public long getFlashlightOnTime(long elapsedRealtimeUs, int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07006412 return mFlashlightOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6413 }
6414
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006415 @Override
6416 public long getFlashlightOnCount(int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07006417 return mFlashlightOnTimer.getCountLocked(which);
6418 }
6419
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006420 @Override
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006421 public long getCameraOnTime(long elapsedRealtimeUs, int which) {
6422 return mCameraOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6423 }
6424
6425 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006426 public long getBluetoothScanTime(long elapsedRealtimeUs, int which) {
6427 return mBluetoothScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6428 }
6429
6430 @Override
Mathew Inwoodaf972c82018-08-20 14:13:20 +01006431 @UnsupportedAppUsage
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006432 public long getNetworkActivityBytes(int type, int which) {
6433 if (type >= 0 && type < mNetworkByteActivityCounters.length) {
6434 return mNetworkByteActivityCounters[type].getCountLocked(which);
6435 } else {
6436 return 0;
6437 }
6438 }
6439
6440 @Override
6441 public long getNetworkActivityPackets(int type, int which) {
6442 if (type >= 0 && type < mNetworkPacketActivityCounters.length) {
6443 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006444 } else {
6445 return 0;
6446 }
6447 }
6448
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08006449 @Override public long getStartClockTime() {
Dianne Hackbornd48954f2015-07-22 17:20:33 -07006450 final long currentTime = System.currentTimeMillis();
Hui Yu5104da02019-06-03 13:58:20 -07006451 if ((currentTime > MILLISECONDS_IN_YEAR
6452 && mStartClockTime < (currentTime - MILLISECONDS_IN_YEAR))
6453 || (mStartClockTime > currentTime)) {
6454 // If the start clock time has changed by more than a year, then presumably
6455 // the previous time was completely bogus. So we are going to figure out a
6456 // new time based on how much time has elapsed since we started counting.
Joe Onoratoabded112016-02-08 16:49:39 -08006457 recordCurrentTimeChangeLocked(currentTime, mClocks.elapsedRealtime(),
6458 mClocks.uptimeMillis());
Hui Yu5104da02019-06-03 13:58:20 -07006459 return currentTime - (mClocks.elapsedRealtime() - (mRealtimeStart / 1000));
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07006460 }
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08006461 return mStartClockTime;
6462 }
6463
Dianne Hackborncd0e3352014-08-07 17:08:09 -07006464 @Override public String getStartPlatformVersion() {
6465 return mStartPlatformVersion;
6466 }
6467
6468 @Override public String getEndPlatformVersion() {
6469 return mEndPlatformVersion;
6470 }
6471
6472 @Override public int getParcelVersion() {
6473 return VERSION;
6474 }
6475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006476 @Override public boolean getIsOnBattery() {
6477 return mOnBattery;
6478 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006479
Mathew Inwoodaf972c82018-08-20 14:13:20 +01006480 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006481 @Override public SparseArray<? extends BatteryStats.Uid> getUidStats() {
6482 return mUidStats;
6483 }
6484
Hui Yu8e88e952018-07-23 17:59:59 -07006485 private static <T extends TimeBaseObs> boolean resetIfNotNull(T t, boolean detachIfReset) {
6486 if (t != null) {
6487 return t.reset(detachIfReset);
Adam Lesinski5f056f62016-07-14 16:56:08 -07006488 }
6489 return true;
6490 }
6491
Hui Yu8e88e952018-07-23 17:59:59 -07006492 private static <T extends TimeBaseObs> boolean resetIfNotNull(T[] t, boolean detachIfReset) {
6493 if (t != null) {
6494 boolean ret = true;
6495 for (int i = 0; i < t.length; i++) {
6496 ret &= resetIfNotNull(t[i], detachIfReset);
6497 }
6498 return ret;
Bookatz867c0d72017-03-07 18:23:42 -08006499 }
6500 return true;
6501 }
6502
Hui Yu8e88e952018-07-23 17:59:59 -07006503 private static <T extends TimeBaseObs> boolean resetIfNotNull(T[][] t, boolean detachIfReset) {
6504 if (t != null) {
6505 boolean ret = true;
6506 for (int i = 0; i < t.length; i++) {
6507 ret &= resetIfNotNull(t[i], detachIfReset);
6508 }
6509 return ret;
Adam Lesinski5f056f62016-07-14 16:56:08 -07006510 }
Hui Yu8e88e952018-07-23 17:59:59 -07006511 return true;
Adam Lesinski5f056f62016-07-14 16:56:08 -07006512 }
6513
Hui Yu10571e02018-08-06 13:12:40 -07006514 private static boolean resetIfNotNull(ControllerActivityCounterImpl counter,
6515 boolean detachIfReset) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07006516 if (counter != null) {
6517 counter.reset(detachIfReset);
6518 }
Hui Yu8e88e952018-07-23 17:59:59 -07006519 return true;
6520 }
6521
6522 private static <T extends TimeBaseObs> void detachIfNotNull(T t) {
6523 if (t != null) {
6524 t.detach();
6525 }
6526 }
6527
6528 private static <T extends TimeBaseObs> void detachIfNotNull(T[] t) {
6529 if (t != null) {
6530 for (int i = 0; i < t.length; i++) {
6531 detachIfNotNull(t[i]);
6532 }
6533 }
6534 }
6535
6536 private static <T extends TimeBaseObs> void detachIfNotNull(T[][] t) {
6537 if (t != null) {
6538 for (int i = 0; i < t.length; i++) {
6539 detachIfNotNull(t[i]);
6540 }
6541 }
6542 }
6543
6544 private static void detachIfNotNull(ControllerActivityCounterImpl counter) {
6545 if (counter != null) {
6546 counter.detach();
6547 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07006548 }
6549
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006550 /**
6551 * The statistics associated with a particular uid.
6552 */
Joe Onoratoabded112016-02-08 16:49:39 -08006553 public static class Uid extends BatteryStats.Uid {
6554 /**
6555 * BatteryStatsImpl that we are associated with.
6556 */
6557 protected BatteryStatsImpl mBsi;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006558
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006559 final int mUid;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006560
Bookatz867c0d72017-03-07 18:23:42 -08006561 /** TimeBase for when uid is in background and device is on battery. */
6562 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6563 public final TimeBase mOnBatteryBackgroundTimeBase;
Bookatzc8c44962017-05-11 12:12:54 -07006564 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6565 public final TimeBase mOnBatteryScreenOffBackgroundTimeBase;
Bookatz867c0d72017-03-07 18:23:42 -08006566
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006567 boolean mWifiRunning;
6568 StopwatchTimer mWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006569
The Android Open Source Project10592532009-03-18 17:39:46 -07006570 boolean mFullWifiLockOut;
Evan Millarc64edde2009-04-18 12:26:32 -07006571 StopwatchTimer mFullWifiLockTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006572
Nick Pelly6ccaa542012-06-15 15:22:47 -07006573 boolean mWifiScanStarted;
Bookatz867c0d72017-03-07 18:23:42 -08006574 DualTimer mWifiScanTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006575
Dianne Hackborn61659e52014-07-09 16:13:01 -07006576 static final int NO_BATCHED_SCAN_STARTED = -1;
Robert Greenwalta029ea12013-09-25 16:38:12 -07006577 int mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
6578 StopwatchTimer[] mWifiBatchedScanTimer;
6579
Ahmed ElArabawy6f1754e2017-11-28 15:50:32 -08006580 int mWifiMulticastWakelockCount;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006581 StopwatchTimer mWifiMulticastTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006582
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006583 StopwatchTimer mAudioTurnedOnTimer;
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006584 StopwatchTimer mVideoTurnedOnTimer;
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006585 StopwatchTimer mFlashlightTurnedOnTimer;
6586 StopwatchTimer mCameraTurnedOnTimer;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006587 StopwatchTimer mForegroundActivityTimer;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006588 StopwatchTimer mForegroundServiceTimer;
Bookatzc8c44962017-05-11 12:12:54 -07006589 /** Total time spent by the uid holding any partial wakelocks. */
6590 DualTimer mAggregatedPartialWakelockTimer;
Bookatz867c0d72017-03-07 18:23:42 -08006591 DualTimer mBluetoothScanTimer;
Bookatzb1f04f32017-05-19 13:57:32 -07006592 DualTimer mBluetoothUnoptimizedScanTimer;
Bookatz956f36bf2017-04-28 09:48:17 -07006593 Counter mBluetoothScanResultCounter;
Bookatzb1f04f32017-05-19 13:57:32 -07006594 Counter mBluetoothScanResultBgCounter;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006595
Dianne Hackborna8d10942015-11-19 17:55:19 -08006596 int mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07006597 StopwatchTimer[] mProcessStateTimer;
6598
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006599 boolean mInForegroundService = false;
6600
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006601 BatchTimer mVibratorOnTimer;
6602
Dianne Hackborn617f8772009-03-31 15:04:46 -07006603 Counter[] mUserActivityCounters;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006604
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006605 LongSamplingCounter[] mNetworkByteActivityCounters;
6606 LongSamplingCounter[] mNetworkPacketActivityCounters;
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006607 LongSamplingCounter mMobileRadioActiveTime;
6608 LongSamplingCounter mMobileRadioActiveCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006610 /**
Adam Lesinski5f056f62016-07-14 16:56:08 -07006611 * How many times this UID woke up the Application Processor due to a Mobile radio packet.
6612 */
6613 private LongSamplingCounter mMobileRadioApWakeupCount;
6614
6615 /**
6616 * How many times this UID woke up the Application Processor due to a Wifi packet.
6617 */
6618 private LongSamplingCounter mWifiRadioApWakeupCount;
6619
6620 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07006621 * The amount of time this uid has kept the WiFi controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006622 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07006623 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006624 private ControllerActivityCounterImpl mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006625
6626 /**
6627 * The amount of time this uid has kept the Bluetooth controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006628 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07006629 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006630 private ControllerActivityCounterImpl mBluetoothControllerActivity;
6631
6632 /**
6633 * The amount of time this uid has kept the Modem controller in idle, tx, and rx mode.
6634 * Can be null if the UID has had no such activity.
6635 */
6636 private ControllerActivityCounterImpl mModemControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006637
6638 /**
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006639 * The CPU times we had at the last history details update.
6640 */
6641 long mLastStepUserTime;
6642 long mLastStepSystemTime;
6643 long mCurStepUserTime;
6644 long mCurStepSystemTime;
6645
Joe Onoratoabded112016-02-08 16:49:39 -08006646 LongSamplingCounter mUserCpuTime;
6647 LongSamplingCounter mSystemCpuTime;
Sudheer Shankaaf857412017-07-21 00:14:24 -07006648 LongSamplingCounter[][] mCpuClusterSpeedTimesUs;
Mike Ma3d422c32017-10-25 11:08:57 -07006649 LongSamplingCounter mCpuActiveTimeMs;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006650
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006651 LongSamplingCounterArray mCpuFreqTimeMs;
6652 LongSamplingCounterArray mScreenOffCpuFreqTimeMs;
Mike Ma3d422c32017-10-25 11:08:57 -07006653 LongSamplingCounterArray mCpuClusterTimesMs;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006654
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006655 LongSamplingCounterArray[] mProcStateTimeMs;
6656 LongSamplingCounterArray[] mProcStateScreenOffTimeMs;
6657
6658 IntArray mChildUids;
6659
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006660 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006661 * The statistics we have collected for this uid's wake locks.
6662 */
Joe Onoratoabded112016-02-08 16:49:39 -08006663 final OverflowArrayMap<Wakelock> mWakelockStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006664
6665 /**
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006666 * The statistics we have collected for this uid's syncs.
6667 */
Bookatz2bffb5b2017-04-13 11:59:33 -07006668 final OverflowArrayMap<DualTimer> mSyncStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006669
6670 /**
6671 * The statistics we have collected for this uid's jobs.
6672 */
Bookatzaa4594a2017-03-24 12:39:56 -07006673 final OverflowArrayMap<DualTimer> mJobStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006674
6675 /**
Dianne Hackborn94326cb2017-06-28 16:17:20 -07006676 * Count of the jobs that have completed and the reasons why they completed.
6677 */
6678 final ArrayMap<String, SparseIntArray> mJobCompletions = new ArrayMap<>();
6679
6680 /**
Amith Yamasani977e11f2018-02-16 11:29:54 -08006681 * Count of app launch events that had associated deferred job counts or info about
6682 * last time a job was run.
6683 */
6684 Counter mJobsDeferredEventCount;
6685
6686 /**
6687 * Count of deferred jobs that were pending when the app was launched or brought to
6688 * the foreground through a user interaction.
6689 */
6690 Counter mJobsDeferredCount;
6691
6692 /**
6693 * Sum of time since the last time a job was run for this app before it was launched.
6694 */
6695 LongSamplingCounter mJobsFreshnessTimeMs;
6696
6697 /**
6698 * Array of counts of instances where the time since the last job was run for the app
6699 * fell within one of the thresholds in {@link #JOB_FRESHNESS_BUCKETS}.
6700 */
6701 final Counter[] mJobsFreshnessBuckets;
6702
6703 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006704 * The statistics we have collected for this uid's sensor activations.
6705 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006706 final SparseArray<Sensor> mSensorStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006707
6708 /**
6709 * The statistics we have collected for this uid's processes.
6710 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006711 final ArrayMap<String, Proc> mProcessStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006712
6713 /**
6714 * The statistics we have collected for this uid's processes.
6715 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006716 final ArrayMap<String, Pkg> mPackageStats = new ArrayMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006717
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006718 /**
6719 * The transient wake stats we have collected for this uid's pids.
6720 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006721 final SparseArray<Pid> mPids = new SparseArray<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006722
Joe Onoratoabded112016-02-08 16:49:39 -08006723 public Uid(BatteryStatsImpl bsi, int uid) {
6724 mBsi = bsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006725 mUid = uid;
Joe Onoratoabded112016-02-08 16:49:39 -08006726
Hui Yu8e88e952018-07-23 17:59:59 -07006727 /* Observer list of TimeBase object in Uid is short */
6728 mOnBatteryBackgroundTimeBase = new TimeBase(false);
Bookatz867c0d72017-03-07 18:23:42 -08006729 mOnBatteryBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
6730 mBsi.mClocks.elapsedRealtime() * 1000);
Hui Yu8e88e952018-07-23 17:59:59 -07006731 /* Observer list of TimeBase object in Uid is short */
6732 mOnBatteryScreenOffBackgroundTimeBase = new TimeBase(false);
Bookatzc8c44962017-05-11 12:12:54 -07006733 mOnBatteryScreenOffBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
6734 mBsi.mClocks.elapsedRealtime() * 1000);
6735
Joe Onoratoabded112016-02-08 16:49:39 -08006736 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6737 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Mike Ma3d422c32017-10-25 11:08:57 -07006738 mCpuActiveTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6739 mCpuClusterTimesMs = new LongSamplingCounterArray(mBsi.mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006740
Dianne Hackborn657153b2016-07-29 14:54:14 -07006741 mWakelockStats = mBsi.new OverflowArrayMap<Wakelock>(uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006742 @Override public Wakelock instantiateObject() {
6743 return new Wakelock(mBsi, Uid.this);
6744 }
6745 };
Bookatz2bffb5b2017-04-13 11:59:33 -07006746 mSyncStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
6747 @Override public DualTimer instantiateObject() {
6748 return new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
6749 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006750 }
6751 };
Bookatzaa4594a2017-03-24 12:39:56 -07006752 mJobStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
6753 @Override public DualTimer instantiateObject() {
6754 return new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
6755 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006756 }
6757 };
6758
6759 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_RUNNING,
6760 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
6761 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, this, FULL_WIFI_LOCK,
6762 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Bookatz867c0d72017-03-07 18:23:42 -08006763 mWifiScanTimer = new DualTimer(mBsi.mClocks, this, WIFI_SCAN,
6764 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006765 mWifiBatchedScanTimer = new StopwatchTimer[NUM_WIFI_BATCHED_SCAN_BINS];
Joe Onoratoabded112016-02-08 16:49:39 -08006766 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_MULTICAST_ENABLED,
6767 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006768 mProcessStateTimer = new StopwatchTimer[NUM_PROCESS_STATE];
Amith Yamasani977e11f2018-02-16 11:29:54 -08006769 mJobsDeferredEventCount = new Counter(mBsi.mOnBatteryTimeBase);
6770 mJobsDeferredCount = new Counter(mBsi.mOnBatteryTimeBase);
6771 mJobsFreshnessTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6772 mJobsFreshnessBuckets = new Counter[JOB_FRESHNESS_BUCKETS.length];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006773 }
6774
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006775 @VisibleForTesting
6776 public void setProcessStateForTest(int procState) {
6777 mProcessState = procState;
6778 }
6779
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006780 @Override
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006781 public long[] getCpuFreqTimes(int which) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006782 return nullIfAllZeros(mCpuFreqTimeMs, which);
6783 }
6784
6785 @Override
6786 public long[] getScreenOffCpuFreqTimes(int which) {
6787 return nullIfAllZeros(mScreenOffCpuFreqTimeMs, which);
6788 }
6789
6790 @Override
Mike Ma3d422c32017-10-25 11:08:57 -07006791 public long getCpuActiveTime() {
6792 return mCpuActiveTimeMs.getCountLocked(STATS_SINCE_CHARGED);
6793 }
6794
6795 @Override
6796 public long[] getCpuClusterTimes() {
6797 return nullIfAllZeros(mCpuClusterTimesMs, STATS_SINCE_CHARGED);
6798 }
6799
6800
6801 @Override
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006802 public long[] getCpuFreqTimes(int which, int procState) {
6803 if (which < 0 || which >= NUM_PROCESS_STATE) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006804 return null;
6805 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006806 if (mProcStateTimeMs == null) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006807 return null;
6808 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006809 if (!mBsi.mPerProcStateCpuTimesAvailable) {
6810 mProcStateTimeMs = null;
6811 return null;
6812 }
6813 return nullIfAllZeros(mProcStateTimeMs[procState], which);
6814 }
6815
6816 @Override
6817 public long[] getScreenOffCpuFreqTimes(int which, int procState) {
6818 if (which < 0 || which >= NUM_PROCESS_STATE) {
6819 return null;
6820 }
6821 if (mProcStateScreenOffTimeMs == null) {
6822 return null;
6823 }
6824 if (!mBsi.mPerProcStateCpuTimesAvailable) {
6825 mProcStateScreenOffTimeMs = null;
6826 return null;
6827 }
6828 return nullIfAllZeros(mProcStateScreenOffTimeMs[procState], which);
6829 }
6830
6831 public void addIsolatedUid(int isolatedUid) {
6832 if (mChildUids == null) {
6833 mChildUids = new IntArray();
6834 } else if (mChildUids.indexOf(isolatedUid) >= 0) {
6835 return;
6836 }
6837 mChildUids.add(isolatedUid);
6838 }
6839
6840 public void removeIsolatedUid(int isolatedUid) {
6841 final int idx = mChildUids == null ? -1 : mChildUids.indexOf(isolatedUid);
6842 if (idx < 0) {
6843 return;
6844 }
6845 mChildUids.remove(idx);
6846 }
6847
6848 private long[] nullIfAllZeros(LongSamplingCounterArray cpuTimesMs, int which) {
6849 if (cpuTimesMs == null) {
6850 return null;
6851 }
6852 final long[] counts = cpuTimesMs.getCountsLocked(which);
6853 if (counts == null) {
6854 return null;
6855 }
6856 // Return counts only if at least one of the elements is non-zero.
6857 for (int i = counts.length - 1; i >= 0; --i) {
6858 if (counts[i] != 0) {
6859 return counts;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006860 }
6861 }
6862 return null;
6863 }
6864
Sudheer Shankae544d162017-12-28 17:06:20 -08006865 private void addProcStateTimesMs(int procState, long[] cpuTimesMs, boolean onBattery) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006866 if (mProcStateTimeMs == null) {
6867 mProcStateTimeMs = new LongSamplingCounterArray[NUM_PROCESS_STATE];
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006868 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006869 if (mProcStateTimeMs[procState] == null
6870 || mProcStateTimeMs[procState].getSize() != cpuTimesMs.length) {
Hui Yu10571e02018-08-06 13:12:40 -07006871 detachIfNotNull(mProcStateTimeMs[procState]);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006872 mProcStateTimeMs[procState] = new LongSamplingCounterArray(
6873 mBsi.mOnBatteryTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006874 }
Sudheer Shankae544d162017-12-28 17:06:20 -08006875 mProcStateTimeMs[procState].addCountLocked(cpuTimesMs, onBattery);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006876 }
6877
Sudheer Shankae544d162017-12-28 17:06:20 -08006878 private void addProcStateScreenOffTimesMs(int procState, long[] cpuTimesMs,
6879 boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006880 if (mProcStateScreenOffTimeMs == null) {
6881 mProcStateScreenOffTimeMs = new LongSamplingCounterArray[NUM_PROCESS_STATE];
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006882 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006883 if (mProcStateScreenOffTimeMs[procState] == null
6884 || mProcStateScreenOffTimeMs[procState].getSize() != cpuTimesMs.length) {
Hui Yu8e88e952018-07-23 17:59:59 -07006885 detachIfNotNull(mProcStateScreenOffTimeMs[procState]);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006886 mProcStateScreenOffTimeMs[procState] = new LongSamplingCounterArray(
6887 mBsi.mOnBatteryScreenOffTimeBase);
6888 }
Sudheer Shankae544d162017-12-28 17:06:20 -08006889 mProcStateScreenOffTimeMs[procState].addCountLocked(cpuTimesMs, onBatteryScreenOff);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006890 }
6891
6892 @Override
Bookatzc8c44962017-05-11 12:12:54 -07006893 public Timer getAggregatedPartialWakelockTimer() {
6894 return mAggregatedPartialWakelockTimer;
6895 }
6896
6897 @Override
Mathew Inwoodaf972c82018-08-20 14:13:20 +01006898 @UnsupportedAppUsage
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006899 public ArrayMap<String, ? extends BatteryStats.Uid.Wakelock> getWakelockStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006900 return mWakelockStats.getMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006901 }
6902
6903 @Override
Ahmed ElArabawyddd09692017-10-30 17:58:29 -07006904 public Timer getMulticastWakelockStats() {
6905 return mWifiMulticastTimer;
6906 }
6907
6908 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006909 public ArrayMap<String, ? extends BatteryStats.Timer> getSyncStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006910 return mSyncStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006911 }
6912
6913 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006914 public ArrayMap<String, ? extends BatteryStats.Timer> getJobStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006915 return mJobStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006916 }
6917
6918 @Override
Dianne Hackborn94326cb2017-06-28 16:17:20 -07006919 public ArrayMap<String, SparseIntArray> getJobCompletionStats() {
6920 return mJobCompletions;
6921 }
6922
6923 @Override
Mathew Inwoodaf972c82018-08-20 14:13:20 +01006924 @UnsupportedAppUsage
Dianne Hackborn61659e52014-07-09 16:13:01 -07006925 public SparseArray<? extends BatteryStats.Uid.Sensor> getSensorStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006926 return mSensorStats;
6927 }
6928
6929 @Override
Mathew Inwoodaf972c82018-08-20 14:13:20 +01006930 @UnsupportedAppUsage
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006931 public ArrayMap<String, ? extends BatteryStats.Uid.Proc> getProcessStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006932 return mProcessStats;
6933 }
6934
6935 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006936 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg> getPackageStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006937 return mPackageStats;
6938 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07006939
6940 @Override
Mathew Inwoodaf972c82018-08-20 14:13:20 +01006941 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006942 public int getUid() {
6943 return mUid;
6944 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07006945
6946 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006947 public void noteWifiRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006948 if (!mWifiRunning) {
6949 mWifiRunning = true;
6950 if (mWifiRunningTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006951 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
6952 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006953 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006954 mWifiRunningTimer.startRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006955 }
6956 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006957
Dianne Hackborn617f8772009-03-31 15:04:46 -07006958 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006959 public void noteWifiStoppedLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006960 if (mWifiRunning) {
6961 mWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006962 mWifiRunningTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006963 }
6964 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006965
Dianne Hackborn617f8772009-03-31 15:04:46 -07006966 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006967 public void noteFullWifiLockAcquiredLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07006968 if (!mFullWifiLockOut) {
6969 mFullWifiLockOut = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006970 if (mFullWifiLockTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006971 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
6972 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006973 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006974 mFullWifiLockTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07006975 }
6976 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006977
The Android Open Source Project10592532009-03-18 17:39:46 -07006978 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006979 public void noteFullWifiLockReleasedLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07006980 if (mFullWifiLockOut) {
6981 mFullWifiLockOut = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006982 mFullWifiLockTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07006983 }
6984 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006985
The Android Open Source Project10592532009-03-18 17:39:46 -07006986 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006987 public void noteWifiScanStartedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07006988 if (!mWifiScanStarted) {
6989 mWifiScanStarted = true;
6990 if (mWifiScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08006991 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
6992 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase,
6993 mOnBatteryBackgroundTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006994 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006995 mWifiScanTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07006996 }
6997 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006998
The Android Open Source Project10592532009-03-18 17:39:46 -07006999 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007000 public void noteWifiScanStoppedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007001 if (mWifiScanStarted) {
7002 mWifiScanStarted = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007003 mWifiScanTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007004 }
7005 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007006
7007 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007008 public void noteWifiBatchedScanStartedLocked(int csph, long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007009 int bin = 0;
Navtej Singh Mann3c0ce5c2015-06-11 16:53:11 -07007010 while (csph > 8 && bin < NUM_WIFI_BATCHED_SCAN_BINS-1) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007011 csph = csph >> 3;
7012 bin++;
7013 }
7014
7015 if (mWifiBatchedScanBinStarted == bin) return;
7016
7017 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
7018 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007019 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007020 }
7021 mWifiBatchedScanBinStarted = bin;
7022 if (mWifiBatchedScanTimer[bin] == null) {
7023 makeWifiBatchedScanBin(bin, null);
7024 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007025 mWifiBatchedScanTimer[bin].startRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007026 }
7027
7028 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007029 public void noteWifiBatchedScanStoppedLocked(long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007030 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
7031 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007032 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007033 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
7034 }
7035 }
7036
7037 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007038 public void noteWifiMulticastEnabledLocked(long elapsedRealtimeMs) {
Ahmed ElArabawy6f1754e2017-11-28 15:50:32 -08007039 if (mWifiMulticastWakelockCount == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007040 if (mWifiMulticastTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007041 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7042 WIFI_MULTICAST_ENABLED, mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007043 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007044 mWifiMulticastTimer.startRunningLocked(elapsedRealtimeMs);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007045 }
Ahmed ElArabawy6f1754e2017-11-28 15:50:32 -08007046 mWifiMulticastWakelockCount++;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007047 }
7048
7049 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007050 public void noteWifiMulticastDisabledLocked(long elapsedRealtimeMs) {
Ahmed ElArabawy6f1754e2017-11-28 15:50:32 -08007051 if (mWifiMulticastWakelockCount == 0) {
7052 return;
7053 }
7054
7055 mWifiMulticastWakelockCount--;
7056 if (mWifiMulticastWakelockCount == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007057 mWifiMulticastTimer.stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007058 }
7059 }
7060
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007061 @Override
7062 public ControllerActivityCounter getWifiControllerActivity() {
7063 return mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07007064 }
7065
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007066 @Override
7067 public ControllerActivityCounter getBluetoothControllerActivity() {
7068 return mBluetoothControllerActivity;
7069 }
7070
7071 @Override
7072 public ControllerActivityCounter getModemControllerActivity() {
7073 return mModemControllerActivity;
7074 }
7075
7076 public ControllerActivityCounterImpl getOrCreateWifiControllerActivityLocked() {
7077 if (mWifiControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007078 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007079 NUM_BT_TX_LEVELS);
Adam Lesinski50e47602015-12-04 17:04:54 -08007080 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007081 return mWifiControllerActivity;
7082 }
7083
7084 public ControllerActivityCounterImpl getOrCreateBluetoothControllerActivityLocked() {
7085 if (mBluetoothControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007086 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007087 NUM_BT_TX_LEVELS);
7088 }
7089 return mBluetoothControllerActivity;
7090 }
7091
7092 public ControllerActivityCounterImpl getOrCreateModemControllerActivityLocked() {
7093 if (mModemControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007094 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007095 ModemActivityInfo.TX_POWER_LEVELS);
7096 }
7097 return mModemControllerActivity;
Adam Lesinski50e47602015-12-04 17:04:54 -08007098 }
7099
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007100 public StopwatchTimer createAudioTurnedOnTimerLocked() {
7101 if (mAudioTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007102 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
7103 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007104 }
7105 return mAudioTurnedOnTimer;
7106 }
7107
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007108 public void noteAudioTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007109 createAudioTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
7110 }
7111
7112 public void noteAudioTurnedOffLocked(long elapsedRealtimeMs) {
7113 if (mAudioTurnedOnTimer != null) {
7114 mAudioTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007115 }
7116 }
7117
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007118 public void noteResetAudioLocked(long elapsedRealtimeMs) {
7119 if (mAudioTurnedOnTimer != null) {
7120 mAudioTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007121 }
7122 }
7123
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007124 public StopwatchTimer createVideoTurnedOnTimerLocked() {
7125 if (mVideoTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007126 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
7127 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007128 }
7129 return mVideoTurnedOnTimer;
7130 }
7131
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007132 public void noteVideoTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007133 createVideoTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
7134 }
7135
7136 public void noteVideoTurnedOffLocked(long elapsedRealtimeMs) {
7137 if (mVideoTurnedOnTimer != null) {
7138 mVideoTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007139 }
7140 }
7141
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007142 public void noteResetVideoLocked(long elapsedRealtimeMs) {
7143 if (mVideoTurnedOnTimer != null) {
7144 mVideoTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007145 }
7146 }
7147
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007148 public StopwatchTimer createFlashlightTurnedOnTimerLocked() {
7149 if (mFlashlightTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007150 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7151 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007152 }
7153 return mFlashlightTurnedOnTimer;
7154 }
7155
7156 public void noteFlashlightTurnedOnLocked(long elapsedRealtimeMs) {
7157 createFlashlightTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
7158 }
7159
7160 public void noteFlashlightTurnedOffLocked(long elapsedRealtimeMs) {
7161 if (mFlashlightTurnedOnTimer != null) {
7162 mFlashlightTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
7163 }
7164 }
7165
7166 public void noteResetFlashlightLocked(long elapsedRealtimeMs) {
7167 if (mFlashlightTurnedOnTimer != null) {
7168 mFlashlightTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
7169 }
7170 }
7171
7172 public StopwatchTimer createCameraTurnedOnTimerLocked() {
7173 if (mCameraTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007174 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
7175 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007176 }
7177 return mCameraTurnedOnTimer;
7178 }
7179
7180 public void noteCameraTurnedOnLocked(long elapsedRealtimeMs) {
7181 createCameraTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
7182 }
7183
7184 public void noteCameraTurnedOffLocked(long elapsedRealtimeMs) {
7185 if (mCameraTurnedOnTimer != null) {
7186 mCameraTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
7187 }
7188 }
7189
7190 public void noteResetCameraLocked(long elapsedRealtimeMs) {
7191 if (mCameraTurnedOnTimer != null) {
7192 mCameraTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
7193 }
7194 }
7195
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007196 public StopwatchTimer createForegroundActivityTimerLocked() {
7197 if (mForegroundActivityTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007198 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7199 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007200 }
7201 return mForegroundActivityTimer;
7202 }
7203
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007204 public StopwatchTimer createForegroundServiceTimerLocked() {
7205 if (mForegroundServiceTimer == null) {
7206 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7207 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase);
7208 }
7209 return mForegroundServiceTimer;
7210 }
7211
Bookatzc8c44962017-05-11 12:12:54 -07007212 public DualTimer createAggregatedPartialWakelockTimerLocked() {
7213 if (mAggregatedPartialWakelockTimer == null) {
7214 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
7215 AGGREGATED_WAKE_TYPE_PARTIAL, null,
7216 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase);
7217 }
7218 return mAggregatedPartialWakelockTimer;
7219 }
7220
Bookatz867c0d72017-03-07 18:23:42 -08007221 public DualTimer createBluetoothScanTimerLocked() {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007222 if (mBluetoothScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007223 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
7224 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
7225 mOnBatteryBackgroundTimeBase);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007226 }
7227 return mBluetoothScanTimer;
7228 }
7229
Bookatzb1f04f32017-05-19 13:57:32 -07007230 public DualTimer createBluetoothUnoptimizedScanTimerLocked() {
7231 if (mBluetoothUnoptimizedScanTimer == null) {
7232 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
7233 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
7234 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
7235 }
7236 return mBluetoothUnoptimizedScanTimer;
7237 }
7238
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00007239 public void noteBluetoothScanStartedLocked(long elapsedRealtimeMs,
7240 boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007241 createBluetoothScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatzb1f04f32017-05-19 13:57:32 -07007242 if (isUnoptimized) {
7243 createBluetoothUnoptimizedScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
7244 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007245 }
7246
Bookatz94c5a312017-07-11 16:49:17 -07007247 public void noteBluetoothScanStoppedLocked(long elapsedRealtimeMs, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007248 if (mBluetoothScanTimer != null) {
7249 mBluetoothScanTimer.stopRunningLocked(elapsedRealtimeMs);
7250 }
Bookatz94c5a312017-07-11 16:49:17 -07007251 if (isUnoptimized && mBluetoothUnoptimizedScanTimer != null) {
Bookatzb1f04f32017-05-19 13:57:32 -07007252 mBluetoothUnoptimizedScanTimer.stopRunningLocked(elapsedRealtimeMs);
7253 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007254 }
7255
7256 public void noteResetBluetoothScanLocked(long elapsedRealtimeMs) {
7257 if (mBluetoothScanTimer != null) {
7258 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
7259 }
Bookatzb1f04f32017-05-19 13:57:32 -07007260 if (mBluetoothUnoptimizedScanTimer != null) {
7261 mBluetoothUnoptimizedScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
7262 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007263 }
7264
Bookatz956f36bf2017-04-28 09:48:17 -07007265 public Counter createBluetoothScanResultCounterLocked() {
7266 if (mBluetoothScanResultCounter == null) {
7267 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase);
7268 }
7269 return mBluetoothScanResultCounter;
7270 }
7271
Bookatzb1f04f32017-05-19 13:57:32 -07007272 public Counter createBluetoothScanResultBgCounterLocked() {
7273 if (mBluetoothScanResultBgCounter == null) {
7274 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase);
7275 }
7276 return mBluetoothScanResultBgCounter;
7277 }
7278
Bookatz4ebc0642017-05-11 12:21:19 -07007279 public void noteBluetoothScanResultsLocked(int numNewResults) {
7280 createBluetoothScanResultCounterLocked().addAtomic(numNewResults);
Bookatzb1f04f32017-05-19 13:57:32 -07007281 // Uses background timebase, so the count will only be incremented if uid in background.
7282 createBluetoothScanResultBgCounterLocked().addAtomic(numNewResults);
Bookatz956f36bf2017-04-28 09:48:17 -07007283 }
7284
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007285 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007286 public void noteActivityResumedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007287 // We always start, since we want multiple foreground PIDs to nest
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007288 createForegroundActivityTimerLocked().startRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007289 }
7290
7291 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007292 public void noteActivityPausedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007293 if (mForegroundActivityTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007294 mForegroundActivityTimer.stopRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007295 }
7296 }
7297
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007298 public void noteForegroundServiceResumedLocked(long elapsedRealtimeMs) {
7299 createForegroundServiceTimerLocked().startRunningLocked(elapsedRealtimeMs);
7300 }
7301
7302 public void noteForegroundServicePausedLocked(long elapsedRealtimeMs) {
7303 if (mForegroundServiceTimer != null) {
7304 mForegroundServiceTimer.stopRunningLocked(elapsedRealtimeMs);
7305 }
7306 }
7307
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007308 public BatchTimer createVibratorOnTimerLocked() {
7309 if (mVibratorOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007310 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
7311 mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007312 }
7313 return mVibratorOnTimer;
7314 }
7315
7316 public void noteVibratorOnLocked(long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08007317 createVibratorOnTimerLocked().addDuration(mBsi, durationMillis);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007318 }
7319
7320 public void noteVibratorOffLocked() {
7321 if (mVibratorOnTimer != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007322 mVibratorOnTimer.abortLastDuration(mBsi);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007323 }
7324 }
7325
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007326 @Override
Mathew Inwoodaf972c82018-08-20 14:13:20 +01007327 @UnsupportedAppUsage
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007328 public long getWifiRunningTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007329 if (mWifiRunningTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007330 return 0;
7331 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007332 return mWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007333 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07007334
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007335 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007336 public long getFullWifiLockTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007337 if (mFullWifiLockTimer == null) {
7338 return 0;
7339 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007340 return mFullWifiLockTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07007341 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007342
7343 @Override
Mathew Inwoodaf972c82018-08-20 14:13:20 +01007344 @UnsupportedAppUsage
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007345 public long getWifiScanTime(long elapsedRealtimeUs, int which) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007346 if (mWifiScanTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007347 return 0;
7348 }
Bookatzaa4594a2017-03-24 12:39:56 -07007349 return mWifiScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07007350 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007351
7352 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07007353 public int getWifiScanCount(int which) {
7354 if (mWifiScanTimer == null) {
7355 return 0;
7356 }
Bookatzaa4594a2017-03-24 12:39:56 -07007357 return mWifiScanTimer.getCountLocked(which);
Bookatz867c0d72017-03-07 18:23:42 -08007358 }
7359
7360 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07007361 public Timer getWifiScanTimer() {
7362 return mWifiScanTimer;
7363 }
7364
7365 @Override
Bookatz867c0d72017-03-07 18:23:42 -08007366 public int getWifiScanBackgroundCount(int which) {
Bookatzaa4594a2017-03-24 12:39:56 -07007367 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007368 return 0;
7369 }
7370 return mWifiScanTimer.getSubTimer().getCountLocked(which);
7371 }
7372
7373 @Override
7374 public long getWifiScanActualTime(final long elapsedRealtimeUs) {
7375 if (mWifiScanTimer == null) {
7376 return 0;
7377 }
7378 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
Bookatzaa4594a2017-03-24 12:39:56 -07007379 return mWifiScanTimer.getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Bookatz867c0d72017-03-07 18:23:42 -08007380 }
7381
7382 @Override
7383 public long getWifiScanBackgroundTime(final long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07007384 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007385 return 0;
7386 }
7387 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
7388 return mWifiScanTimer.getSubTimer().getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Dianne Hackborn62793e42015-03-09 11:15:41 -07007389 }
7390
7391 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07007392 public Timer getWifiScanBackgroundTimer() {
7393 if (mWifiScanTimer == null) {
7394 return null;
7395 }
7396 return mWifiScanTimer.getSubTimer();
7397 }
7398
7399 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007400 public long getWifiBatchedScanTime(int csphBin, long elapsedRealtimeUs, int which) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007401 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
7402 if (mWifiBatchedScanTimer[csphBin] == null) {
7403 return 0;
7404 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007405 return mWifiBatchedScanTimer[csphBin].getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007406 }
7407
7408 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07007409 public int getWifiBatchedScanCount(int csphBin, int which) {
7410 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
7411 if (mWifiBatchedScanTimer[csphBin] == null) {
7412 return 0;
7413 }
7414 return mWifiBatchedScanTimer[csphBin].getCountLocked(which);
7415 }
7416
7417 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007418 public long getWifiMulticastTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007419 if (mWifiMulticastTimer == null) {
7420 return 0;
7421 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007422 return mWifiMulticastTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007423 }
7424
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007425 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007426 public Timer getAudioTurnedOnTimer() {
7427 return mAudioTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007428 }
7429
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007430 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007431 public Timer getVideoTurnedOnTimer() {
7432 return mVideoTurnedOnTimer;
7433 }
7434
7435 @Override
7436 public Timer getFlashlightTurnedOnTimer() {
7437 return mFlashlightTurnedOnTimer;
7438 }
7439
7440 @Override
7441 public Timer getCameraTurnedOnTimer() {
7442 return mCameraTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007443 }
7444
Dianne Hackborn617f8772009-03-31 15:04:46 -07007445 @Override
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007446 public Timer getForegroundActivityTimer() {
7447 return mForegroundActivityTimer;
7448 }
7449
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007450 @Override
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007451 public Timer getForegroundServiceTimer() {
7452 return mForegroundServiceTimer;
7453 }
7454
7455 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007456 public Timer getBluetoothScanTimer() {
Bookatzaa4594a2017-03-24 12:39:56 -07007457 return mBluetoothScanTimer;
Bookatz867c0d72017-03-07 18:23:42 -08007458 }
7459
7460 @Override
7461 public Timer getBluetoothScanBackgroundTimer() {
7462 if (mBluetoothScanTimer == null) {
7463 return null;
7464 }
7465 return mBluetoothScanTimer.getSubTimer();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007466 }
7467
Bookatz956f36bf2017-04-28 09:48:17 -07007468 @Override
Bookatzb1f04f32017-05-19 13:57:32 -07007469 public Timer getBluetoothUnoptimizedScanTimer() {
7470 return mBluetoothUnoptimizedScanTimer;
7471 }
7472
7473 @Override
7474 public Timer getBluetoothUnoptimizedScanBackgroundTimer() {
7475 if (mBluetoothUnoptimizedScanTimer == null) {
7476 return null;
7477 }
7478 return mBluetoothUnoptimizedScanTimer.getSubTimer();
7479 }
7480
7481 @Override
Bookatz956f36bf2017-04-28 09:48:17 -07007482 public Counter getBluetoothScanResultCounter() {
7483 return mBluetoothScanResultCounter;
7484 }
7485
Bookatzb1f04f32017-05-19 13:57:32 -07007486 @Override
7487 public Counter getBluetoothScanResultBgCounter() {
7488 return mBluetoothScanResultBgCounter;
7489 }
7490
Dianne Hackborn61659e52014-07-09 16:13:01 -07007491 void makeProcessState(int i, Parcel in) {
7492 if (i < 0 || i >= NUM_PROCESS_STATE) return;
7493
Hui Yu8e88e952018-07-23 17:59:59 -07007494 detachIfNotNull(mProcessStateTimer[i]);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007495 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007496 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
7497 mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007498 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08007499 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
7500 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007501 }
7502 }
7503
7504 @Override
7505 public long getProcessStateTime(int state, long elapsedRealtimeUs, int which) {
7506 if (state < 0 || state >= NUM_PROCESS_STATE) return 0;
7507 if (mProcessStateTimer[state] == null) {
7508 return 0;
7509 }
7510 return mProcessStateTimer[state].getTotalTimeLocked(elapsedRealtimeUs, which);
7511 }
7512
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007513 @Override
Joe Onorato713fec82016-03-04 10:34:02 -08007514 public Timer getProcessStateTimer(int state) {
7515 if (state < 0 || state >= NUM_PROCESS_STATE) return null;
7516 return mProcessStateTimer[state];
7517 }
7518
7519 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007520 public Timer getVibratorOnTimer() {
7521 return mVibratorOnTimer;
7522 }
7523
7524 @Override
Dianne Hackborn617f8772009-03-31 15:04:46 -07007525 public void noteUserActivityLocked(int type) {
7526 if (mUserActivityCounters == null) {
7527 initUserActivityLocked();
7528 }
Jeff Browndf693de2012-07-27 12:03:38 -07007529 if (type >= 0 && type < NUM_USER_ACTIVITY_TYPES) {
7530 mUserActivityCounters[type].stepAtomic();
7531 } else {
7532 Slog.w(TAG, "Unknown user activity type " + type + " was specified.",
7533 new Throwable());
7534 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07007535 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007536
Dianne Hackborn617f8772009-03-31 15:04:46 -07007537 @Override
7538 public boolean hasUserActivity() {
7539 return mUserActivityCounters != null;
7540 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007541
Dianne Hackborn617f8772009-03-31 15:04:46 -07007542 @Override
7543 public int getUserActivityCount(int type, int which) {
7544 if (mUserActivityCounters == null) {
7545 return 0;
7546 }
Evan Millarc64edde2009-04-18 12:26:32 -07007547 return mUserActivityCounters[type].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007548 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007549
Robert Greenwalta029ea12013-09-25 16:38:12 -07007550 void makeWifiBatchedScanBin(int i, Parcel in) {
7551 if (i < 0 || i >= NUM_WIFI_BATCHED_SCAN_BINS) return;
7552
Joe Onoratoabded112016-02-08 16:49:39 -08007553 ArrayList<StopwatchTimer> collected = mBsi.mWifiBatchedScanTimers.get(i);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007554 if (collected == null) {
7555 collected = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08007556 mBsi.mWifiBatchedScanTimers.put(i, collected);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007557 }
Hui Yu8e88e952018-07-23 17:59:59 -07007558 detachIfNotNull(mWifiBatchedScanTimer[i]);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007559 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007560 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
7561 collected, mBsi.mOnBatteryTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007562 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08007563 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
7564 collected, mBsi.mOnBatteryTimeBase, in);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007565 }
7566 }
7567
7568
Dianne Hackborn617f8772009-03-31 15:04:46 -07007569 void initUserActivityLocked() {
Hui Yu10571e02018-08-06 13:12:40 -07007570 detachIfNotNull(mUserActivityCounters);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007571 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
7572 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007573 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007574 }
7575 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007576
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007577 void noteNetworkActivityLocked(int type, long deltaBytes, long deltaPackets) {
7578 if (mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007579 initNetworkActivityLocked();
7580 }
7581 if (type >= 0 && type < NUM_NETWORK_ACTIVITY_TYPES) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007582 mNetworkByteActivityCounters[type].addCountLocked(deltaBytes);
7583 mNetworkPacketActivityCounters[type].addCountLocked(deltaPackets);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007584 } else {
7585 Slog.w(TAG, "Unknown network activity type " + type + " was specified.",
7586 new Throwable());
7587 }
7588 }
7589
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007590 void noteMobileRadioActiveTimeLocked(long batteryUptime) {
7591 if (mNetworkByteActivityCounters == null) {
7592 initNetworkActivityLocked();
7593 }
7594 mMobileRadioActiveTime.addCountLocked(batteryUptime);
7595 mMobileRadioActiveCount.addCountLocked(1);
7596 }
7597
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007598 @Override
7599 public boolean hasNetworkActivity() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007600 return mNetworkByteActivityCounters != null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007601 }
7602
7603 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007604 public long getNetworkActivityBytes(int type, int which) {
7605 if (mNetworkByteActivityCounters != null && type >= 0
7606 && type < mNetworkByteActivityCounters.length) {
7607 return mNetworkByteActivityCounters[type].getCountLocked(which);
7608 } else {
7609 return 0;
7610 }
7611 }
7612
7613 @Override
7614 public long getNetworkActivityPackets(int type, int which) {
7615 if (mNetworkPacketActivityCounters != null && type >= 0
7616 && type < mNetworkPacketActivityCounters.length) {
7617 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007618 } else {
7619 return 0;
7620 }
7621 }
7622
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007623 @Override
7624 public long getMobileRadioActiveTime(int which) {
7625 return mMobileRadioActiveTime != null
7626 ? mMobileRadioActiveTime.getCountLocked(which) : 0;
7627 }
7628
7629 @Override
7630 public int getMobileRadioActiveCount(int which) {
7631 return mMobileRadioActiveCount != null
7632 ? (int)mMobileRadioActiveCount.getCountLocked(which) : 0;
7633 }
7634
Adam Lesinskie08af192015-03-25 16:42:59 -07007635 @Override
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007636 public long getUserCpuTimeUs(int which) {
7637 return mUserCpuTime.getCountLocked(which);
7638 }
7639
7640 @Override
7641 public long getSystemCpuTimeUs(int which) {
7642 return mSystemCpuTime.getCountLocked(which);
7643 }
7644
7645 @Override
Adam Lesinski6832f392015-09-05 18:05:40 -07007646 public long getTimeAtCpuSpeed(int cluster, int step, int which) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07007647 if (mCpuClusterSpeedTimesUs != null) {
7648 if (cluster >= 0 && cluster < mCpuClusterSpeedTimesUs.length) {
7649 final LongSamplingCounter[] cpuSpeedTimesUs = mCpuClusterSpeedTimesUs[cluster];
7650 if (cpuSpeedTimesUs != null) {
7651 if (step >= 0 && step < cpuSpeedTimesUs.length) {
7652 final LongSamplingCounter c = cpuSpeedTimesUs[step];
Adam Lesinski6832f392015-09-05 18:05:40 -07007653 if (c != null) {
7654 return c.getCountLocked(which);
7655 }
7656 }
7657 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007658 }
7659 }
7660 return 0;
7661 }
7662
Adam Lesinski5f056f62016-07-14 16:56:08 -07007663 public void noteMobileRadioApWakeupLocked() {
7664 if (mMobileRadioApWakeupCount == null) {
7665 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7666 }
7667 mMobileRadioApWakeupCount.addCountLocked(1);
7668 }
7669
7670 @Override
7671 public long getMobileRadioApWakeupCount(int which) {
7672 if (mMobileRadioApWakeupCount != null) {
7673 return mMobileRadioApWakeupCount.getCountLocked(which);
7674 }
7675 return 0;
7676 }
7677
7678 public void noteWifiRadioApWakeupLocked() {
7679 if (mWifiRadioApWakeupCount == null) {
7680 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7681 }
7682 mWifiRadioApWakeupCount.addCountLocked(1);
7683 }
7684
7685 @Override
7686 public long getWifiRadioApWakeupCount(int which) {
7687 if (mWifiRadioApWakeupCount != null) {
7688 return mWifiRadioApWakeupCount.getCountLocked(which);
7689 }
7690 return 0;
7691 }
7692
Amith Yamasani977e11f2018-02-16 11:29:54 -08007693 @Override
7694 public void getDeferredJobsCheckinLineLocked(StringBuilder sb, int which) {
7695 sb.setLength(0);
7696 final int deferredEventCount = mJobsDeferredEventCount.getCountLocked(which);
7697 if (deferredEventCount == 0) {
7698 return;
7699 }
7700 final int deferredCount = mJobsDeferredCount.getCountLocked(which);
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007701 final long totalLatency = mJobsFreshnessTimeMs.getCountLocked(which);
Amith Yamasani977e11f2018-02-16 11:29:54 -08007702 sb.append(deferredEventCount); sb.append(',');
7703 sb.append(deferredCount); sb.append(',');
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007704 sb.append(totalLatency);
Amith Yamasani977e11f2018-02-16 11:29:54 -08007705 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
7706 if (mJobsFreshnessBuckets[i] == null) {
7707 sb.append(",0");
7708 } else {
7709 sb.append(",");
7710 sb.append(mJobsFreshnessBuckets[i].getCountLocked(which));
7711 }
7712 }
7713 }
7714
7715 @Override
7716 public void getDeferredJobsLineLocked(StringBuilder sb, int which) {
7717 sb.setLength(0);
7718 final int deferredEventCount = mJobsDeferredEventCount.getCountLocked(which);
7719 if (deferredEventCount == 0) {
7720 return;
7721 }
7722 final int deferredCount = mJobsDeferredCount.getCountLocked(which);
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007723 final long totalLatency = mJobsFreshnessTimeMs.getCountLocked(which);
Amith Yamasani977e11f2018-02-16 11:29:54 -08007724 sb.append("times="); sb.append(deferredEventCount); sb.append(", ");
7725 sb.append("count="); sb.append(deferredCount); sb.append(", ");
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007726 sb.append("totalLatencyMs="); sb.append(totalLatency); sb.append(", ");
Amith Yamasani977e11f2018-02-16 11:29:54 -08007727 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
7728 sb.append("<"); sb.append(JOB_FRESHNESS_BUCKETS[i]); sb.append("ms=");
7729 if (mJobsFreshnessBuckets[i] == null) {
7730 sb.append("0");
7731 } else {
7732 sb.append(mJobsFreshnessBuckets[i].getCountLocked(which));
7733 }
7734 sb.append(" ");
7735 }
7736 }
7737
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007738 void initNetworkActivityLocked() {
Hui Yu8e88e952018-07-23 17:59:59 -07007739 detachIfNotNull(mNetworkByteActivityCounters);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007740 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Hui Yu8e88e952018-07-23 17:59:59 -07007741 detachIfNotNull(mNetworkPacketActivityCounters);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007742 mNetworkPacketActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007743 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007744 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7745 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007746 }
Hui Yu8e88e952018-07-23 17:59:59 -07007747 detachIfNotNull(mMobileRadioActiveTime);
Joe Onoratoabded112016-02-08 16:49:39 -08007748 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Hui Yu8e88e952018-07-23 17:59:59 -07007749 detachIfNotNull(mMobileRadioActiveCount);
Joe Onoratoabded112016-02-08 16:49:39 -08007750 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007751 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07007752
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007753 /**
7754 * Clear all stats for this uid. Returns true if the uid is completely
7755 * inactive so can be dropped.
7756 */
Adam Lesinski5f212c82017-03-13 12:25:13 -07007757 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
Bookatz993a0be2017-07-21 09:03:23 -07007758 public boolean reset(long uptime, long realtime) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007759 boolean active = false;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007760
Bookatz993a0be2017-07-21 09:03:23 -07007761 mOnBatteryBackgroundTimeBase.init(uptime, realtime);
7762 mOnBatteryScreenOffBackgroundTimeBase.init(uptime, realtime);
7763
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007764 if (mWifiRunningTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007765 active |= !mWifiRunningTimer.reset(false);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007766 active |= mWifiRunning;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007767 }
7768 if (mFullWifiLockTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007769 active |= !mFullWifiLockTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007770 active |= mFullWifiLockOut;
7771 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07007772 if (mWifiScanTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007773 active |= !mWifiScanTimer.reset(false);
Nick Pelly6ccaa542012-06-15 15:22:47 -07007774 active |= mWifiScanStarted;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007775 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07007776 if (mWifiBatchedScanTimer != null) {
7777 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
7778 if (mWifiBatchedScanTimer[i] != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007779 active |= !mWifiBatchedScanTimer[i].reset(false);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007780 }
7781 }
7782 active |= (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED);
7783 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007784 if (mWifiMulticastTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007785 active |= !mWifiMulticastTimer.reset(false);
Ahmed ElArabawy6f1754e2017-11-28 15:50:32 -08007786 active |= (mWifiMulticastWakelockCount > 0);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007787 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007788
Hui Yu8e88e952018-07-23 17:59:59 -07007789 active |= !resetIfNotNull(mAudioTurnedOnTimer, false);
7790 active |= !resetIfNotNull(mVideoTurnedOnTimer, false);
7791 active |= !resetIfNotNull(mFlashlightTurnedOnTimer, false);
7792 active |= !resetIfNotNull(mCameraTurnedOnTimer, false);
7793 active |= !resetIfNotNull(mForegroundActivityTimer, false);
7794 active |= !resetIfNotNull(mForegroundServiceTimer, false);
7795 active |= !resetIfNotNull(mAggregatedPartialWakelockTimer, false);
7796 active |= !resetIfNotNull(mBluetoothScanTimer, false);
7797 active |= !resetIfNotNull(mBluetoothUnoptimizedScanTimer, false);
7798
7799 resetIfNotNull(mBluetoothScanResultCounter, false);
7800 resetIfNotNull(mBluetoothScanResultBgCounter, false);
Adam Lesinski5f056f62016-07-14 16:56:08 -07007801
Dianne Hackborn61659e52014-07-09 16:13:01 -07007802 if (mProcessStateTimer != null) {
7803 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
Hui Yu8e88e952018-07-23 17:59:59 -07007804 active |= !resetIfNotNull(mProcessStateTimer[i], false);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007805 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08007806 active |= (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007807 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007808 if (mVibratorOnTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007809 if (mVibratorOnTimer.reset(false)) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007810 mVibratorOnTimer.detach();
7811 mVibratorOnTimer = null;
7812 } else {
7813 active = true;
7814 }
7815 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007816
Hui Yu8e88e952018-07-23 17:59:59 -07007817 resetIfNotNull(mUserActivityCounters, false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007818
Hui Yu8e88e952018-07-23 17:59:59 -07007819 resetIfNotNull(mNetworkByteActivityCounters, false);
7820 resetIfNotNull(mNetworkPacketActivityCounters, false);
7821 resetIfNotNull(mMobileRadioActiveTime, false);
7822 resetIfNotNull(mMobileRadioActiveCount, false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007823
Hui Yu8e88e952018-07-23 17:59:59 -07007824 resetIfNotNull(mWifiControllerActivity, false);
7825 resetIfNotNull(mBluetoothControllerActivity, false);
7826 resetIfNotNull(mModemControllerActivity, false);
Adam Lesinskie08af192015-03-25 16:42:59 -07007827
Hui Yu8e88e952018-07-23 17:59:59 -07007828 resetIfNotNull(mUserCpuTime, false);
7829 resetIfNotNull(mSystemCpuTime, false);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007830
Hui Yu8e88e952018-07-23 17:59:59 -07007831 resetIfNotNull(mCpuClusterSpeedTimesUs, false);
Adam Lesinskie08af192015-03-25 16:42:59 -07007832
Hui Yu8e88e952018-07-23 17:59:59 -07007833 resetIfNotNull(mCpuFreqTimeMs, false);
7834 resetIfNotNull(mScreenOffCpuFreqTimeMs, false);
Adam Lesinski6832f392015-09-05 18:05:40 -07007835
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007836
Hui Yu8e88e952018-07-23 17:59:59 -07007837 resetIfNotNull(mCpuActiveTimeMs, false);
7838 resetIfNotNull(mCpuClusterTimesMs, false);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007839
Hui Yu8e88e952018-07-23 17:59:59 -07007840 resetIfNotNull(mProcStateTimeMs, false);
Mike Ma3d422c32017-10-25 11:08:57 -07007841
Hui Yu8e88e952018-07-23 17:59:59 -07007842 resetIfNotNull(mProcStateScreenOffTimeMs, false);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007843
Hui Yu8e88e952018-07-23 17:59:59 -07007844 resetIfNotNull(mMobileRadioApWakeupCount, false);
7845
7846 resetIfNotNull(mWifiRadioApWakeupCount, false);
7847
Adam Lesinski5f056f62016-07-14 16:56:08 -07007848
Dianne Hackbornd953c532014-08-16 18:17:38 -07007849 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
7850 for (int iw=wakeStats.size()-1; iw>=0; iw--) {
7851 Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007852 if (wl.reset()) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007853 wakeStats.removeAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007854 } else {
7855 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007856 }
7857 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07007858 mWakelockStats.cleanup();
Bookatz2bffb5b2017-04-13 11:59:33 -07007859 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07007860 for (int is=syncStats.size()-1; is>=0; is--) {
Bookatz2bffb5b2017-04-13 11:59:33 -07007861 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007862 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007863 syncStats.removeAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007864 timer.detach();
7865 } else {
7866 active = true;
7867 }
7868 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07007869 mSyncStats.cleanup();
Bookatzaa4594a2017-03-24 12:39:56 -07007870 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07007871 for (int ij=jobStats.size()-1; ij>=0; ij--) {
Bookatzaa4594a2017-03-24 12:39:56 -07007872 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007873 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007874 jobStats.removeAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007875 timer.detach();
7876 } else {
7877 active = true;
7878 }
7879 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07007880 mJobStats.cleanup();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07007881 mJobCompletions.clear();
Amith Yamasani977e11f2018-02-16 11:29:54 -08007882
Hui Yu8e88e952018-07-23 17:59:59 -07007883 resetIfNotNull(mJobsDeferredEventCount, false);
7884 resetIfNotNull(mJobsDeferredCount, false);
7885 resetIfNotNull(mJobsFreshnessTimeMs, false);
7886 resetIfNotNull(mJobsFreshnessBuckets, false);
Amith Yamasani977e11f2018-02-16 11:29:54 -08007887
Hui Yu8e88e952018-07-23 17:59:59 -07007888 for (int ise = mSensorStats.size() - 1; ise >= 0; ise--) {
Dianne Hackborn61659e52014-07-09 16:13:01 -07007889 Sensor s = mSensorStats.valueAt(ise);
7890 if (s.reset()) {
7891 mSensorStats.removeAt(ise);
7892 } else {
7893 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007894 }
7895 }
Amith Yamasani977e11f2018-02-16 11:29:54 -08007896
Hui Yu8e88e952018-07-23 17:59:59 -07007897 for (int ip = mProcessStats.size() - 1; ip >= 0; ip--) {
Dianne Hackborn61659e52014-07-09 16:13:01 -07007898 Proc proc = mProcessStats.valueAt(ip);
Dianne Hackborna8d10942015-11-19 17:55:19 -08007899 proc.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007900 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08007901 mProcessStats.clear();
Hui Yu8e88e952018-07-23 17:59:59 -07007902
7903 for (int i = mPids.size() - 1; i >= 0; i--) {
7904 Pid pid = mPids.valueAt(i);
7905 if (pid.mWakeNesting > 0) {
7906 active = true;
7907 } else {
7908 mPids.removeAt(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007909 }
7910 }
Hui Yu8e88e952018-07-23 17:59:59 -07007911
7912
7913 for(int i = mPackageStats.size() - 1; i >= 0; i--) {
7914 Pkg p = mPackageStats.valueAt(i);
7915 p.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007916 }
Hui Yu8e88e952018-07-23 17:59:59 -07007917 mPackageStats.clear();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007918
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08007919 mLastStepUserTime = mLastStepSystemTime = 0;
7920 mCurStepUserTime = mCurStepSystemTime = 0;
7921
Hui Yu8e88e952018-07-23 17:59:59 -07007922 return !active;
7923 }
Adam Lesinskie08af192015-03-25 16:42:59 -07007924
Hui Yu8e88e952018-07-23 17:59:59 -07007925 /**
7926 * This method MUST be called whenever the Uid object is destructed, otherwise it is a
7927 * memory leak in {@link TimeBase#mObservers} list.
7928 * Typically the Uid object is destructed when it is removed from
7929 * {@link BatteryStatsImpl#mUidStats}
7930 */
7931 void detachFromTimeBase() {
7932 detachIfNotNull(mWifiRunningTimer);
7933 detachIfNotNull(mFullWifiLockTimer);
7934 detachIfNotNull(mWifiScanTimer);
7935 detachIfNotNull(mWifiBatchedScanTimer);
7936 detachIfNotNull(mWifiMulticastTimer);
7937 detachIfNotNull(mAudioTurnedOnTimer);
7938 detachIfNotNull(mVideoTurnedOnTimer);
7939 detachIfNotNull(mFlashlightTurnedOnTimer);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007940
Hui Yu8e88e952018-07-23 17:59:59 -07007941 detachIfNotNull(mCameraTurnedOnTimer);
7942 detachIfNotNull(mForegroundActivityTimer);
7943 detachIfNotNull(mForegroundServiceTimer);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007944
Hui Yu8e88e952018-07-23 17:59:59 -07007945 detachIfNotNull(mAggregatedPartialWakelockTimer);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007946
Hui Yu8e88e952018-07-23 17:59:59 -07007947 detachIfNotNull(mBluetoothScanTimer);
7948 detachIfNotNull(mBluetoothUnoptimizedScanTimer);
7949 detachIfNotNull(mBluetoothScanResultCounter);
7950 detachIfNotNull(mBluetoothScanResultBgCounter);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007951
Hui Yu8e88e952018-07-23 17:59:59 -07007952 detachIfNotNull(mProcessStateTimer);
Adam Lesinski6832f392015-09-05 18:05:40 -07007953
Hui Yu8e88e952018-07-23 17:59:59 -07007954 detachIfNotNull(mVibratorOnTimer);
Adam Lesinski5f056f62016-07-14 16:56:08 -07007955
Hui Yu8e88e952018-07-23 17:59:59 -07007956 detachIfNotNull(mUserActivityCounters);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007957
Hui Yu8e88e952018-07-23 17:59:59 -07007958 detachIfNotNull(mNetworkByteActivityCounters);
7959 detachIfNotNull(mNetworkPacketActivityCounters);
7960
7961 detachIfNotNull(mMobileRadioActiveTime);
7962 detachIfNotNull(mMobileRadioActiveCount);
7963 detachIfNotNull(mMobileRadioApWakeupCount);
7964 detachIfNotNull(mWifiRadioApWakeupCount);
7965
7966 detachIfNotNull(mWifiControllerActivity);
7967 detachIfNotNull(mBluetoothControllerActivity);
7968 detachIfNotNull(mModemControllerActivity);
7969
7970 mPids.clear();
7971
7972 detachIfNotNull(mUserCpuTime);
7973 detachIfNotNull(mSystemCpuTime);
7974
7975 detachIfNotNull(mCpuClusterSpeedTimesUs);
7976
7977 detachIfNotNull(mCpuActiveTimeMs);
7978 detachIfNotNull(mCpuFreqTimeMs);
7979
7980 detachIfNotNull(mScreenOffCpuFreqTimeMs);
7981
7982 detachIfNotNull(mCpuClusterTimesMs);
7983
7984 detachIfNotNull(mProcStateTimeMs);
7985
7986 detachIfNotNull(mProcStateScreenOffTimeMs);
7987
7988 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
7989 for (int iw = wakeStats.size() - 1; iw >= 0; iw--) {
7990 Wakelock wl = wakeStats.valueAt(iw);
7991 wl.detachFromTimeBase();
7992 }
7993 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
7994 for (int is = syncStats.size() - 1; is >= 0; is--) {
7995 DualTimer timer = syncStats.valueAt(is);
7996 detachIfNotNull(timer);
7997 }
7998 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
7999 for (int ij = jobStats.size() - 1; ij >= 0; ij--) {
8000 DualTimer timer = jobStats.valueAt(ij);
8001 detachIfNotNull(timer);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008002 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008003
Hui Yu8e88e952018-07-23 17:59:59 -07008004 detachIfNotNull(mJobsDeferredEventCount);
8005 detachIfNotNull(mJobsDeferredCount);
8006 detachIfNotNull(mJobsFreshnessTimeMs);
8007 detachIfNotNull(mJobsFreshnessBuckets);
8008
8009
8010 for (int ise = mSensorStats.size() - 1; ise >= 0; ise--) {
8011 Sensor s = mSensorStats.valueAt(ise);
8012 s.detachFromTimeBase();
8013 }
8014
8015 for (int ip= mProcessStats.size() - 1; ip >= 0; ip--) {
8016 Proc proc = mProcessStats.valueAt(ip);
8017 proc.detach();
8018 }
8019 mProcessStats.clear();
8020
8021 for(int i = mPackageStats.size() - 1; i >= 0; i--) {
8022 Pkg p = mPackageStats.valueAt(i);
8023 p.detach();
8024 }
8025 mPackageStats.clear();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008026 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008027
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008028 void writeJobCompletionsToParcelLocked(Parcel out) {
8029 int NJC = mJobCompletions.size();
8030 out.writeInt(NJC);
8031 for (int ijc=0; ijc<NJC; ijc++) {
8032 out.writeString(mJobCompletions.keyAt(ijc));
8033 SparseIntArray types = mJobCompletions.valueAt(ijc);
8034 int NT = types.size();
8035 out.writeInt(NT);
8036 for (int it=0; it<NT; it++) {
8037 out.writeInt(types.keyAt(it));
8038 out.writeInt(types.valueAt(it));
8039 }
8040 }
8041 }
8042
Bookatz867c0d72017-03-07 18:23:42 -08008043 void writeToParcelLocked(Parcel out, long uptimeUs, long elapsedRealtimeUs) {
8044 mOnBatteryBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatzc8c44962017-05-11 12:12:54 -07008045 mOnBatteryScreenOffBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08008046
Dianne Hackbornd953c532014-08-16 18:17:38 -07008047 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
8048 int NW = wakeStats.size();
Dianne Hackborn61659e52014-07-09 16:13:01 -07008049 out.writeInt(NW);
8050 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008051 out.writeString(wakeStats.keyAt(iw));
8052 Uid.Wakelock wakelock = wakeStats.valueAt(iw);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008053 wakelock.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008054 }
8055
Bookatz2bffb5b2017-04-13 11:59:33 -07008056 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008057 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008058 out.writeInt(NS);
8059 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008060 out.writeString(syncStats.keyAt(is));
Bookatz2bffb5b2017-04-13 11:59:33 -07008061 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008062 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
8063 }
8064
Bookatzaa4594a2017-03-24 12:39:56 -07008065 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008066 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008067 out.writeInt(NJ);
8068 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008069 out.writeString(jobStats.keyAt(ij));
Bookatzaa4594a2017-03-24 12:39:56 -07008070 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008071 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
8072 }
8073
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008074 writeJobCompletionsToParcelLocked(out);
8075
Amith Yamasani977e11f2018-02-16 11:29:54 -08008076 mJobsDeferredEventCount.writeToParcel(out);
8077 mJobsDeferredCount.writeToParcel(out);
8078 mJobsFreshnessTimeMs.writeToParcel(out);
8079 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
8080 Counter.writeCounterToParcel(out, mJobsFreshnessBuckets[i]);
8081 }
8082
Dianne Hackborn61659e52014-07-09 16:13:01 -07008083 int NSE = mSensorStats.size();
8084 out.writeInt(NSE);
8085 for (int ise=0; ise<NSE; ise++) {
8086 out.writeInt(mSensorStats.keyAt(ise));
8087 Uid.Sensor sensor = mSensorStats.valueAt(ise);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008088 sensor.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008089 }
8090
Dianne Hackborn61659e52014-07-09 16:13:01 -07008091 int NP = mProcessStats.size();
8092 out.writeInt(NP);
8093 for (int ip=0; ip<NP; ip++) {
8094 out.writeString(mProcessStats.keyAt(ip));
8095 Uid.Proc proc = mProcessStats.valueAt(ip);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008096 proc.writeToParcelLocked(out);
8097 }
8098
8099 out.writeInt(mPackageStats.size());
8100 for (Map.Entry<String, Uid.Pkg> pkgEntry : mPackageStats.entrySet()) {
8101 out.writeString(pkgEntry.getKey());
8102 Uid.Pkg pkg = pkgEntry.getValue();
8103 pkg.writeToParcelLocked(out);
8104 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008105
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008106 if (mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008107 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008108 mWifiRunningTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008109 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008110 out.writeInt(0);
8111 }
8112 if (mFullWifiLockTimer != null) {
8113 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008114 mFullWifiLockTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008115 } else {
8116 out.writeInt(0);
8117 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008118 if (mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008119 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008120 mWifiScanTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008121 } else {
8122 out.writeInt(0);
8123 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008124 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8125 if (mWifiBatchedScanTimer[i] != null) {
8126 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008127 mWifiBatchedScanTimer[i].writeToParcel(out, elapsedRealtimeUs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07008128 } else {
8129 out.writeInt(0);
8130 }
8131 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008132 if (mWifiMulticastTimer != null) {
8133 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008134 mWifiMulticastTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008135 } else {
8136 out.writeInt(0);
8137 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008138
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008139 if (mAudioTurnedOnTimer != null) {
8140 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008141 mAudioTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008142 } else {
8143 out.writeInt(0);
8144 }
8145 if (mVideoTurnedOnTimer != null) {
8146 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008147 mVideoTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008148 } else {
8149 out.writeInt(0);
8150 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008151 if (mFlashlightTurnedOnTimer != null) {
8152 out.writeInt(1);
8153 mFlashlightTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
8154 } else {
8155 out.writeInt(0);
8156 }
8157 if (mCameraTurnedOnTimer != null) {
8158 out.writeInt(1);
8159 mCameraTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
8160 } else {
8161 out.writeInt(0);
8162 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008163 if (mForegroundActivityTimer != null) {
8164 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008165 mForegroundActivityTimer.writeToParcel(out, elapsedRealtimeUs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008166 } else {
8167 out.writeInt(0);
8168 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008169 if (mForegroundServiceTimer != null) {
8170 out.writeInt(1);
8171 mForegroundServiceTimer.writeToParcel(out, elapsedRealtimeUs);
8172 } else {
8173 out.writeInt(0);
8174 }
Bookatzc8c44962017-05-11 12:12:54 -07008175 if (mAggregatedPartialWakelockTimer != null) {
8176 out.writeInt(1);
8177 mAggregatedPartialWakelockTimer.writeToParcel(out, elapsedRealtimeUs);
8178 } else {
8179 out.writeInt(0);
8180 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008181 if (mBluetoothScanTimer != null) {
8182 out.writeInt(1);
8183 mBluetoothScanTimer.writeToParcel(out, elapsedRealtimeUs);
8184 } else {
8185 out.writeInt(0);
8186 }
Bookatzb1f04f32017-05-19 13:57:32 -07008187 if (mBluetoothUnoptimizedScanTimer != null) {
8188 out.writeInt(1);
8189 mBluetoothUnoptimizedScanTimer.writeToParcel(out, elapsedRealtimeUs);
8190 } else {
8191 out.writeInt(0);
8192 }
Bookatz956f36bf2017-04-28 09:48:17 -07008193 if (mBluetoothScanResultCounter != null) {
8194 out.writeInt(1);
8195 mBluetoothScanResultCounter.writeToParcel(out);
8196 } else {
8197 out.writeInt(0);
8198 }
Bookatzb1f04f32017-05-19 13:57:32 -07008199 if (mBluetoothScanResultBgCounter != null) {
8200 out.writeInt(1);
8201 mBluetoothScanResultBgCounter.writeToParcel(out);
8202 } else {
8203 out.writeInt(0);
8204 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07008205 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8206 if (mProcessStateTimer[i] != null) {
8207 out.writeInt(1);
8208 mProcessStateTimer[i].writeToParcel(out, elapsedRealtimeUs);
8209 } else {
8210 out.writeInt(0);
8211 }
8212 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008213 if (mVibratorOnTimer != null) {
8214 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008215 mVibratorOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008216 } else {
8217 out.writeInt(0);
8218 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008219 if (mUserActivityCounters != null) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07008220 out.writeInt(1);
8221 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
8222 mUserActivityCounters[i].writeToParcel(out);
8223 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008224 } else {
8225 out.writeInt(0);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008226 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008227 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008228 out.writeInt(1);
8229 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008230 mNetworkByteActivityCounters[i].writeToParcel(out);
8231 mNetworkPacketActivityCounters[i].writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008232 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08008233 mMobileRadioActiveTime.writeToParcel(out);
8234 mMobileRadioActiveCount.writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008235 } else {
8236 out.writeInt(0);
8237 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008238
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008239 if (mWifiControllerActivity != null) {
8240 out.writeInt(1);
8241 mWifiControllerActivity.writeToParcel(out, 0);
8242 } else {
8243 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07008244 }
8245
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008246 if (mBluetoothControllerActivity != null) {
8247 out.writeInt(1);
8248 mBluetoothControllerActivity.writeToParcel(out, 0);
8249 } else {
8250 out.writeInt(0);
8251 }
8252
8253 if (mModemControllerActivity != null) {
8254 out.writeInt(1);
8255 mModemControllerActivity.writeToParcel(out, 0);
8256 } else {
8257 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07008258 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008259
8260 mUserCpuTime.writeToParcel(out);
8261 mSystemCpuTime.writeToParcel(out);
8262
Sudheer Shankaaf857412017-07-21 00:14:24 -07008263 if (mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008264 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -07008265 out.writeInt(mCpuClusterSpeedTimesUs.length);
8266 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008267 if (cpuSpeeds != null) {
8268 out.writeInt(1);
8269 out.writeInt(cpuSpeeds.length);
8270 for (LongSamplingCounter c : cpuSpeeds) {
8271 if (c != null) {
8272 out.writeInt(1);
8273 c.writeToParcel(out);
8274 } else {
8275 out.writeInt(0);
8276 }
8277 }
8278 } else {
8279 out.writeInt(0);
8280 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008281 }
Adam Lesinski6832f392015-09-05 18:05:40 -07008282 } else {
8283 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008284 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008285
Sudheer Shanka59f5c002017-05-15 10:57:15 -07008286 LongSamplingCounterArray.writeToParcel(out, mCpuFreqTimeMs);
8287 LongSamplingCounterArray.writeToParcel(out, mScreenOffCpuFreqTimeMs);
Mike Ma3d422c32017-10-25 11:08:57 -07008288
8289 mCpuActiveTimeMs.writeToParcel(out);
8290 mCpuClusterTimesMs.writeToParcel(out);
8291
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008292 if (mProcStateTimeMs != null) {
8293 out.writeInt(mProcStateTimeMs.length);
8294 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8295 LongSamplingCounterArray.writeToParcel(out, counters);
8296 }
8297 } else {
8298 out.writeInt(0);
8299 }
8300 if (mProcStateScreenOffTimeMs != null) {
8301 out.writeInt(mProcStateScreenOffTimeMs.length);
8302 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8303 LongSamplingCounterArray.writeToParcel(out, counters);
8304 }
8305 } else {
8306 out.writeInt(0);
8307 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008308
Adam Lesinski5f056f62016-07-14 16:56:08 -07008309 if (mMobileRadioApWakeupCount != null) {
8310 out.writeInt(1);
8311 mMobileRadioApWakeupCount.writeToParcel(out);
8312 } else {
8313 out.writeInt(0);
8314 }
8315
8316 if (mWifiRadioApWakeupCount != null) {
8317 out.writeInt(1);
8318 mWifiRadioApWakeupCount.writeToParcel(out);
8319 } else {
8320 out.writeInt(0);
8321 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008322 }
8323
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008324 void readJobCompletionsFromParcelLocked(Parcel in) {
8325 int numJobCompletions = in.readInt();
8326 mJobCompletions.clear();
8327 for (int j = 0; j < numJobCompletions; j++) {
8328 String jobName = in.readString();
8329 int numTypes = in.readInt();
8330 if (numTypes > 0) {
8331 SparseIntArray types = new SparseIntArray();
8332 for (int k = 0; k < numTypes; k++) {
8333 int type = in.readInt();
8334 int count = in.readInt();
8335 types.put(type, count);
8336 }
8337 mJobCompletions.put(jobName, types);
8338 }
8339 }
8340 }
8341
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008342 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase, Parcel in) {
Bookatz867c0d72017-03-07 18:23:42 -08008343 mOnBatteryBackgroundTimeBase.readFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -07008344 mOnBatteryScreenOffBackgroundTimeBase.readFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -08008345
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008346 int numWakelocks = in.readInt();
8347 mWakelockStats.clear();
8348 for (int j = 0; j < numWakelocks; j++) {
8349 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008350 Uid.Wakelock wakelock = new Wakelock(mBsi, this);
Bookatz5b5ec322017-05-26 09:40:38 -07008351 wakelock.readFromParcelLocked(
8352 timeBase, screenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase, in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07008353 mWakelockStats.add(wakelockName, wakelock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008354 }
8355
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008356 int numSyncs = in.readInt();
8357 mSyncStats.clear();
8358 for (int j = 0; j < numSyncs; j++) {
8359 String syncName = in.readString();
8360 if (in.readInt() != 0) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008361 mSyncStats.add(syncName, new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
8362 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008363 }
8364 }
8365
8366 int numJobs = in.readInt();
8367 mJobStats.clear();
8368 for (int j = 0; j < numJobs; j++) {
8369 String jobName = in.readString();
8370 if (in.readInt() != 0) {
Bookatzaa4594a2017-03-24 12:39:56 -07008371 mJobStats.add(jobName, new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
8372 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008373 }
8374 }
8375
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008376 readJobCompletionsFromParcelLocked(in);
8377
Amith Yamasani977e11f2018-02-16 11:29:54 -08008378 mJobsDeferredEventCount = new Counter(mBsi.mOnBatteryTimeBase, in);
8379 mJobsDeferredCount = new Counter(mBsi.mOnBatteryTimeBase, in);
8380 mJobsFreshnessTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8381 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
8382 mJobsFreshnessBuckets[i] = Counter.readCounterFromParcel(mBsi.mOnBatteryTimeBase,
8383 in);
8384 }
8385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008386 int numSensors = in.readInt();
8387 mSensorStats.clear();
8388 for (int k = 0; k < numSensors; k++) {
8389 int sensorNumber = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008390 Uid.Sensor sensor = new Sensor(mBsi, this, sensorNumber);
Bookatz867c0d72017-03-07 18:23:42 -08008391 sensor.readFromParcelLocked(mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
8392 in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008393 mSensorStats.put(sensorNumber, sensor);
8394 }
8395
8396 int numProcs = in.readInt();
8397 mProcessStats.clear();
8398 for (int k = 0; k < numProcs; k++) {
8399 String processName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008400 Uid.Proc proc = new Proc(mBsi, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008401 proc.readFromParcelLocked(in);
8402 mProcessStats.put(processName, proc);
8403 }
8404
8405 int numPkgs = in.readInt();
8406 mPackageStats.clear();
8407 for (int l = 0; l < numPkgs; l++) {
8408 String packageName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008409 Uid.Pkg pkg = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008410 pkg.readFromParcelLocked(in);
8411 mPackageStats.put(packageName, pkg);
8412 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008413
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008414 mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008415 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008416 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
8417 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008418 } else {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008419 mWifiRunningTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008420 }
8421 mFullWifiLockOut = false;
8422 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008423 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
8424 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008425 } else {
8426 mFullWifiLockTimer = null;
8427 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008428 mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008429 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08008430 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
8431 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
8432 in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008433 } else {
Nick Pelly6ccaa542012-06-15 15:22:47 -07008434 mWifiScanTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008435 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008436 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
8437 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8438 if (in.readInt() != 0) {
8439 makeWifiBatchedScanBin(i, in);
8440 } else {
8441 mWifiBatchedScanTimer[i] = null;
8442 }
8443 }
Ahmed ElArabawy6f1754e2017-11-28 15:50:32 -08008444 mWifiMulticastWakelockCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008445 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008446 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_MULTICAST_ENABLED,
8447 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008448 } else {
8449 mWifiMulticastTimer = null;
8450 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008451 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008452 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
8453 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008454 } else {
8455 mAudioTurnedOnTimer = null;
8456 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008457 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008458 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
8459 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008460 } else {
8461 mVideoTurnedOnTimer = null;
8462 }
8463 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008464 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8465 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008466 } else {
8467 mFlashlightTurnedOnTimer = null;
8468 }
8469 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008470 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
8471 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008472 } else {
8473 mCameraTurnedOnTimer = null;
8474 }
8475 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008476 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8477 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008478 } else {
8479 mForegroundActivityTimer = null;
8480 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008481 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008482 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8483 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase, in);
8484 } else {
8485 mForegroundServiceTimer = null;
8486 }
8487 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -07008488 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
8489 AGGREGATED_WAKE_TYPE_PARTIAL, null,
8490 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase,
8491 in);
8492 } else {
8493 mAggregatedPartialWakelockTimer = null;
8494 }
8495 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08008496 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
8497 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
8498 mOnBatteryBackgroundTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008499 } else {
8500 mBluetoothScanTimer = null;
8501 }
Bookatz956f36bf2017-04-28 09:48:17 -07008502 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -07008503 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
8504 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
8505 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in);
8506 } else {
8507 mBluetoothUnoptimizedScanTimer = null;
8508 }
8509 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -07008510 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase, in);
8511 } else {
8512 mBluetoothScanResultCounter = null;
8513 }
Bookatzb1f04f32017-05-19 13:57:32 -07008514 if (in.readInt() != 0) {
8515 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase, in);
8516 } else {
8517 mBluetoothScanResultBgCounter = null;
8518 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08008519 mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07008520 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8521 if (in.readInt() != 0) {
8522 makeProcessState(i, in);
8523 } else {
8524 mProcessStateTimer[i] = null;
8525 }
8526 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008527 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008528 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
8529 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008530 } else {
8531 mVibratorOnTimer = null;
8532 }
8533 if (in.readInt() != 0) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07008534 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
8535 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08008536 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008537 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008538 } else {
8539 mUserActivityCounters = null;
Dianne Hackborn617f8772009-03-31 15:04:46 -07008540 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008541 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008542 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
8543 mNetworkPacketActivityCounters
8544 = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008545 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008546 mNetworkByteActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08008547 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008548 mNetworkPacketActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08008549 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008550 }
Joe Onoratoabded112016-02-08 16:49:39 -08008551 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8552 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008553 } else {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008554 mNetworkByteActivityCounters = null;
8555 mNetworkPacketActivityCounters = null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008556 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008557
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008558 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008559 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008560 NUM_WIFI_TX_LEVELS, in);
8561 } else {
8562 mWifiControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07008563 }
8564
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008565 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008566 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008567 NUM_BT_TX_LEVELS, in);
8568 } else {
8569 mBluetoothControllerActivity = null;
8570 }
8571
8572 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008573 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008574 ModemActivityInfo.TX_POWER_LEVELS, in);
8575 } else {
8576 mModemControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07008577 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008578
Joe Onoratoabded112016-02-08 16:49:39 -08008579 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8580 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008581
Adam Lesinski6832f392015-09-05 18:05:40 -07008582 if (in.readInt() != 0) {
8583 int numCpuClusters = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008584 if (mBsi.mPowerProfile != null && mBsi.mPowerProfile.getNumCpuClusters() != numCpuClusters) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008585 throw new ParcelFormatException("Incompatible number of cpu clusters");
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008586 }
Adam Lesinski6832f392015-09-05 18:05:40 -07008587
Sudheer Shankaaf857412017-07-21 00:14:24 -07008588 mCpuClusterSpeedTimesUs = new LongSamplingCounter[numCpuClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -07008589 for (int cluster = 0; cluster < numCpuClusters; cluster++) {
8590 if (in.readInt() != 0) {
8591 int numSpeeds = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008592 if (mBsi.mPowerProfile != null &&
8593 mBsi.mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != numSpeeds) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008594 throw new ParcelFormatException("Incompatible number of cpu speeds");
8595 }
8596
8597 final LongSamplingCounter[] cpuSpeeds = new LongSamplingCounter[numSpeeds];
Sudheer Shankaaf857412017-07-21 00:14:24 -07008598 mCpuClusterSpeedTimesUs[cluster] = cpuSpeeds;
Adam Lesinski6832f392015-09-05 18:05:40 -07008599 for (int speed = 0; speed < numSpeeds; speed++) {
8600 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008601 cpuSpeeds[speed] = new LongSamplingCounter(
8602 mBsi.mOnBatteryTimeBase, in);
Adam Lesinski6832f392015-09-05 18:05:40 -07008603 }
8604 }
Adam Lesinskia57a5402015-09-28 10:21:33 -07008605 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008606 mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -07008607 }
8608 }
8609 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008610 mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008611 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008612
Sudheer Shanka59f5c002017-05-15 10:57:15 -07008613 mCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(in, mBsi.mOnBatteryTimeBase);
8614 mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(
8615 in, mBsi.mOnBatteryScreenOffTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008616
Mike Ma3d422c32017-10-25 11:08:57 -07008617 mCpuActiveTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8618 mCpuClusterTimesMs = new LongSamplingCounterArray(mBsi.mOnBatteryTimeBase, in);
8619
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008620 int length = in.readInt();
8621 if (length == NUM_PROCESS_STATE) {
8622 mProcStateTimeMs = new LongSamplingCounterArray[length];
8623 for (int procState = 0; procState < length; ++procState) {
8624 mProcStateTimeMs[procState] = LongSamplingCounterArray.readFromParcel(
8625 in, mBsi.mOnBatteryTimeBase);
8626 }
8627 } else {
8628 mProcStateTimeMs = null;
8629 }
8630 length = in.readInt();
8631 if (length == NUM_PROCESS_STATE) {
8632 mProcStateScreenOffTimeMs = new LongSamplingCounterArray[length];
8633 for (int procState = 0; procState < length; ++procState) {
8634 mProcStateScreenOffTimeMs[procState] = LongSamplingCounterArray.readFromParcel(
8635 in, mBsi.mOnBatteryScreenOffTimeBase);
8636 }
8637 } else {
8638 mProcStateScreenOffTimeMs = null;
8639 }
8640
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008641 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07008642 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8643 } else {
8644 mMobileRadioApWakeupCount = null;
8645 }
8646
8647 if (in.readInt() != 0) {
8648 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8649 } else {
8650 mWifiRadioApWakeupCount = null;
8651 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008652 }
8653
Amith Yamasani977e11f2018-02-16 11:29:54 -08008654 public void noteJobsDeferredLocked(int numDeferred, long sinceLast) {
8655 mJobsDeferredEventCount.addAtomic(1);
8656 mJobsDeferredCount.addAtomic(numDeferred);
8657 if (sinceLast != 0) {
8658 // Add the total time, which can be divided by the event count to get an average
8659 mJobsFreshnessTimeMs.addCountLocked(sinceLast);
8660 // Also keep track of how many times there were in these different buckets.
8661 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
8662 if (sinceLast < JOB_FRESHNESS_BUCKETS[i]) {
8663 if (mJobsFreshnessBuckets[i] == null) {
8664 mJobsFreshnessBuckets[i] = new Counter(
8665 mBsi.mOnBatteryTimeBase);
8666 }
8667 mJobsFreshnessBuckets[i].addAtomic(1);
8668 break;
8669 }
8670 }
8671 }
8672 }
8673
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008674 /**
8675 * The statistics associated with a particular wake lock.
8676 */
Joe Onoratoabded112016-02-08 16:49:39 -08008677 public static class Wakelock extends BatteryStats.Uid.Wakelock {
8678 /**
8679 * BatteryStatsImpl that we are associated with.
8680 */
8681 protected BatteryStatsImpl mBsi;
8682
8683 /**
8684 * BatteryStatsImpl that we are associated with.
8685 */
8686 protected Uid mUid;
8687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008688 /**
8689 * How long (in ms) this uid has been keeping the device partially awake.
Bookatz5b5ec322017-05-26 09:40:38 -07008690 * 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 -08008691 */
Bookatz5b5ec322017-05-26 09:40:38 -07008692 DualTimer mTimerPartial;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008693
8694 /**
8695 * How long (in ms) this uid has been keeping the device fully awake.
8696 */
Evan Millarc64edde2009-04-18 12:26:32 -07008697 StopwatchTimer mTimerFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008698
8699 /**
8700 * How long (in ms) this uid has had a window keeping the device awake.
8701 */
Evan Millarc64edde2009-04-18 12:26:32 -07008702 StopwatchTimer mTimerWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008703
8704 /**
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008705 * How long (in ms) this uid has had a draw wake lock.
Adam Lesinski9425fe22015-06-19 12:02:13 -07008706 */
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008707 StopwatchTimer mTimerDraw;
Adam Lesinski9425fe22015-06-19 12:02:13 -07008708
Joe Onoratoabded112016-02-08 16:49:39 -08008709 public Wakelock(BatteryStatsImpl bsi, Uid uid) {
8710 mBsi = bsi;
8711 mUid = uid;
8712 }
8713
Adam Lesinski9425fe22015-06-19 12:02:13 -07008714 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008715 * Reads a possibly null Timer from a Parcel. The timer is associated with the
8716 * proper timer pool from the given BatteryStatsImpl object.
8717 *
8718 * @param in the Parcel to be read from.
8719 * return a new Timer, or null.
8720 */
Joe Onorato92fd23f2016-07-25 11:18:42 -07008721 private StopwatchTimer readStopwatchTimerFromParcel(int type,
8722 ArrayList<StopwatchTimer> pool, TimeBase timeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008723 if (in.readInt() == 0) {
8724 return null;
8725 }
8726
Joe Onoratoabded112016-02-08 16:49:39 -08008727 return new StopwatchTimer(mBsi.mClocks, mUid, type, pool, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008728 }
8729
Joe Onorato92fd23f2016-07-25 11:18:42 -07008730 /**
8731 * Reads a possibly null Timer from a Parcel. The timer is associated with the
8732 * proper timer pool from the given BatteryStatsImpl object.
8733 *
8734 * @param in the Parcel to be read from.
8735 * return a new Timer, or null.
8736 */
Bookatz5b5ec322017-05-26 09:40:38 -07008737 private DualTimer readDualTimerFromParcel(int type, ArrayList<StopwatchTimer> pool,
8738 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07008739 if (in.readInt() == 0) {
8740 return null;
8741 }
8742
Bookatz5b5ec322017-05-26 09:40:38 -07008743 return new DualTimer(mBsi.mClocks, mUid, type, pool, timeBase, bgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07008744 }
8745
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008746 boolean reset() {
8747 boolean wlactive = false;
Hui Yu8e88e952018-07-23 17:59:59 -07008748
8749 wlactive |= !resetIfNotNull(mTimerFull,false);
8750 wlactive |= !resetIfNotNull(mTimerPartial,false);
8751 wlactive |= !resetIfNotNull(mTimerWindow,false);
8752 wlactive |= !resetIfNotNull(mTimerDraw,false);
8753
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008754 if (!wlactive) {
Hui Yu8e88e952018-07-23 17:59:59 -07008755 detachIfNotNull(mTimerFull);
8756 mTimerFull = null;
8757
8758 detachIfNotNull(mTimerPartial);
8759 mTimerPartial = null;
8760
8761 detachIfNotNull(mTimerWindow);
8762 mTimerWindow = null;
8763
8764 detachIfNotNull(mTimerDraw);
8765 mTimerDraw = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008766 }
8767 return !wlactive;
8768 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008769
Bookatz5b5ec322017-05-26 09:40:38 -07008770 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase,
8771 TimeBase screenOffBgTimeBase, Parcel in) {
8772 mTimerPartial = readDualTimerFromParcel(WAKE_TYPE_PARTIAL,
8773 mBsi.mPartialTimers, screenOffTimeBase, screenOffBgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07008774 mTimerFull = readStopwatchTimerFromParcel(WAKE_TYPE_FULL,
8775 mBsi.mFullTimers, timeBase, in);
8776 mTimerWindow = readStopwatchTimerFromParcel(WAKE_TYPE_WINDOW,
8777 mBsi.mWindowTimers, timeBase, in);
8778 mTimerDraw = readStopwatchTimerFromParcel(WAKE_TYPE_DRAW,
8779 mBsi.mDrawTimers, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008780 }
8781
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008782 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
8783 Timer.writeTimerToParcel(out, mTimerPartial, elapsedRealtimeUs);
8784 Timer.writeTimerToParcel(out, mTimerFull, elapsedRealtimeUs);
8785 Timer.writeTimerToParcel(out, mTimerWindow, elapsedRealtimeUs);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008786 Timer.writeTimerToParcel(out, mTimerDraw, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008787 }
8788
8789 @Override
Mathew Inwoodaf972c82018-08-20 14:13:20 +01008790 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008791 public Timer getWakeTime(int type) {
8792 switch (type) {
8793 case WAKE_TYPE_FULL: return mTimerFull;
8794 case WAKE_TYPE_PARTIAL: return mTimerPartial;
8795 case WAKE_TYPE_WINDOW: return mTimerWindow;
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008796 case WAKE_TYPE_DRAW: return mTimerDraw;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008797 default: throw new IllegalArgumentException("type = " + type);
8798 }
8799 }
Hui Yu8e88e952018-07-23 17:59:59 -07008800
8801 public void detachFromTimeBase() {
8802 detachIfNotNull(mTimerPartial);
8803 detachIfNotNull(mTimerFull);
8804 detachIfNotNull(mTimerWindow);
8805 detachIfNotNull(mTimerDraw);
8806 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008807 }
8808
Joe Onoratoabded112016-02-08 16:49:39 -08008809 public static class Sensor extends BatteryStats.Uid.Sensor {
8810 /**
8811 * BatteryStatsImpl that we are associated with.
8812 */
8813 protected BatteryStatsImpl mBsi;
8814
8815 /**
Bookatz867c0d72017-03-07 18:23:42 -08008816 * Uid that we are associated with.
Joe Onoratoabded112016-02-08 16:49:39 -08008817 */
8818 protected Uid mUid;
8819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008820 final int mHandle;
Bookatz867c0d72017-03-07 18:23:42 -08008821 DualTimer mTimer;
Amith Yamasaniab9ad192016-12-06 12:46:59 -08008822
Joe Onoratoabded112016-02-08 16:49:39 -08008823 public Sensor(BatteryStatsImpl bsi, Uid uid, int handle) {
8824 mBsi = bsi;
8825 mUid = uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008826 mHandle = handle;
8827 }
8828
Bookatz867c0d72017-03-07 18:23:42 -08008829 private DualTimer readTimersFromParcel(
8830 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008831 if (in.readInt() == 0) {
8832 return null;
8833 }
8834
Joe Onoratoabded112016-02-08 16:49:39 -08008835 ArrayList<StopwatchTimer> pool = mBsi.mSensorTimers.get(mHandle);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008836 if (pool == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07008837 pool = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08008838 mBsi.mSensorTimers.put(mHandle, pool);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008839 }
Bookatz867c0d72017-03-07 18:23:42 -08008840 return new DualTimer(mBsi.mClocks, mUid, 0, pool, timeBase, bgTimeBase, in);
Amith Yamasaniab9ad192016-12-06 12:46:59 -08008841 }
8842
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008843 boolean reset() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008844 if (mTimer.reset(true)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008845 mTimer = null;
8846 return true;
8847 }
8848 return false;
8849 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008850
Bookatz867c0d72017-03-07 18:23:42 -08008851 void readFromParcelLocked(TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
8852 mTimer = readTimersFromParcel(timeBase, bgTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008853 }
8854
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008855 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07008856 Timer.writeTimerToParcel(out, mTimer, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008857 }
8858
8859 @Override
Mathew Inwoodaf972c82018-08-20 14:13:20 +01008860 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008861 public Timer getSensorTime() {
Bookatzaa4594a2017-03-24 12:39:56 -07008862 return mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008863 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008864
8865 @Override
Bookatz867c0d72017-03-07 18:23:42 -08008866 public Timer getSensorBackgroundTime() {
8867 if (mTimer == null) {
8868 return null;
8869 }
8870 return mTimer.getSubTimer();
Amith Yamasaniab9ad192016-12-06 12:46:59 -08008871 }
8872
8873 @Override
Mathew Inwoodaf972c82018-08-20 14:13:20 +01008874 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008875 public int getHandle() {
8876 return mHandle;
8877 }
Hui Yu8e88e952018-07-23 17:59:59 -07008878
8879 public void detachFromTimeBase() {
8880 detachIfNotNull(mTimer);
8881 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008882 }
8883
8884 /**
8885 * The statistics associated with a particular process.
8886 */
Joe Onoratoabded112016-02-08 16:49:39 -08008887 public static class Proc extends BatteryStats.Uid.Proc implements TimeBaseObs {
8888 /**
8889 * BatteryStatsImpl that we are associated with.
8890 */
8891 protected BatteryStatsImpl mBsi;
8892
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008893 /**
Dianne Hackborncd0e3352014-08-07 17:08:09 -07008894 * The name of this process.
8895 */
8896 final String mName;
8897
8898 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -08008899 * Remains true until removed from the stats.
8900 */
8901 boolean mActive = true;
8902
8903 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07008904 * Total time (in ms) spent executing in user code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008905 */
8906 long mUserTime;
8907
8908 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07008909 * Total time (in ms) spent executing in kernel code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008910 */
8911 long mSystemTime;
8912
8913 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07008914 * Amount of time (in ms) the process was running in the foreground.
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008915 */
8916 long mForegroundTime;
8917
8918 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008919 * Number of times the process has been started.
8920 */
8921 int mStarts;
8922
8923 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008924 * Number of times the process has crashed.
8925 */
8926 int mNumCrashes;
8927
8928 /**
8929 * Number of times the process has had an ANR.
8930 */
8931 int mNumAnrs;
8932
Dianne Hackborn287952c2010-09-22 22:34:31 -07008933 ArrayList<ExcessivePower> mExcessivePower;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008934
Joe Onoratoabded112016-02-08 16:49:39 -08008935 public Proc(BatteryStatsImpl bsi, String name) {
8936 mBsi = bsi;
Dianne Hackborncd0e3352014-08-07 17:08:09 -07008937 mName = name;
Joe Onoratoabded112016-02-08 16:49:39 -08008938 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008939 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07008940
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008941 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008942 }
8943
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008944 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008945 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008946
Hui Yu8e88e952018-07-23 17:59:59 -07008947 @Override
8948 public boolean reset(boolean detachIfReset) {
8949 if (detachIfReset) {
8950 this.detach();
8951 }
8952 return true;
8953 }
8954
8955 @Override
8956 public void detach() {
Dianne Hackborn099bc622014-01-22 13:39:16 -08008957 mActive = false;
Joe Onoratoabded112016-02-08 16:49:39 -08008958 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008959 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008960
Dianne Hackborn287952c2010-09-22 22:34:31 -07008961 public int countExcessivePowers() {
8962 return mExcessivePower != null ? mExcessivePower.size() : 0;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008963 }
8964
Dianne Hackborn287952c2010-09-22 22:34:31 -07008965 public ExcessivePower getExcessivePower(int i) {
8966 if (mExcessivePower != null) {
8967 return mExcessivePower.get(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008968 }
8969 return null;
8970 }
8971
Dianne Hackborn287952c2010-09-22 22:34:31 -07008972 public void addExcessiveCpu(long overTime, long usedTime) {
8973 if (mExcessivePower == null) {
8974 mExcessivePower = new ArrayList<ExcessivePower>();
8975 }
8976 ExcessivePower ew = new ExcessivePower();
8977 ew.type = ExcessivePower.TYPE_CPU;
8978 ew.overTime = overTime;
8979 ew.usedTime = usedTime;
8980 mExcessivePower.add(ew);
8981 }
8982
8983 void writeExcessivePowerToParcelLocked(Parcel out) {
8984 if (mExcessivePower == null) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008985 out.writeInt(0);
8986 return;
8987 }
8988
Dianne Hackborn287952c2010-09-22 22:34:31 -07008989 final int N = mExcessivePower.size();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008990 out.writeInt(N);
8991 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008992 ExcessivePower ew = mExcessivePower.get(i);
8993 out.writeInt(ew.type);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008994 out.writeLong(ew.overTime);
8995 out.writeLong(ew.usedTime);
8996 }
8997 }
8998
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07008999 void readExcessivePowerFromParcelLocked(Parcel in) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009000 final int N = in.readInt();
9001 if (N == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009002 mExcessivePower = null;
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009003 return;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009004 }
9005
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08009006 if (N > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009007 throw new ParcelFormatException(
9008 "File corrupt: too many excessive power entries " + N);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08009009 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009010
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009011 mExcessivePower = new ArrayList<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009012 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009013 ExcessivePower ew = new ExcessivePower();
9014 ew.type = in.readInt();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009015 ew.overTime = in.readLong();
9016 ew.usedTime = in.readLong();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009017 mExcessivePower.add(ew);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009018 }
9019 }
9020
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009021 void writeToParcelLocked(Parcel out) {
9022 out.writeLong(mUserTime);
9023 out.writeLong(mSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009024 out.writeLong(mForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009025 out.writeInt(mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009026 out.writeInt(mNumCrashes);
9027 out.writeInt(mNumAnrs);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009028 writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009029 }
9030
9031 void readFromParcelLocked(Parcel in) {
9032 mUserTime = in.readLong();
9033 mSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009034 mForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009035 mStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009036 mNumCrashes = in.readInt();
9037 mNumAnrs = in.readInt();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009038 readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009039 }
9040
Mathew Inwoodaf972c82018-08-20 14:13:20 +01009041 @UnsupportedAppUsage
Adam Lesinski06af1fa2015-05-05 17:35:35 -07009042 public void addCpuTimeLocked(int utime, int stime) {
Sudheer Shankac57729a2018-02-09 15:44:42 -08009043 addCpuTimeLocked(utime, stime, mBsi.mOnBatteryTimeBase.isRunning());
9044 }
9045
9046 public void addCpuTimeLocked(int utime, int stime, boolean isRunning) {
9047 if (isRunning) {
9048 mUserTime += utime;
9049 mSystemTime += stime;
9050 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009051 }
9052
Mathew Inwoodaf972c82018-08-20 14:13:20 +01009053 @UnsupportedAppUsage
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009054 public void addForegroundTimeLocked(long ttime) {
9055 mForegroundTime += ttime;
9056 }
9057
Mathew Inwoodaf972c82018-08-20 14:13:20 +01009058 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009059 public void incStartsLocked() {
9060 mStarts++;
9061 }
9062
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009063 public void incNumCrashesLocked() {
9064 mNumCrashes++;
9065 }
9066
9067 public void incNumAnrsLocked() {
9068 mNumAnrs++;
9069 }
9070
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009071 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -08009072 public boolean isActive() {
9073 return mActive;
9074 }
9075
9076 @Override
Mathew Inwoodaf972c82018-08-20 14:13:20 +01009077 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009078 public long getUserTime(int which) {
Mike Ma99e57c32018-03-15 14:40:37 -07009079 return mUserTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009080 }
9081
9082 @Override
Mathew Inwoodaf972c82018-08-20 14:13:20 +01009083 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009084 public long getSystemTime(int which) {
Mike Ma99e57c32018-03-15 14:40:37 -07009085 return mSystemTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009086 }
9087
9088 @Override
Mathew Inwoodaf972c82018-08-20 14:13:20 +01009089 @UnsupportedAppUsage
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009090 public long getForegroundTime(int which) {
Mike Ma99e57c32018-03-15 14:40:37 -07009091 return mForegroundTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009092 }
9093
9094 @Override
Mathew Inwoodaf972c82018-08-20 14:13:20 +01009095 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009096 public int getStarts(int which) {
Mike Ma99e57c32018-03-15 14:40:37 -07009097 return mStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009098 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07009099
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009100 @Override
9101 public int getNumCrashes(int which) {
Mike Ma99e57c32018-03-15 14:40:37 -07009102 return mNumCrashes;
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009103 }
9104
9105 @Override
9106 public int getNumAnrs(int which) {
Mike Ma99e57c32018-03-15 14:40:37 -07009107 return mNumAnrs;
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009108 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009109 }
9110
9111 /**
9112 * The statistics associated with a particular package.
9113 */
Joe Onoratoabded112016-02-08 16:49:39 -08009114 public static class Pkg extends BatteryStats.Uid.Pkg implements TimeBaseObs {
9115 /**
9116 * BatteryStatsImpl that we are associated with.
9117 */
9118 protected BatteryStatsImpl mBsi;
9119
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009120 /**
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009121 * Number of times wakeup alarms have occurred for this app.
Bookatz98d4d5c2017-08-01 19:07:54 -07009122 * On screen-off timebase starting in report v25.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009123 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009124 ArrayMap<String, Counter> mWakeupAlarms = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009125
9126 /**
9127 * The statics we have collected for this package's services.
9128 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009129 final ArrayMap<String, Serv> mServiceStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009130
Joe Onoratoabded112016-02-08 16:49:39 -08009131 public Pkg(BatteryStatsImpl bsi) {
9132 mBsi = bsi;
9133 mBsi.mOnBatteryScreenOffTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009134 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009135
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009136 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009137 }
9138
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009139 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009140 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009141
Hui Yu8e88e952018-07-23 17:59:59 -07009142 @Override
9143 public boolean reset(boolean detachIfReset) {
9144 if (detachIfReset) {
9145 this.detach();
9146 }
9147 return true;
9148 }
9149
9150 @Override
9151 public void detach() {
Joe Onoratoabded112016-02-08 16:49:39 -08009152 mBsi.mOnBatteryScreenOffTimeBase.remove(this);
Hui Yu8e88e952018-07-23 17:59:59 -07009153 for (int j = mWakeupAlarms.size() - 1; j >= 0; j--) {
9154 detachIfNotNull(mWakeupAlarms.valueAt(j));
9155 }
9156 for (int j = mServiceStats.size() - 1; j >= 0; j--) {
9157 detachIfNotNull(mServiceStats.valueAt(j));
9158 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009159 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009161 void readFromParcelLocked(Parcel in) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009162 int numWA = in.readInt();
9163 mWakeupAlarms.clear();
9164 for (int i=0; i<numWA; i++) {
9165 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -07009166 mWakeupAlarms.put(tag, new Counter(mBsi.mOnBatteryScreenOffTimeBase, in));
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009167 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009168
9169 int numServs = in.readInt();
9170 mServiceStats.clear();
9171 for (int m = 0; m < numServs; m++) {
9172 String serviceName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08009173 Uid.Pkg.Serv serv = new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009174 mServiceStats.put(serviceName, serv);
9175
9176 serv.readFromParcelLocked(in);
9177 }
9178 }
9179
9180 void writeToParcelLocked(Parcel out) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009181 int numWA = mWakeupAlarms.size();
9182 out.writeInt(numWA);
9183 for (int i=0; i<numWA; i++) {
9184 out.writeString(mWakeupAlarms.keyAt(i));
9185 mWakeupAlarms.valueAt(i).writeToParcel(out);
9186 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009187
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009188 final int NS = mServiceStats.size();
9189 out.writeInt(NS);
9190 for (int i=0; i<NS; i++) {
9191 out.writeString(mServiceStats.keyAt(i));
9192 Uid.Pkg.Serv serv = mServiceStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009193 serv.writeToParcelLocked(out);
9194 }
9195 }
9196
9197 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009198 public ArrayMap<String, ? extends BatteryStats.Counter> getWakeupAlarmStats() {
9199 return mWakeupAlarms;
9200 }
9201
9202 public void noteWakeupAlarmLocked(String tag) {
9203 Counter c = mWakeupAlarms.get(tag);
9204 if (c == null) {
Bookatz98d4d5c2017-08-01 19:07:54 -07009205 c = new Counter(mBsi.mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009206 mWakeupAlarms.put(tag, c);
9207 }
9208 c.stepAtomic();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009209 }
9210
9211 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009212 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg.Serv> getServiceStats() {
9213 return mServiceStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009214 }
9215
9216 /**
9217 * The statistics associated with a particular service.
9218 */
Joe Onoratoabded112016-02-08 16:49:39 -08009219 public static class Serv extends BatteryStats.Uid.Pkg.Serv implements TimeBaseObs {
9220 /**
9221 * BatteryStatsImpl that we are associated with.
9222 */
9223 protected BatteryStatsImpl mBsi;
9224
9225 /**
9226 * The android package in which this service resides.
9227 */
9228 protected Pkg mPkg;
9229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009230 /**
9231 * Total time (ms in battery uptime) the service has been left started.
9232 */
Joe Onoratoabded112016-02-08 16:49:39 -08009233 protected long mStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009234
9235 /**
9236 * If service has been started and not yet stopped, this is
9237 * when it was started.
9238 */
Joe Onoratoabded112016-02-08 16:49:39 -08009239 protected long mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009240
9241 /**
9242 * True if we are currently running.
9243 */
Joe Onoratoabded112016-02-08 16:49:39 -08009244 protected boolean mRunning;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009245
9246 /**
9247 * Total number of times startService() has been called.
9248 */
Joe Onoratoabded112016-02-08 16:49:39 -08009249 protected int mStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009250
9251 /**
9252 * Total time (ms in battery uptime) the service has been left launched.
9253 */
Joe Onoratoabded112016-02-08 16:49:39 -08009254 protected long mLaunchedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009255
9256 /**
9257 * If service has been launched and not yet exited, this is
9258 * when it was launched (ms in battery uptime).
9259 */
Joe Onoratoabded112016-02-08 16:49:39 -08009260 protected long mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009261
9262 /**
9263 * True if we are currently launched.
9264 */
Joe Onoratoabded112016-02-08 16:49:39 -08009265 protected boolean mLaunched;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009266
9267 /**
9268 * Total number times the service has been launched.
9269 */
Joe Onoratoabded112016-02-08 16:49:39 -08009270 protected int mLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009271
9272 /**
Joe Onoratoabded112016-02-08 16:49:39 -08009273 * Construct a Serv. Also adds it to the on-battery time base as a listener.
9274 */
9275 public Serv(BatteryStatsImpl bsi) {
9276 mBsi = bsi;
9277 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009278 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009279
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009280 public void onTimeStarted(long elapsedRealtime, long baseUptime,
9281 long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009282 }
9283
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009284 public void onTimeStopped(long elapsedRealtime, long baseUptime,
9285 long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009286 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009287
Hui Yu8e88e952018-07-23 17:59:59 -07009288 @Override
9289 public boolean reset(boolean detachIfReset) {
9290 if (detachIfReset) {
9291 this.detach();
9292 }
9293 return true;
9294 }
9295
Joe Onoratoabded112016-02-08 16:49:39 -08009296 /**
9297 * Remove this Serv as a listener from the time base.
9298 */
Hui Yu8e88e952018-07-23 17:59:59 -07009299 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08009300 public void detach() {
9301 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009302 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009303
Joe Onoratoabded112016-02-08 16:49:39 -08009304 public void readFromParcelLocked(Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009305 mStartTime = in.readLong();
9306 mRunningSince = in.readLong();
9307 mRunning = in.readInt() != 0;
9308 mStarts = in.readInt();
9309 mLaunchedTime = in.readLong();
9310 mLaunchedSince = in.readLong();
9311 mLaunched = in.readInt() != 0;
9312 mLaunches = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009313 }
9314
Joe Onoratoabded112016-02-08 16:49:39 -08009315 public void writeToParcelLocked(Parcel out) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009316 out.writeLong(mStartTime);
9317 out.writeLong(mRunningSince);
9318 out.writeInt(mRunning ? 1 : 0);
9319 out.writeInt(mStarts);
9320 out.writeLong(mLaunchedTime);
9321 out.writeLong(mLaunchedSince);
9322 out.writeInt(mLaunched ? 1 : 0);
9323 out.writeInt(mLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009324 }
9325
Joe Onoratoabded112016-02-08 16:49:39 -08009326 public long getLaunchTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009327 if (!mLaunched) return mLaunchedTime;
9328 return mLaunchedTime + batteryUptime - mLaunchedSince;
9329 }
9330
Joe Onoratoabded112016-02-08 16:49:39 -08009331 public long getStartTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009332 if (!mRunning) return mStartTime;
9333 return mStartTime + batteryUptime - mRunningSince;
9334 }
9335
Mathew Inwoodaf972c82018-08-20 14:13:20 +01009336 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009337 public void startLaunchedLocked() {
9338 if (!mLaunched) {
9339 mLaunches++;
Joe Onoratoabded112016-02-08 16:49:39 -08009340 mLaunchedSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009341 mLaunched = true;
9342 }
9343 }
9344
Mathew Inwoodaf972c82018-08-20 14:13:20 +01009345 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009346 public void stopLaunchedLocked() {
9347 if (mLaunched) {
Joe Onoratoabded112016-02-08 16:49:39 -08009348 long time = mBsi.getBatteryUptimeLocked() - mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009349 if (time > 0) {
9350 mLaunchedTime += time;
9351 } else {
9352 mLaunches--;
9353 }
9354 mLaunched = false;
9355 }
9356 }
9357
Mathew Inwoodaf972c82018-08-20 14:13:20 +01009358 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009359 public void startRunningLocked() {
9360 if (!mRunning) {
9361 mStarts++;
Joe Onoratoabded112016-02-08 16:49:39 -08009362 mRunningSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009363 mRunning = true;
9364 }
9365 }
9366
Mathew Inwoodaf972c82018-08-20 14:13:20 +01009367 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009368 public void stopRunningLocked() {
9369 if (mRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08009370 long time = mBsi.getBatteryUptimeLocked() - mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009371 if (time > 0) {
9372 mStartTime += time;
9373 } else {
9374 mStarts--;
9375 }
9376 mRunning = false;
9377 }
9378 }
9379
Mathew Inwoodaf972c82018-08-20 14:13:20 +01009380 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009381 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -08009382 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009383 }
9384
9385 @Override
9386 public int getLaunches(int which) {
Mike Ma99e57c32018-03-15 14:40:37 -07009387 return mLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009388 }
9389
9390 @Override
9391 public long getStartTime(long now, int which) {
Mike Ma99e57c32018-03-15 14:40:37 -07009392 return getStartTimeToNowLocked(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009393 }
9394
9395 @Override
9396 public int getStarts(int which) {
Mike Ma99e57c32018-03-15 14:40:37 -07009397 return mStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009398 }
9399 }
9400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009401 final Serv newServiceStatsLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08009402 return new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009403 }
9404 }
9405
9406 /**
9407 * Retrieve the statistics object for a particular process, creating
9408 * if needed.
9409 */
9410 public Proc getProcessStatsLocked(String name) {
9411 Proc ps = mProcessStats.get(name);
9412 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08009413 ps = new Proc(mBsi, name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009414 mProcessStats.put(name, ps);
9415 }
9416
9417 return ps;
9418 }
9419
Andreas Gampe3f24e692018-02-05 13:24:28 -08009420 @GuardedBy("mBsi")
Dianne Hackborna8d10942015-11-19 17:55:19 -08009421 public void updateUidProcessStateLocked(int procState) {
9422 int uidRunningState;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009423 // Make special note of Foreground Services
9424 final boolean userAwareService =
Amith Yamasania0a30a12019-01-22 11:38:06 -08009425 (ActivityManager.isForegroundService(procState));
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009426 uidRunningState = BatteryStats.mapToInternalProcessState(procState);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009427
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009428 if (mProcessState == uidRunningState && userAwareService == mInForegroundService) {
9429 return;
9430 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08009431
Bookatz867c0d72017-03-07 18:23:42 -08009432 final long elapsedRealtimeMs = mBsi.mClocks.elapsedRealtime();
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009433 if (mProcessState != uidRunningState) {
9434 final long uptimeMs = mBsi.mClocks.uptimeMillis();
Dianne Hackborna8d10942015-11-19 17:55:19 -08009435
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009436 if (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
9437 mProcessStateTimer[mProcessState].stopRunningLocked(elapsedRealtimeMs);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009438
Sudheer Shanka5c19b892018-01-05 17:25:46 -08009439 if (mBsi.trackPerProcStateCpuTimes()) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009440 if (mBsi.mPendingUids.size() == 0) {
Sudheer Shankae544d162017-12-28 17:06:20 -08009441 mBsi.mExternalSync.scheduleReadProcStateCpuTimes(
9442 mBsi.mOnBatteryTimeBase.isRunning(),
Sudheer Shankac20379e2018-02-15 00:06:21 -08009443 mBsi.mOnBatteryScreenOffTimeBase.isRunning(),
9444 mBsi.mConstants.PROC_STATE_CPU_TIMES_READ_DELAY_MS);
Mike Ma234d1822018-03-13 18:53:21 -07009445 mBsi.mNumSingleUidCpuTimeReads++;
Sudheer Shankac20379e2018-02-15 00:06:21 -08009446 } else {
Mike Ma234d1822018-03-13 18:53:21 -07009447 mBsi.mNumBatchedSingleUidCpuTimeReads++;
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009448 }
9449 if (mBsi.mPendingUids.indexOfKey(mUid) < 0
9450 || ArrayUtils.contains(CRITICAL_PROC_STATES, mProcessState)) {
9451 mBsi.mPendingUids.put(mUid, mProcessState);
9452 }
9453 } else {
9454 mBsi.mPendingUids.clear();
9455 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07009456 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009457 mProcessState = uidRunningState;
9458 if (uidRunningState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
9459 if (mProcessStateTimer[uidRunningState] == null) {
9460 makeProcessState(uidRunningState, null);
9461 }
9462 mProcessStateTimer[uidRunningState].startRunningLocked(elapsedRealtimeMs);
9463 }
9464
9465 updateOnBatteryBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
9466 updateOnBatteryScreenOffBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009467 }
Bookatz867c0d72017-03-07 18:23:42 -08009468
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009469 if (userAwareService != mInForegroundService) {
9470 if (userAwareService) {
9471 noteForegroundServiceResumedLocked(elapsedRealtimeMs);
9472 } else {
9473 noteForegroundServicePausedLocked(elapsedRealtimeMs);
9474 }
9475 mInForegroundService = userAwareService;
9476 }
Bookatz867c0d72017-03-07 18:23:42 -08009477 }
9478
Bookatzc8c44962017-05-11 12:12:54 -07009479 /** Whether to consider Uid to be in the background for background timebase purposes. */
9480 public boolean isInBackground() {
Bookatz867c0d72017-03-07 18:23:42 -08009481 // Note that PROCESS_STATE_CACHED and ActivityManager.PROCESS_STATE_NONEXISTENT is
9482 // also considered to be 'background' for our purposes, because it's not foreground.
Bookatzc8c44962017-05-11 12:12:54 -07009483 return mProcessState >= PROCESS_STATE_BACKGROUND;
9484 }
9485
9486 public boolean updateOnBatteryBgTimeBase(long uptimeUs, long realtimeUs) {
9487 boolean on = mBsi.mOnBatteryTimeBase.isRunning() && isInBackground();
9488 return mOnBatteryBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
9489 }
9490
9491 public boolean updateOnBatteryScreenOffBgTimeBase(long uptimeUs, long realtimeUs) {
9492 boolean on = mBsi.mOnBatteryScreenOffTimeBase.isRunning() && isInBackground();
9493 return mOnBatteryScreenOffBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009494 }
9495
Dianne Hackbornb5e31652010-09-07 12:13:55 -07009496 public SparseArray<? extends Pid> getPidStats() {
9497 return mPids;
9498 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009499
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009500 public Pid getPidStatsLocked(int pid) {
9501 Pid p = mPids.get(pid);
9502 if (p == null) {
9503 p = new Pid();
9504 mPids.put(pid, p);
9505 }
9506 return p;
9507 }
9508
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009509 /**
9510 * Retrieve the statistics object for a particular service, creating
9511 * if needed.
9512 */
9513 public Pkg getPackageStatsLocked(String name) {
9514 Pkg ps = mPackageStats.get(name);
9515 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08009516 ps = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009517 mPackageStats.put(name, ps);
9518 }
9519
9520 return ps;
9521 }
9522
9523 /**
9524 * Retrieve the statistics object for a particular service, creating
9525 * if needed.
9526 */
9527 public Pkg.Serv getServiceStatsLocked(String pkg, String serv) {
9528 Pkg ps = getPackageStatsLocked(pkg);
9529 Pkg.Serv ss = ps.mServiceStats.get(serv);
9530 if (ss == null) {
9531 ss = ps.newServiceStatsLocked();
9532 ps.mServiceStats.put(serv, ss);
9533 }
9534
9535 return ss;
9536 }
9537
Dianne Hackbornd953c532014-08-16 18:17:38 -07009538 public void readSyncSummaryFromParcelLocked(String name, Parcel in) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009539 DualTimer timer = mSyncStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07009540 timer.readSummaryFromParcelLocked(in);
9541 mSyncStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009542 }
9543
Dianne Hackbornd953c532014-08-16 18:17:38 -07009544 public void readJobSummaryFromParcelLocked(String name, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07009545 DualTimer timer = mJobStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07009546 timer.readSummaryFromParcelLocked(in);
9547 mJobStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009548 }
9549
Dianne Hackbornd953c532014-08-16 18:17:38 -07009550 public void readWakeSummaryFromParcelLocked(String wlName, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08009551 Wakelock wl = new Wakelock(mBsi, this);
Dianne Hackbornd953c532014-08-16 18:17:38 -07009552 mWakelockStats.add(wlName, wl);
9553 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009554 getWakelockTimerLocked(wl, WAKE_TYPE_FULL).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009555 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07009556 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009557 getWakelockTimerLocked(wl, WAKE_TYPE_PARTIAL).readSummaryFromParcelLocked(in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07009558 }
9559 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009560 getWakelockTimerLocked(wl, WAKE_TYPE_WINDOW).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009561 }
Adam Lesinski9425fe22015-06-19 12:02:13 -07009562 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009563 getWakelockTimerLocked(wl, WAKE_TYPE_DRAW).readSummaryFromParcelLocked(in);
Adam Lesinski9425fe22015-06-19 12:02:13 -07009564 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009565 }
9566
Bookatz867c0d72017-03-07 18:23:42 -08009567 public DualTimer getSensorTimerLocked(int sensor, boolean create) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009568 Sensor se = mSensorStats.get(sensor);
9569 if (se == null) {
9570 if (!create) {
9571 return null;
9572 }
Joe Onoratoabded112016-02-08 16:49:39 -08009573 se = new Sensor(mBsi, this, sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009574 mSensorStats.put(sensor, se);
9575 }
Bookatz867c0d72017-03-07 18:23:42 -08009576 DualTimer t = se.mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009577 if (t != null) {
9578 return t;
9579 }
Joe Onoratoabded112016-02-08 16:49:39 -08009580 ArrayList<StopwatchTimer> timers = mBsi.mSensorTimers.get(sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009581 if (timers == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07009582 timers = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08009583 mBsi.mSensorTimers.put(sensor, timers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009584 }
Bookatz867c0d72017-03-07 18:23:42 -08009585 t = new DualTimer(mBsi.mClocks, this, BatteryStats.SENSOR, timers,
9586 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009587 se.mTimer = t;
9588 return t;
9589 }
9590
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009591 public void noteStartSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009592 DualTimer t = mSyncStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009593 if (t != null) {
9594 t.startRunningLocked(elapsedRealtimeMs);
9595 }
9596 }
9597
9598 public void noteStopSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009599 DualTimer t = mSyncStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009600 if (t != null) {
9601 t.stopRunningLocked(elapsedRealtimeMs);
9602 }
9603 }
9604
9605 public void noteStartJobLocked(String name, long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07009606 DualTimer t = mJobStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009607 if (t != null) {
9608 t.startRunningLocked(elapsedRealtimeMs);
9609 }
9610 }
9611
Dianne Hackborn94326cb2017-06-28 16:17:20 -07009612 public void noteStopJobLocked(String name, long elapsedRealtimeMs, int stopReason) {
Bookatzaa4594a2017-03-24 12:39:56 -07009613 DualTimer t = mJobStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009614 if (t != null) {
9615 t.stopRunningLocked(elapsedRealtimeMs);
9616 }
Dianne Hackborn94326cb2017-06-28 16:17:20 -07009617 if (mBsi.mOnBatteryTimeBase.isRunning()) {
9618 SparseIntArray types = mJobCompletions.get(name);
9619 if (types == null) {
9620 types = new SparseIntArray();
9621 mJobCompletions.put(name, types);
9622 }
9623 int last = types.get(stopReason, 0);
9624 types.put(stopReason, last + 1);
9625 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009626 }
9627
Bookatz5b5ec322017-05-26 09:40:38 -07009628 public StopwatchTimer getWakelockTimerLocked(Wakelock wl, int type) {
9629 if (wl == null) {
9630 return null;
9631 }
9632 switch (type) {
9633 case WAKE_TYPE_PARTIAL: {
9634 DualTimer t = wl.mTimerPartial;
9635 if (t == null) {
9636 t = new DualTimer(mBsi.mClocks, this, WAKE_TYPE_PARTIAL,
9637 mBsi.mPartialTimers, mBsi.mOnBatteryScreenOffTimeBase,
9638 mOnBatteryScreenOffBackgroundTimeBase);
9639 wl.mTimerPartial = t;
9640 }
9641 return t;
9642 }
9643 case WAKE_TYPE_FULL: {
9644 StopwatchTimer t = wl.mTimerFull;
9645 if (t == null) {
9646 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_FULL,
9647 mBsi.mFullTimers, mBsi.mOnBatteryTimeBase);
9648 wl.mTimerFull = t;
9649 }
9650 return t;
9651 }
9652 case WAKE_TYPE_WINDOW: {
9653 StopwatchTimer t = wl.mTimerWindow;
9654 if (t == null) {
9655 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_WINDOW,
9656 mBsi.mWindowTimers, mBsi.mOnBatteryTimeBase);
9657 wl.mTimerWindow = t;
9658 }
9659 return t;
9660 }
9661 case WAKE_TYPE_DRAW: {
9662 StopwatchTimer t = wl.mTimerDraw;
9663 if (t == null) {
9664 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_DRAW,
9665 mBsi.mDrawTimers, mBsi.mOnBatteryTimeBase);
9666 wl.mTimerDraw = t;
9667 }
9668 return t;
9669 }
9670 default:
9671 throw new IllegalArgumentException("type=" + type);
9672 }
9673 }
9674
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009675 public void noteStartWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07009676 Wakelock wl = mWakelockStats.startObject(name);
9677 if (wl != null) {
Bookatz5b5ec322017-05-26 09:40:38 -07009678 getWakelockTimerLocked(wl, type).startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009679 }
Bookatzc8c44962017-05-11 12:12:54 -07009680 if (type == WAKE_TYPE_PARTIAL) {
9681 createAggregatedPartialWakelockTimerLocked().startRunningLocked(elapsedRealtimeMs);
9682 if (pid >= 0) {
9683 Pid p = getPidStatsLocked(pid);
9684 if (p.mWakeNesting++ == 0) {
9685 p.mWakeStartMs = elapsedRealtimeMs;
9686 }
Dianne Hackbornb8071d792010-09-09 16:45:15 -07009687 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009688 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009689 }
9690
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009691 public void noteStopWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07009692 Wakelock wl = mWakelockStats.stopObject(name);
9693 if (wl != null) {
Bookatzd6746242017-10-24 18:39:35 -07009694 StopwatchTimer wlt = getWakelockTimerLocked(wl, type);
9695 wlt.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009696 }
Bookatzc8c44962017-05-11 12:12:54 -07009697 if (type == WAKE_TYPE_PARTIAL) {
9698 if (mAggregatedPartialWakelockTimer != null) {
9699 mAggregatedPartialWakelockTimer.stopRunningLocked(elapsedRealtimeMs);
9700 }
9701 if (pid >= 0) {
9702 Pid p = mPids.get(pid);
9703 if (p != null && p.mWakeNesting > 0) {
9704 if (p.mWakeNesting-- == 1) {
9705 p.mWakeSumMs += elapsedRealtimeMs - p.mWakeStartMs;
9706 p.mWakeStartMs = 0;
9707 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -08009708 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009709 }
9710 }
9711 }
9712
Dianne Hackborn287952c2010-09-22 22:34:31 -07009713 public void reportExcessiveCpuLocked(String proc, long overTime, long usedTime) {
9714 Proc p = getProcessStatsLocked(proc);
9715 if (p != null) {
9716 p.addExcessiveCpu(overTime, usedTime);
9717 }
9718 }
9719
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009720 public void noteStartSensor(int sensor, long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -08009721 DualTimer t = getSensorTimerLocked(sensor, /* create= */ true);
Amith Yamasani154d1242017-02-16 10:01:48 -08009722 t.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009723 }
9724
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009725 public void noteStopSensor(int sensor, long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009726 // Don't create a timer if one doesn't already exist
Bookatz867c0d72017-03-07 18:23:42 -08009727 DualTimer t = getSensorTimerLocked(sensor, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009728 if (t != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009729 t.stopRunningLocked(elapsedRealtimeMs);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009730 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009731 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009732
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009733 public void noteStartGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -08009734 noteStartSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009735 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009736
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009737 public void noteStopGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -08009738 noteStopSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009739 }
9740
9741 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -08009742 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009743 }
9744 }
9745
Sudheer Shanka9b735c52017-05-09 18:26:18 -07009746 public long[] getCpuFreqs() {
9747 return mCpuFreqs;
9748 }
9749
Suprabh Shuklae6e723d2017-06-14 16:14:43 -07009750 public BatteryStatsImpl(File systemDir, Handler handler, PlatformIdleStateCallback cb,
Blake Kragtencb308d92019-01-28 10:54:13 -08009751 RailEnergyDataCallback railStatsCb, UserInfoProvider userInfoProvider) {
9752 this(new SystemClocks(), systemDir, handler, cb, railStatsCb, userInfoProvider);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07009753 }
9754
Suprabh Shuklae6e723d2017-06-14 16:14:43 -07009755 private BatteryStatsImpl(Clocks clocks, File systemDir, Handler handler,
Blake Kragtencb308d92019-01-28 10:54:13 -08009756 PlatformIdleStateCallback cb, RailEnergyDataCallback railStatsCb,
Suprabh Shuklae6e723d2017-06-14 16:14:43 -07009757 UserInfoProvider userInfoProvider) {
Joe Onoratoabded112016-02-08 16:49:39 -08009758 init(clocks);
9759
Hui Yu0ed84f12018-06-20 19:07:56 -07009760
9761 if (systemDir == null) {
9762 mStatsFile = null;
9763 mBatteryStatsHistory = new BatteryStatsHistory(this, mHistoryBuffer);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07009764 } else {
Hui Yu0ed84f12018-06-20 19:07:56 -07009765 mStatsFile = new AtomicFile(new File(systemDir, "batterystats.bin"));
9766 mBatteryStatsHistory = new BatteryStatsHistory(this, systemDir, mHistoryBuffer);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07009767 }
9768 mCheckinFile = new AtomicFile(new File(systemDir, "batterystats-checkin.bin"));
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009769 mDailyFile = new AtomicFile(new File(systemDir, "batterystats-daily.xml"));
Jeff Brown6f357d32014-01-15 20:40:55 -08009770 mHandler = new MyHandler(handler.getLooper());
Sudheer Shanka5c19b892018-01-05 17:25:46 -08009771 mConstants = new Constants(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009772 mStartCount++;
Joe Onoratoabded112016-02-08 16:49:39 -08009773 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -07009774 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -07009775 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08009776 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009777 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -07009778 }
Joe Onoratoabded112016-02-08 16:49:39 -08009779 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase);
9780 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
9781 mOnBatteryTimeBase);
9782 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -11, null,
9783 mOnBatteryTimeBase);
9784 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
9785 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null, mOnBatteryTimeBase);
9786 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase);
9787 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase);
9788 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
9789 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i, null,
9790 mOnBatteryTimeBase);
9791 }
9792 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
9793 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -07009794 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08009795 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009796 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -07009797 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07009798 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009799 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
9800 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07009801 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009802 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase, NUM_WIFI_TX_LEVELS);
9803 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
9804 NUM_BT_TX_LEVELS);
9805 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
9806 ModemActivityInfo.TX_POWER_LEVELS);
Joe Onoratoabded112016-02-08 16:49:39 -08009807 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null, mOnBatteryTimeBase);
9808 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
9809 mOnBatteryTimeBase);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07009810 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009811 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase);
9812 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08009813 mWifiMulticastWakelockTimer = new StopwatchTimer(mClocks, null,
9814 WIFI_AGGREGATE_MULTICAST_ENABLED, null, mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08009815 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase);
9816 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null, mOnBatteryTimeBase);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08009817 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08009818 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i, null,
Dianne Hackborn3251b902014-06-20 14:40:53 -07009819 mOnBatteryTimeBase);
9820 }
Joe Onoratoabded112016-02-08 16:49:39 -08009821 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
9822 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i, null,
9823 mOnBatteryTimeBase);
9824 }
9825 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
9826 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i, null,
9827 mOnBatteryTimeBase);
9828 }
Siddharth Rayb50a6842017-12-14 15:15:28 -08009829 mWifiActiveTimer = new StopwatchTimer(mClocks, null, -900, null, mOnBatteryTimeBase);
Siddharth Ray78ccaf52017-12-23 16:16:21 -08009830 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
9831 mGpsSignalQualityTimer[i] = new StopwatchTimer(mClocks, null, -1000-i, null,
9832 mOnBatteryTimeBase);
9833 }
Joe Onoratoabded112016-02-08 16:49:39 -08009834 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
9835 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
9836 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase);
9837 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase);
9838 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -07009839 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -07009840 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Mike Ma15313c92017-11-15 17:58:21 -08009841 mDischargeLightDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
9842 mDischargeDeepDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -07009843 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009844 mOnBattery = mOnBatteryInternal = false;
Joe Onoratoabded112016-02-08 16:49:39 -08009845 long uptime = mClocks.uptimeMillis() * 1000;
9846 long realtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009847 initTimes(uptime, realtime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -07009848 mStartPlatformVersion = mEndPlatformVersion = Build.ID;
Evan Millar633a1742009-04-02 16:36:33 -07009849 mDischargeStartLevel = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009850 mDischargeUnplugLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07009851 mDischargePlugLevel = -1;
Evan Millar633a1742009-04-02 16:36:33 -07009852 mDischargeCurrentLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07009853 mCurrentBatteryLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08009854 initDischarge();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009855 clearHistoryLocked();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009856 updateDailyDeadlineLocked();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07009857 mPlatformIdleStateCallback = cb;
Blake Kragtencb308d92019-01-28 10:54:13 -08009858 mRailEnergyDataCallback = railStatsCb;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -07009859 mUserInfoProvider = userInfoProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009860 }
9861
Mathew Inwoodaf972c82018-08-20 14:13:20 +01009862 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009863 public BatteryStatsImpl(Parcel p) {
Joe Onoratoabded112016-02-08 16:49:39 -08009864 this(new SystemClocks(), p);
9865 }
9866
9867 public BatteryStatsImpl(Clocks clocks, Parcel p) {
9868 init(clocks);
Hui Yu0ed84f12018-06-20 19:07:56 -07009869 mStatsFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07009870 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009871 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07009872 mHandler = null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009873 mExternalSync = null;
Sudheer Shanka5c19b892018-01-05 17:25:46 -08009874 mConstants = new Constants(mHandler);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009875 clearHistoryLocked();
Hui Yu0ed84f12018-06-20 19:07:56 -07009876 mBatteryStatsHistory = new BatteryStatsHistory(this, mHistoryBuffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009877 readFromParcel(p);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07009878 mPlatformIdleStateCallback = null;
Blake Kragtencb308d92019-01-28 10:54:13 -08009879 mRailEnergyDataCallback = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009880 }
9881
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009882 public void setPowerProfileLocked(PowerProfile profile) {
9883 mPowerProfile = profile;
Adam Lesinski6832f392015-09-05 18:05:40 -07009884
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009885 // We need to initialize the KernelCpuSpeedReaders to read from
9886 // the first cpu of each core. Once we have the PowerProfile, we have access to this
9887 // information.
9888 final int numClusters = mPowerProfile.getNumCpuClusters();
9889 mKernelCpuSpeedReaders = new KernelCpuSpeedReader[numClusters];
9890 int firstCpuOfCluster = 0;
9891 for (int i = 0; i < numClusters; i++) {
9892 final int numSpeedSteps = mPowerProfile.getNumSpeedStepsInCpuCluster(i);
9893 mKernelCpuSpeedReaders[i] = new KernelCpuSpeedReader(firstCpuOfCluster,
9894 numSpeedSteps);
9895 firstCpuOfCluster += mPowerProfile.getNumCoresInCpuCluster(i);
9896 }
Adam Lesinskif9b20a92016-06-17 17:30:01 -07009897
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009898 if (mEstimatedBatteryCapacity == -1) {
9899 // Initialize the estimated battery capacity to a known preset one.
9900 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
Adam Lesinskie08af192015-03-25 16:42:59 -07009901 }
9902 }
9903
Dianne Hackborn0d903a82010-09-07 23:51:03 -07009904 public void setCallback(BatteryCallback cb) {
9905 mCallback = cb;
9906 }
9907
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009908 public void setRadioScanningTimeoutLocked(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07009909 if (mPhoneSignalScanningTimer != null) {
9910 mPhoneSignalScanningTimer.setTimeout(timeout);
9911 }
9912 }
9913
Adam Lesinskib3a1bad2017-05-26 11:50:40 -07009914 public void setExternalStatsSyncLocked(ExternalStatsSync sync) {
9915 mExternalSync = sync;
9916 }
9917
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009918 public void updateDailyDeadlineLocked() {
9919 // Get the current time.
9920 long currentTime = mDailyStartTime = System.currentTimeMillis();
9921 Calendar calDeadline = Calendar.getInstance();
9922 calDeadline.setTimeInMillis(currentTime);
9923
9924 // Move time up to the next day, ranging from 1am to 3pm.
9925 calDeadline.set(Calendar.DAY_OF_YEAR, calDeadline.get(Calendar.DAY_OF_YEAR) + 1);
9926 calDeadline.set(Calendar.MILLISECOND, 0);
9927 calDeadline.set(Calendar.SECOND, 0);
9928 calDeadline.set(Calendar.MINUTE, 0);
9929 calDeadline.set(Calendar.HOUR_OF_DAY, 1);
9930 mNextMinDailyDeadline = calDeadline.getTimeInMillis();
9931 calDeadline.set(Calendar.HOUR_OF_DAY, 3);
9932 mNextMaxDailyDeadline = calDeadline.getTimeInMillis();
9933 }
9934
9935 public void recordDailyStatsIfNeededLocked(boolean settled) {
9936 long currentTime = System.currentTimeMillis();
9937 if (currentTime >= mNextMaxDailyDeadline) {
9938 recordDailyStatsLocked();
9939 } else if (settled && currentTime >= mNextMinDailyDeadline) {
9940 recordDailyStatsLocked();
9941 } else if (currentTime < (mDailyStartTime-(1000*60*60*24))) {
9942 recordDailyStatsLocked();
9943 }
9944 }
9945
9946 public void recordDailyStatsLocked() {
9947 DailyItem item = new DailyItem();
9948 item.mStartTime = mDailyStartTime;
9949 item.mEndTime = System.currentTimeMillis();
9950 boolean hasData = false;
9951 if (mDailyDischargeStepTracker.mNumStepDurations > 0) {
9952 hasData = true;
9953 item.mDischargeSteps = new LevelStepTracker(
9954 mDailyDischargeStepTracker.mNumStepDurations,
9955 mDailyDischargeStepTracker.mStepDurations);
9956 }
9957 if (mDailyChargeStepTracker.mNumStepDurations > 0) {
9958 hasData = true;
9959 item.mChargeSteps = new LevelStepTracker(
9960 mDailyChargeStepTracker.mNumStepDurations,
9961 mDailyChargeStepTracker.mStepDurations);
9962 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07009963 if (mDailyPackageChanges != null) {
9964 hasData = true;
9965 item.mPackageChanges = mDailyPackageChanges;
9966 mDailyPackageChanges = null;
9967 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009968 mDailyDischargeStepTracker.init();
9969 mDailyChargeStepTracker.init();
9970 updateDailyDeadlineLocked();
9971
9972 if (hasData) {
Dianne Hackborne17b4452018-01-10 13:15:40 -08009973 final long startTime = SystemClock.uptimeMillis();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009974 mDailyItems.add(item);
9975 while (mDailyItems.size() > MAX_DAILY_ITEMS) {
9976 mDailyItems.remove(0);
9977 }
9978 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
9979 try {
9980 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01009981 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009982 writeDailyItemsLocked(out);
Dianne Hackborne17b4452018-01-10 13:15:40 -08009983 final long initialTime = SystemClock.uptimeMillis() - startTime;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009984 BackgroundThread.getHandler().post(new Runnable() {
9985 @Override
9986 public void run() {
9987 synchronized (mCheckinFile) {
Dianne Hackborne17b4452018-01-10 13:15:40 -08009988 final long startTime2 = SystemClock.uptimeMillis();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009989 FileOutputStream stream = null;
9990 try {
9991 stream = mDailyFile.startWrite();
9992 memStream.writeTo(stream);
9993 stream.flush();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009994 mDailyFile.finishWrite(stream);
Dianne Hackborne17b4452018-01-10 13:15:40 -08009995 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
9996 "batterystats-daily",
9997 initialTime + SystemClock.uptimeMillis() - startTime2);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009998 } catch (IOException e) {
9999 Slog.w("BatteryStats",
10000 "Error writing battery daily items", e);
10001 mDailyFile.failWrite(stream);
10002 }
10003 }
10004 }
10005 });
10006 } catch (IOException e) {
10007 }
10008 }
10009 }
10010
10011 private void writeDailyItemsLocked(XmlSerializer out) throws IOException {
10012 StringBuilder sb = new StringBuilder(64);
10013 out.startDocument(null, true);
10014 out.startTag(null, "daily-items");
10015 for (int i=0; i<mDailyItems.size(); i++) {
10016 final DailyItem dit = mDailyItems.get(i);
10017 out.startTag(null, "item");
10018 out.attribute(null, "start", Long.toString(dit.mStartTime));
10019 out.attribute(null, "end", Long.toString(dit.mEndTime));
10020 writeDailyLevelSteps(out, "dis", dit.mDischargeSteps, sb);
10021 writeDailyLevelSteps(out, "chg", dit.mChargeSteps, sb);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010022 if (dit.mPackageChanges != null) {
10023 for (int j=0; j<dit.mPackageChanges.size(); j++) {
10024 PackageChange pc = dit.mPackageChanges.get(j);
10025 if (pc.mUpdate) {
10026 out.startTag(null, "upd");
10027 out.attribute(null, "pkg", pc.mPackageName);
Dianne Hackborn3accca02013-09-20 09:32:11 -070010028 out.attribute(null, "ver", Long.toString(pc.mVersionCode));
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010029 out.endTag(null, "upd");
10030 } else {
10031 out.startTag(null, "rem");
10032 out.attribute(null, "pkg", pc.mPackageName);
10033 out.endTag(null, "rem");
10034 }
10035 }
10036 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010037 out.endTag(null, "item");
10038 }
10039 out.endTag(null, "daily-items");
10040 out.endDocument();
10041 }
10042
10043 private void writeDailyLevelSteps(XmlSerializer out, String tag, LevelStepTracker steps,
10044 StringBuilder tmpBuilder) throws IOException {
10045 if (steps != null) {
10046 out.startTag(null, tag);
10047 out.attribute(null, "n", Integer.toString(steps.mNumStepDurations));
10048 for (int i=0; i<steps.mNumStepDurations; i++) {
10049 out.startTag(null, "s");
10050 tmpBuilder.setLength(0);
10051 steps.encodeEntryAt(i, tmpBuilder);
10052 out.attribute(null, "v", tmpBuilder.toString());
10053 out.endTag(null, "s");
10054 }
10055 out.endTag(null, tag);
10056 }
10057 }
10058
10059 public void readDailyStatsLocked() {
10060 Slog.d(TAG, "Reading daily items from " + mDailyFile.getBaseFile());
10061 mDailyItems.clear();
10062 FileInputStream stream;
10063 try {
10064 stream = mDailyFile.openRead();
10065 } catch (FileNotFoundException e) {
10066 return;
10067 }
10068 try {
10069 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010010070 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010071 readDailyItemsLocked(parser);
10072 } catch (XmlPullParserException e) {
10073 } finally {
10074 try {
10075 stream.close();
10076 } catch (IOException e) {
10077 }
10078 }
10079 }
10080
10081 private void readDailyItemsLocked(XmlPullParser parser) {
10082 try {
10083 int type;
10084 while ((type = parser.next()) != XmlPullParser.START_TAG
10085 && type != XmlPullParser.END_DOCUMENT) {
10086 ;
10087 }
10088
10089 if (type != XmlPullParser.START_TAG) {
10090 throw new IllegalStateException("no start tag found");
10091 }
10092
10093 int outerDepth = parser.getDepth();
10094 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10095 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10096 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10097 continue;
10098 }
10099
10100 String tagName = parser.getName();
10101 if (tagName.equals("item")) {
10102 readDailyItemTagLocked(parser);
10103 } else {
10104 Slog.w(TAG, "Unknown element under <daily-items>: "
10105 + parser.getName());
10106 XmlUtils.skipCurrentTag(parser);
10107 }
10108 }
10109
10110 } catch (IllegalStateException e) {
10111 Slog.w(TAG, "Failed parsing daily " + e);
10112 } catch (NullPointerException e) {
10113 Slog.w(TAG, "Failed parsing daily " + e);
10114 } catch (NumberFormatException e) {
10115 Slog.w(TAG, "Failed parsing daily " + e);
10116 } catch (XmlPullParserException e) {
10117 Slog.w(TAG, "Failed parsing daily " + e);
10118 } catch (IOException e) {
10119 Slog.w(TAG, "Failed parsing daily " + e);
10120 } catch (IndexOutOfBoundsException e) {
10121 Slog.w(TAG, "Failed parsing daily " + e);
10122 }
10123 }
10124
10125 void readDailyItemTagLocked(XmlPullParser parser) throws NumberFormatException,
10126 XmlPullParserException, IOException {
10127 DailyItem dit = new DailyItem();
10128 String attr = parser.getAttributeValue(null, "start");
10129 if (attr != null) {
10130 dit.mStartTime = Long.parseLong(attr);
10131 }
10132 attr = parser.getAttributeValue(null, "end");
10133 if (attr != null) {
10134 dit.mEndTime = Long.parseLong(attr);
10135 }
10136 int outerDepth = parser.getDepth();
10137 int type;
10138 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10139 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10140 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10141 continue;
10142 }
10143
10144 String tagName = parser.getName();
10145 if (tagName.equals("dis")) {
10146 readDailyItemTagDetailsLocked(parser, dit, false, "dis");
10147 } else if (tagName.equals("chg")) {
10148 readDailyItemTagDetailsLocked(parser, dit, true, "chg");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010149 } else if (tagName.equals("upd")) {
10150 if (dit.mPackageChanges == null) {
10151 dit.mPackageChanges = new ArrayList<>();
10152 }
10153 PackageChange pc = new PackageChange();
10154 pc.mUpdate = true;
10155 pc.mPackageName = parser.getAttributeValue(null, "pkg");
10156 String verStr = parser.getAttributeValue(null, "ver");
Dianne Hackborn3accca02013-09-20 09:32:11 -070010157 pc.mVersionCode = verStr != null ? Long.parseLong(verStr) : 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010158 dit.mPackageChanges.add(pc);
10159 XmlUtils.skipCurrentTag(parser);
10160 } else if (tagName.equals("rem")) {
10161 if (dit.mPackageChanges == null) {
10162 dit.mPackageChanges = new ArrayList<>();
10163 }
10164 PackageChange pc = new PackageChange();
10165 pc.mUpdate = false;
10166 pc.mPackageName = parser.getAttributeValue(null, "pkg");
10167 dit.mPackageChanges.add(pc);
10168 XmlUtils.skipCurrentTag(parser);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010169 } else {
10170 Slog.w(TAG, "Unknown element under <item>: "
10171 + parser.getName());
10172 XmlUtils.skipCurrentTag(parser);
10173 }
10174 }
10175 mDailyItems.add(dit);
10176 }
10177
10178 void readDailyItemTagDetailsLocked(XmlPullParser parser, DailyItem dit, boolean isCharge,
10179 String tag)
10180 throws NumberFormatException, XmlPullParserException, IOException {
10181 final String numAttr = parser.getAttributeValue(null, "n");
10182 if (numAttr == null) {
10183 Slog.w(TAG, "Missing 'n' attribute at " + parser.getPositionDescription());
10184 XmlUtils.skipCurrentTag(parser);
10185 return;
10186 }
10187 final int num = Integer.parseInt(numAttr);
10188 LevelStepTracker steps = new LevelStepTracker(num);
10189 if (isCharge) {
10190 dit.mChargeSteps = steps;
10191 } else {
10192 dit.mDischargeSteps = steps;
10193 }
10194 int i = 0;
10195 int outerDepth = parser.getDepth();
10196 int type;
10197 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10198 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10199 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10200 continue;
10201 }
10202
10203 String tagName = parser.getName();
10204 if ("s".equals(tagName)) {
10205 if (i < num) {
10206 String valueAttr = parser.getAttributeValue(null, "v");
10207 if (valueAttr != null) {
10208 steps.decodeEntryAt(i, valueAttr);
10209 i++;
10210 }
10211 }
10212 } else {
10213 Slog.w(TAG, "Unknown element under <" + tag + ">: "
10214 + parser.getName());
10215 XmlUtils.skipCurrentTag(parser);
10216 }
10217 }
10218 steps.mNumStepDurations = i;
10219 }
10220
10221 @Override
10222 public DailyItem getDailyItemLocked(int daysAgo) {
10223 int index = mDailyItems.size()-1-daysAgo;
10224 return index >= 0 ? mDailyItems.get(index) : null;
10225 }
10226
10227 @Override
10228 public long getCurrentDailyStartTime() {
10229 return mDailyStartTime;
10230 }
10231
10232 @Override
10233 public long getNextMinDailyDeadline() {
10234 return mNextMinDailyDeadline;
10235 }
10236
10237 @Override
10238 public long getNextMaxDailyDeadline() {
10239 return mNextMaxDailyDeadline;
10240 }
10241
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010242 @Override
10243 public boolean startIteratingOldHistoryLocked() {
10244 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
10245 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010246 if ((mHistoryIterator = mHistory) == null) {
10247 return false;
10248 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010249 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010250 mHistoryReadTmp.clear();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010251 mReadOverflow = false;
10252 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010253 return true;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010254 }
10255
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010256 @Override
10257 public boolean getNextOldHistoryLocked(HistoryItem out) {
10258 boolean end = mHistoryBuffer.dataPosition() >= mHistoryBuffer.dataSize();
10259 if (!end) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010260 readHistoryDelta(mHistoryBuffer, mHistoryReadTmp);
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010261 mReadOverflow |= mHistoryReadTmp.cmd == HistoryItem.CMD_OVERFLOW;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010262 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010263 HistoryItem cur = mHistoryIterator;
10264 if (cur == null) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010265 if (!mReadOverflow && !end) {
10266 Slog.w(TAG, "Old history ends before new history!");
10267 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010268 return false;
10269 }
10270 out.setTo(cur);
10271 mHistoryIterator = cur.next;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010272 if (!mReadOverflow) {
10273 if (end) {
10274 Slog.w(TAG, "New history ends before old history!");
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010275 } else if (!out.same(mHistoryReadTmp)) {
Dianne Hackborn8c841092013-06-24 13:46:13 -070010276 PrintWriter pw = new FastPrintWriter(new LogWriter(android.util.Log.WARN, TAG));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010277 pw.println("Histories differ!");
10278 pw.println("Old history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010279 (new HistoryPrinter()).printNextItem(pw, out, 0, false, true);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010280 pw.println("New history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010281 (new HistoryPrinter()).printNextItem(pw, mHistoryReadTmp, 0, false,
10282 true);
Dianne Hackborn8c841092013-06-24 13:46:13 -070010283 pw.flush();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010284 }
10285 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010286 return true;
10287 }
10288
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010289 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010290 public void finishIteratingOldHistoryLocked() {
10291 mIteratingHistory = false;
10292 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010293 mHistoryIterator = null;
10294 }
10295
10296 public int getHistoryTotalSize() {
Hui Yu0ed84f12018-06-20 19:07:56 -070010297 return mConstants.MAX_HISTORY_BUFFER * mConstants.MAX_HISTORY_FILES;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010298 }
10299
10300 public int getHistoryUsedSize() {
Hui Yu0ed84f12018-06-20 19:07:56 -070010301 return mBatteryStatsHistory.getHistoryUsedSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010302 }
10303
10304 @Override
Mathew Inwoodaf972c82018-08-20 14:13:20 +010010305 @UnsupportedAppUsage
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010306 public boolean startIteratingHistoryLocked() {
Hui Yu0ed84f12018-06-20 19:07:56 -070010307 mBatteryStatsHistory.startIteratingHistory();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010308 mReadOverflow = false;
10309 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010310 mReadHistoryStrings = new String[mHistoryTagPool.size()];
10311 mReadHistoryUids = new int[mHistoryTagPool.size()];
10312 mReadHistoryChars = 0;
10313 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
10314 final HistoryTag tag = ent.getKey();
10315 final int idx = ent.getValue();
10316 mReadHistoryStrings[idx] = tag.string;
10317 mReadHistoryUids[idx] = tag.uid;
10318 mReadHistoryChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080010319 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010320 return true;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010321 }
10322
10323 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -080010324 public int getHistoryStringPoolSize() {
10325 return mReadHistoryStrings.length;
10326 }
10327
10328 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010329 public int getHistoryStringPoolBytes() {
10330 // Each entry is a fixed 12 bytes: 4 for index, 4 for uid, 4 for string size
10331 // Each string character is 2 bytes.
10332 return (mReadHistoryStrings.length * 12) + (mReadHistoryChars * 2);
10333 }
10334
10335 @Override
10336 public String getHistoryTagPoolString(int index) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080010337 return mReadHistoryStrings[index];
10338 }
10339
10340 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010341 public int getHistoryTagPoolUid(int index) {
10342 return mReadHistoryUids[index];
10343 }
10344
10345 @Override
Mathew Inwoodaf972c82018-08-20 14:13:20 +010010346 @UnsupportedAppUsage
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010347 public boolean getNextHistoryLocked(HistoryItem out) {
Hui Yu0ed84f12018-06-20 19:07:56 -070010348 Parcel p = mBatteryStatsHistory.getNextParcel(out);
10349 if (p == null) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010350 return false;
10351 }
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010352 final long lastRealtime = out.time;
10353 final long lastWalltime = out.currentTime;
Hui Yu0ed84f12018-06-20 19:07:56 -070010354 readHistoryDelta(p, out);
Dianne Hackborn37de0982014-05-09 09:32:18 -070010355 if (out.cmd != HistoryItem.CMD_CURRENT_TIME
10356 && out.cmd != HistoryItem.CMD_RESET && lastWalltime != 0) {
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010357 out.currentTime = lastWalltime + (out.time - lastRealtime);
10358 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010359 return true;
10360 }
10361
10362 @Override
10363 public void finishIteratingHistoryLocked() {
Hui Yu0ed84f12018-06-20 19:07:56 -070010364 mBatteryStatsHistory.finishIteratingHistory();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010365 mIteratingHistory = false;
Dianne Hackborn099bc622014-01-22 13:39:16 -080010366 mReadHistoryStrings = null;
Hui Yu0ed84f12018-06-20 19:07:56 -070010367 mReadHistoryUids = null;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010368 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010369
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010370 @Override
Dianne Hackbornb5e31652010-09-07 12:13:55 -070010371 public long getHistoryBaseTime() {
10372 return mHistoryBaseTime;
10373 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010374
Dianne Hackbornb5e31652010-09-07 12:13:55 -070010375 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010376 public int getStartCount() {
10377 return mStartCount;
10378 }
10379
Mathew Inwoodaf972c82018-08-20 14:13:20 +010010380 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010381 public boolean isOnBattery() {
10382 return mOnBattery;
10383 }
10384
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010385 public boolean isCharging() {
10386 return mCharging;
10387 }
10388
Mike Mac2f518a2017-09-19 16:06:03 -070010389 public boolean isScreenOn(int state) {
Chris Phoenix10a4a642017-09-25 13:21:00 -070010390 return state == Display.STATE_ON || state == Display.STATE_VR
10391 || state == Display.STATE_ON_SUSPEND;
Mike Mac2f518a2017-09-19 16:06:03 -070010392 }
10393
10394 public boolean isScreenOff(int state) {
10395 return state == Display.STATE_OFF;
10396 }
10397
10398 public boolean isScreenDoze(int state) {
10399 return state == Display.STATE_DOZE || state == Display.STATE_DOZE_SUSPEND;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010400 }
10401
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010402 void initTimes(long uptime, long realtime) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080010403 mStartClockTime = System.currentTimeMillis();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010404 mOnBatteryTimeBase.init(uptime, realtime);
10405 mOnBatteryScreenOffTimeBase.init(uptime, realtime);
Dianne Hackborn4590e522014-03-24 13:36:46 -070010406 mRealtime = 0;
10407 mUptime = 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010408 mRealtimeStart = realtime;
Dianne Hackborn4590e522014-03-24 13:36:46 -070010409 mUptimeStart = uptime;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010410 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010411
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010412 void initDischarge() {
10413 mLowDischargeAmountSinceCharge = 0;
10414 mHighDischargeAmountSinceCharge = 0;
10415 mDischargeAmountScreenOn = 0;
10416 mDischargeAmountScreenOnSinceCharge = 0;
10417 mDischargeAmountScreenOff = 0;
10418 mDischargeAmountScreenOffSinceCharge = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010419 mDischargeAmountScreenDoze = 0;
10420 mDischargeAmountScreenDozeSinceCharge = 0;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010421 mDischargeStepTracker.init();
10422 mChargeStepTracker.init();
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010423 mDischargeScreenOffCounter.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -070010424 mDischargeScreenDozeCounter.reset(false);
Mike Ma15313c92017-11-15 17:58:21 -080010425 mDischargeLightDozeCounter.reset(false);
10426 mDischargeDeepDozeCounter.reset(false);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010427 mDischargeCounter.reset(false);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010428 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010429
10430 public void resetAllStatsCmdLocked() {
10431 resetAllStatsLocked();
Joe Onoratoabded112016-02-08 16:49:39 -080010432 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -070010433 long uptime = mSecUptime * 1000;
Joe Onoratoabded112016-02-08 16:49:39 -080010434 long mSecRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010435 long realtime = mSecRealtime * 1000;
10436 mDischargeStartLevel = mHistoryCur.batteryLevel;
10437 pullPendingStateUpdatesLocked();
Dianne Hackborn40c87252014-03-19 16:55:40 -070010438 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010439 mDischargeCurrentLevel = mDischargeUnplugLevel = mDischargePlugLevel
10440 = mCurrentBatteryLevel = mHistoryCur.batteryLevel;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010441 mOnBatteryTimeBase.reset(uptime, realtime);
10442 mOnBatteryScreenOffTimeBase.reset(uptime, realtime);
10443 if ((mHistoryCur.states&HistoryItem.STATE_BATTERY_PLUGGED_FLAG) == 0) {
Mike Mac2f518a2017-09-19 16:06:03 -070010444 if (isScreenOn(mScreenState)) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010445 mDischargeScreenOnUnplugLevel = mHistoryCur.batteryLevel;
Mike Mac2f518a2017-09-19 16:06:03 -070010446 mDischargeScreenDozeUnplugLevel = 0;
10447 mDischargeScreenOffUnplugLevel = 0;
10448 } else if (isScreenDoze(mScreenState)) {
10449 mDischargeScreenOnUnplugLevel = 0;
10450 mDischargeScreenDozeUnplugLevel = mHistoryCur.batteryLevel;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010451 mDischargeScreenOffUnplugLevel = 0;
10452 } else {
10453 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010454 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010455 mDischargeScreenOffUnplugLevel = mHistoryCur.batteryLevel;
10456 }
10457 mDischargeAmountScreenOn = 0;
10458 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010459 mDischargeAmountScreenDoze = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010460 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070010461 initActiveHistoryEventsLocked(mSecRealtime, mSecUptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010462 }
10463
10464 private void resetAllStatsLocked() {
Adam Lesinski8ce36942016-05-26 16:05:35 -070010465 final long uptimeMillis = mClocks.uptimeMillis();
10466 final long elapsedRealtimeMillis = mClocks.elapsedRealtime();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010467 mStartCount = 0;
Adam Lesinski8ce36942016-05-26 16:05:35 -070010468 initTimes(uptimeMillis * 1000, elapsedRealtimeMillis * 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010469 mScreenOnTimer.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -070010470 mScreenDozeTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010471 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010472 mScreenBrightnessTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010473 }
Adam Lesinski1a76a622016-06-22 10:28:47 -070010474
10475 if (mPowerProfile != null) {
10476 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
10477 } else {
10478 mEstimatedBatteryCapacity = -1;
10479 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070010480 mMinLearnedBatteryCapacity = -1;
10481 mMaxLearnedBatteryCapacity = -1;
Jeff Browne95c3cd2014-05-02 16:59:26 -070010482 mInteractiveTimer.reset(false);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070010483 mPowerSaveModeEnabledTimer.reset(false);
Adam Lesinski8ce36942016-05-26 16:05:35 -070010484 mLastIdleTimeStart = elapsedRealtimeMillis;
Dianne Hackborn08c47a52015-10-15 12:38:14 -070010485 mLongestLightIdleTime = 0;
10486 mLongestFullIdleTime = 0;
10487 mDeviceIdleModeLightTimer.reset(false);
10488 mDeviceIdleModeFullTimer.reset(false);
10489 mDeviceLightIdlingTimer.reset(false);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010490 mDeviceIdlingTimer.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010491 mPhoneOnTimer.reset(false);
10492 mAudioOnTimer.reset(false);
10493 mVideoOnTimer.reset(false);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070010494 mFlashlightOnTimer.reset(false);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070010495 mCameraOnTimer.reset(false);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010496 mBluetoothScanTimer.reset(false);
Wink Saville52840902011-02-18 12:40:47 -080010497 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010498 mPhoneSignalStrengthsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010499 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010500 mPhoneSignalScanningTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010501 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010502 mPhoneDataConnectionsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010503 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010504 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010505 mNetworkByteActivityCounters[i].reset(false);
10506 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010507 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010508 mMobileRadioActiveTimer.reset(false);
10509 mMobileRadioActivePerAppTimer.reset(false);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010510 mMobileRadioActiveAdjustedTime.reset(false);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080010511 mMobileRadioActiveUnknownTime.reset(false);
10512 mMobileRadioActiveUnknownCount.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010513 mWifiOnTimer.reset(false);
10514 mGlobalWifiRunningTimer.reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010515 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010516 mWifiStateTimer[i].reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010517 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070010518 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
10519 mWifiSupplStateTimer[i].reset(false);
10520 }
10521 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
10522 mWifiSignalStrengthsTimer[i].reset(false);
10523 }
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080010524 mWifiMulticastWakelockTimer.reset(false);
Siddharth Rayb50a6842017-12-14 15:15:28 -080010525 mWifiActiveTimer.reset(false);
10526 mWifiActivity.reset(false);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080010527 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
10528 mGpsSignalQualityTimer[i].reset(false);
10529 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010530 mBluetoothActivity.reset(false);
10531 mModemActivity.reset(false);
Mike Ma99e57c32018-03-15 14:40:37 -070010532 mNumConnectivityChange = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010533
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010534 for (int i=0; i<mUidStats.size(); i++) {
Bookatz993a0be2017-07-21 09:03:23 -070010535 if (mUidStats.valueAt(i).reset(uptimeMillis * 1000, elapsedRealtimeMillis * 1000)) {
Hui Yu8e88e952018-07-23 17:59:59 -070010536 mUidStats.valueAt(i).detachFromTimeBase();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010537 mUidStats.remove(mUidStats.keyAt(i));
10538 i--;
10539 }
10540 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010541
Bookatz50df7112017-08-04 14:53:26 -070010542 if (mRpmStats.size() > 0) {
10543 for (SamplingTimer timer : mRpmStats.values()) {
10544 mOnBatteryTimeBase.remove(timer);
10545 }
10546 mRpmStats.clear();
10547 }
10548 if (mScreenOffRpmStats.size() > 0) {
10549 for (SamplingTimer timer : mScreenOffRpmStats.values()) {
10550 mOnBatteryScreenOffTimeBase.remove(timer);
10551 }
10552 mScreenOffRpmStats.clear();
10553 }
10554
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010555 if (mKernelWakelockStats.size() > 0) {
10556 for (SamplingTimer timer : mKernelWakelockStats.values()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010557 mOnBatteryScreenOffTimeBase.remove(timer);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010558 }
10559 mKernelWakelockStats.clear();
10560 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010561
James Carr3a226052016-07-01 14:49:52 -070010562 if (mKernelMemoryStats.size() > 0) {
10563 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
10564 mOnBatteryTimeBase.remove(mKernelMemoryStats.valueAt(i));
10565 }
10566 mKernelMemoryStats.clear();
10567 }
10568
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010569 if (mWakeupReasonStats.size() > 0) {
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070010570 for (SamplingTimer timer : mWakeupReasonStats.values()) {
10571 mOnBatteryTimeBase.remove(timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010572 }
10573 mWakeupReasonStats.clear();
10574 }
10575
Blake Kragtencb308d92019-01-28 10:54:13 -080010576 mTmpRailStats.reset();
10577
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080010578 mLastHistoryStepDetails = null;
10579 mLastStepCpuUserTime = mLastStepCpuSystemTime = 0;
10580 mCurStepCpuUserTime = mCurStepCpuSystemTime = 0;
10581 mLastStepCpuUserTime = mCurStepCpuUserTime = 0;
10582 mLastStepCpuSystemTime = mCurStepCpuSystemTime = 0;
10583 mLastStepStatUserTime = mCurStepStatUserTime = 0;
10584 mLastStepStatSystemTime = mCurStepStatSystemTime = 0;
10585 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime = 0;
10586 mLastStepStatIrqTime = mCurStepStatIrqTime = 0;
10587 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime = 0;
10588 mLastStepStatIdleTime = mCurStepStatIdleTime = 0;
10589
Mike Ma234d1822018-03-13 18:53:21 -070010590 mNumAllUidCpuTimeReads = 0;
10591 mNumUidsRemoved = 0;
10592
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010593 initDischarge();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010594
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010595 clearHistoryLocked();
Hui Yu0ed84f12018-06-20 19:07:56 -070010596 mBatteryStatsHistory.resetAllFiles();
10597
Fyodor Kupolov8aa51242018-04-23 12:44:51 -070010598 mHandler.sendEmptyMessage(MSG_REPORT_RESET_STATS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010599 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010600
Dianne Hackborn40c87252014-03-19 16:55:40 -070010601 private void initActiveHistoryEventsLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010602 for (int i=0; i<HistoryItem.EVENT_COUNT; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010603 if (!mRecordAllHistory && i == HistoryItem.EVENT_PROC) {
10604 // Not recording process starts/stops.
10605 continue;
10606 }
Dianne Hackborn37de0982014-05-09 09:32:18 -070010607 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(i);
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010608 if (active == null) {
10609 continue;
10610 }
Dianne Hackborn37de0982014-05-09 09:32:18 -070010611 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
10612 SparseIntArray uids = ent.getValue();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010613 for (int j=0; j<uids.size(); j++) {
Dianne Hackborn37de0982014-05-09 09:32:18 -070010614 addHistoryEventLocked(elapsedRealtimeMs, uptimeMs, i, ent.getKey(),
10615 uids.keyAt(j));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010616 }
10617 }
10618 }
10619 }
10620
Mike Mac2f518a2017-09-19 16:06:03 -070010621 void updateDischargeScreenLevelsLocked(int oldState, int newState) {
10622 updateOldDischargeScreenLevelLocked(oldState);
10623 updateNewDischargeScreenLevelLocked(newState);
10624 }
10625
10626 private void updateOldDischargeScreenLevelLocked(int state) {
10627 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010628 int diff = mDischargeScreenOnUnplugLevel - mDischargeCurrentLevel;
10629 if (diff > 0) {
10630 mDischargeAmountScreenOn += diff;
10631 mDischargeAmountScreenOnSinceCharge += diff;
10632 }
Mike Mac2f518a2017-09-19 16:06:03 -070010633 } else if (isScreenDoze(state)) {
10634 int diff = mDischargeScreenDozeUnplugLevel - mDischargeCurrentLevel;
10635 if (diff > 0) {
10636 mDischargeAmountScreenDoze += diff;
10637 mDischargeAmountScreenDozeSinceCharge += diff;
10638 }
10639 } else if (isScreenOff(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010640 int diff = mDischargeScreenOffUnplugLevel - mDischargeCurrentLevel;
10641 if (diff > 0) {
10642 mDischargeAmountScreenOff += diff;
10643 mDischargeAmountScreenOffSinceCharge += diff;
10644 }
10645 }
Mike Mac2f518a2017-09-19 16:06:03 -070010646 }
10647
10648 private void updateNewDischargeScreenLevelLocked(int state) {
10649 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010650 mDischargeScreenOnUnplugLevel = mDischargeCurrentLevel;
10651 mDischargeScreenOffUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010652 mDischargeScreenDozeUnplugLevel = 0;
10653 } else if (isScreenDoze(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010654 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010655 mDischargeScreenDozeUnplugLevel = mDischargeCurrentLevel;
10656 mDischargeScreenOffUnplugLevel = 0;
10657 } else if (isScreenOff(state)) {
10658 mDischargeScreenOnUnplugLevel = 0;
10659 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010660 mDischargeScreenOffUnplugLevel = mDischargeCurrentLevel;
10661 }
10662 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010663
Dianne Hackborna7c837f2014-01-15 16:20:44 -080010664 public void pullPendingStateUpdatesLocked() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -080010665 if (mOnBatteryInternal) {
Mike Mac2f518a2017-09-19 16:06:03 -070010666 updateDischargeScreenLevelsLocked(mScreenState, mScreenState);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080010667 }
Dianne Hackborna7c837f2014-01-15 16:20:44 -080010668 }
10669
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010670 private final Pools.Pool<NetworkStats> mNetworkStatsPool = new Pools.SynchronizedPool<>(6);
10671
10672 private final Object mWifiNetworkLock = new Object();
10673
10674 @GuardedBy("mWifiNetworkLock")
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010675 private String[] mWifiIfaces = EmptyArray.STRING;
10676
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010677 @GuardedBy("mWifiNetworkLock")
10678 private NetworkStats mLastWifiNetworkStats = new NetworkStats(0, -1);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010679
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010680 private final Object mModemNetworkLock = new Object();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010681
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010682 @GuardedBy("mModemNetworkLock")
10683 private String[] mModemIfaces = EmptyArray.STRING;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010684
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010685 @GuardedBy("mModemNetworkLock")
10686 private NetworkStats mLastModemNetworkStats = new NetworkStats(0, -1);
10687
10688 private NetworkStats readNetworkStatsLocked(String[] ifaces) {
10689 try {
10690 if (!ArrayUtils.isEmpty(ifaces)) {
Chenbo Fenge62e2872019-01-11 15:50:17 -080010691 INetworkStatsService statsService = INetworkStatsService.Stub.asInterface(
10692 ServiceManager.getService(Context.NETWORK_STATS_SERVICE));
10693 if (statsService != null) {
10694 return statsService.getDetailedUidStats(ifaces);
10695 } else {
10696 Slog.e(TAG, "Failed to get networkStatsService ");
10697 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010698 }
Chenbo Fenge62e2872019-01-11 15:50:17 -080010699 } catch (RemoteException e) {
10700 Slog.e(TAG, "failed to read network stats for ifaces: " + Arrays.toString(ifaces) + e);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010701 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010702 return null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010703 }
10704
Chenjie Yu89083392018-01-11 14:53:31 -080010705 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010706 * Distribute WiFi energy info and network traffic to apps.
10707 * @param info The energy information from the WiFi controller.
10708 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010709 public void updateWifiState(@Nullable final WifiActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070010710 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010711 Slog.d(TAG, "Updating wifi stats: " + Arrays.toString(mWifiIfaces));
Adam Lesinskia7c90c82015-06-18 14:52:24 -070010712 }
10713
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010714 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070010715 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010716 synchronized (mWifiNetworkLock) {
10717 final NetworkStats latestStats = readNetworkStatsLocked(mWifiIfaces);
10718 if (latestStats != null) {
10719 delta = NetworkStats.subtract(latestStats, mLastWifiNetworkStats, null, null,
10720 mNetworkStatsPool.acquire());
10721 mNetworkStatsPool.release(mLastWifiNetworkStats);
10722 mLastWifiNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070010723 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010724 }
10725
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010726 synchronized (this) {
10727 if (!mOnBatteryInternal) {
10728 if (delta != null) {
10729 mNetworkStatsPool.release(delta);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010730 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010731 return;
10732 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010733
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010734 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
10735 SparseLongArray rxPackets = new SparseLongArray();
10736 SparseLongArray txPackets = new SparseLongArray();
10737 long totalTxPackets = 0;
10738 long totalRxPackets = 0;
10739 if (delta != null) {
10740 NetworkStats.Entry entry = new NetworkStats.Entry();
10741 final int size = delta.size();
10742 for (int i = 0; i < size; i++) {
10743 entry = delta.getValues(i, entry);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010744
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010745 if (DEBUG_ENERGY) {
10746 Slog.d(TAG, "Wifi uid " + entry.uid + ": delta rx=" + entry.rxBytes
10747 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
10748 + " txPackets=" + entry.txPackets);
10749 }
10750
10751 if (entry.rxBytes == 0 && entry.txBytes == 0) {
10752 // Skip the lookup below since there is no work to do.
10753 continue;
10754 }
10755
10756 final Uid u = getUidStatsLocked(mapUid(entry.uid));
10757 if (entry.rxBytes != 0) {
10758 u.noteNetworkActivityLocked(NETWORK_WIFI_RX_DATA, entry.rxBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -080010759 entry.rxPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010760 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
10761 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_RX_DATA, entry.rxBytes,
10762 entry.rxPackets);
10763 }
10764 mNetworkByteActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
10765 entry.rxBytes);
10766 mNetworkPacketActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
10767 entry.rxPackets);
10768
10769 rxPackets.put(u.getUid(), entry.rxPackets);
10770
10771 // Sum the total number of packets so that the Rx Power can
10772 // be evenly distributed amongst the apps.
10773 totalRxPackets += entry.rxPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -080010774 }
Adam Lesinskie08af192015-03-25 16:42:59 -070010775
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010776 if (entry.txBytes != 0) {
10777 u.noteNetworkActivityLocked(NETWORK_WIFI_TX_DATA, entry.txBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -080010778 entry.txPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010779 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
10780 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_TX_DATA, entry.txBytes,
10781 entry.txPackets);
10782 }
10783 mNetworkByteActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
10784 entry.txBytes);
10785 mNetworkPacketActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
10786 entry.txPackets);
10787
10788 txPackets.put(u.getUid(), entry.txPackets);
10789
10790 // Sum the total number of packets so that the Tx Power can
10791 // be evenly distributed amongst the apps.
10792 totalTxPackets += entry.txPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -080010793 }
Adam Lesinskiba88e682015-12-08 12:06:55 -080010794 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010795 mNetworkStatsPool.release(delta);
10796 delta = null;
Adam Lesinskie08af192015-03-25 16:42:59 -070010797 }
10798
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010799 if (info != null) {
10800 mHasWifiReporting = true;
Adam Lesinskie08af192015-03-25 16:42:59 -070010801
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010802 // Measured in mAms
10803 final long txTimeMs = info.getControllerTxTimeMillis();
10804 final long rxTimeMs = info.getControllerRxTimeMillis();
Siddharth Rayb50a6842017-12-14 15:15:28 -080010805 final long scanTimeMs = info.getControllerScanTimeMillis();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010806 final long idleTimeMs = info.getControllerIdleTimeMillis();
10807 final long totalTimeMs = txTimeMs + rxTimeMs + idleTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -070010808
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010809 long leftOverRxTimeMs = rxTimeMs;
10810 long leftOverTxTimeMs = txTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -070010811
Adam Lesinskie08af192015-03-25 16:42:59 -070010812 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010813 Slog.d(TAG, "------ BEGIN WiFi power blaming ------");
10814 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
10815 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
10816 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms");
10817 Slog.d(TAG, " Total Time: " + totalTimeMs + " ms");
Siddharth Rayb50a6842017-12-14 15:15:28 -080010818 Slog.d(TAG, " Scan Time: " + scanTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070010819 }
Adam Lesinskie08af192015-03-25 16:42:59 -070010820
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010821 long totalWifiLockTimeMs = 0;
10822 long totalScanTimeMs = 0;
10823
10824 // On the first pass, collect some totals so that we can normalize power
10825 // calculations if we need to.
10826 final int uidStatsSize = mUidStats.size();
10827 for (int i = 0; i < uidStatsSize; i++) {
10828 final Uid uid = mUidStats.valueAt(i);
10829
10830 // Sum the total scan power for all apps.
10831 totalScanTimeMs += uid.mWifiScanTimer.getTimeSinceMarkLocked(
10832 elapsedRealtimeMs * 1000) / 1000;
10833
10834 // Sum the total time holding wifi lock for all apps.
10835 totalWifiLockTimeMs += uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
10836 elapsedRealtimeMs * 1000) / 1000;
10837 }
10838
10839 if (DEBUG_ENERGY && totalScanTimeMs > rxTimeMs) {
10840 Slog.d(TAG,
10841 " !Estimated scan time > Actual rx time (" + totalScanTimeMs + " ms > "
10842 + rxTimeMs + " ms). Normalizing scan time.");
10843 }
10844 if (DEBUG_ENERGY && totalScanTimeMs > txTimeMs) {
10845 Slog.d(TAG,
10846 " !Estimated scan time > Actual tx time (" + totalScanTimeMs + " ms > "
10847 + txTimeMs + " ms). Normalizing scan time.");
10848 }
10849
10850 // Actually assign and distribute power usage to apps.
10851 for (int i = 0; i < uidStatsSize; i++) {
10852 final Uid uid = mUidStats.valueAt(i);
10853
10854 long scanTimeSinceMarkMs = uid.mWifiScanTimer.getTimeSinceMarkLocked(
10855 elapsedRealtimeMs * 1000) / 1000;
10856 if (scanTimeSinceMarkMs > 0) {
10857 // Set the new mark so that next time we get new data since this point.
10858 uid.mWifiScanTimer.setMark(elapsedRealtimeMs);
10859
10860 long scanRxTimeSinceMarkMs = scanTimeSinceMarkMs;
10861 long scanTxTimeSinceMarkMs = scanTimeSinceMarkMs;
10862
10863 // Our total scan time is more than the reported Tx/Rx time.
10864 // This is possible because the cost of a scan is approximate.
10865 // Let's normalize the result so that we evenly blame each app
10866 // scanning.
10867 //
10868 // This means that we may have apps that transmitted/received packets not be
10869 // blamed for this, but this is fine as scans are relatively more expensive.
10870 if (totalScanTimeMs > rxTimeMs) {
10871 scanRxTimeSinceMarkMs = (rxTimeMs * scanRxTimeSinceMarkMs) /
10872 totalScanTimeMs;
10873 }
10874 if (totalScanTimeMs > txTimeMs) {
10875 scanTxTimeSinceMarkMs = (txTimeMs * scanTxTimeSinceMarkMs) /
10876 totalScanTimeMs;
10877 }
10878
10879 if (DEBUG_ENERGY) {
10880 Slog.d(TAG, " ScanTime for UID " + uid.getUid() + ": Rx:"
10881 + scanRxTimeSinceMarkMs + " ms Tx:"
10882 + scanTxTimeSinceMarkMs + " ms)");
10883 }
10884
10885 ControllerActivityCounterImpl activityCounter =
10886 uid.getOrCreateWifiControllerActivityLocked();
10887 activityCounter.getRxTimeCounter().addCountLocked(scanRxTimeSinceMarkMs);
10888 activityCounter.getTxTimeCounters()[0].addCountLocked(
10889 scanTxTimeSinceMarkMs);
10890 leftOverRxTimeMs -= scanRxTimeSinceMarkMs;
10891 leftOverTxTimeMs -= scanTxTimeSinceMarkMs;
10892 }
10893
10894 // Distribute evenly the power consumed while Idle to each app holding a WiFi
10895 // lock.
10896 final long wifiLockTimeSinceMarkMs =
10897 uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
10898 elapsedRealtimeMs * 1000) / 1000;
10899 if (wifiLockTimeSinceMarkMs > 0) {
10900 // Set the new mark so that next time we get new data since this point.
10901 uid.mFullWifiLockTimer.setMark(elapsedRealtimeMs);
10902
10903 final long myIdleTimeMs = (wifiLockTimeSinceMarkMs * idleTimeMs)
10904 / totalWifiLockTimeMs;
10905 if (DEBUG_ENERGY) {
10906 Slog.d(TAG, " IdleTime for UID " + uid.getUid() + ": "
10907 + myIdleTimeMs + " ms");
10908 }
10909 uid.getOrCreateWifiControllerActivityLocked().getIdleTimeCounter()
10910 .addCountLocked(myIdleTimeMs);
10911 }
10912 }
10913
Adam Lesinskie08af192015-03-25 16:42:59 -070010914 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010915 Slog.d(TAG, " New RxPower: " + leftOverRxTimeMs + " ms");
10916 Slog.d(TAG, " New TxPower: " + leftOverTxTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070010917 }
Adam Lesinskie08af192015-03-25 16:42:59 -070010918
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010919 // Distribute the remaining Tx power appropriately between all apps that transmitted
10920 // packets.
10921 for (int i = 0; i < txPackets.size(); i++) {
10922 final Uid uid = getUidStatsLocked(txPackets.keyAt(i));
10923 final long myTxTimeMs = (txPackets.valueAt(i) * leftOverTxTimeMs)
10924 / totalTxPackets;
10925 if (DEBUG_ENERGY) {
10926 Slog.d(TAG, " TxTime for UID " + uid.getUid() + ": " + myTxTimeMs + " ms");
10927 }
10928 uid.getOrCreateWifiControllerActivityLocked().getTxTimeCounters()[0]
10929 .addCountLocked(myTxTimeMs);
10930 }
Adam Lesinskie08af192015-03-25 16:42:59 -070010931
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010932 // Distribute the remaining Rx power appropriately between all apps that received
10933 // packets.
10934 for (int i = 0; i < rxPackets.size(); i++) {
10935 final Uid uid = getUidStatsLocked(rxPackets.keyAt(i));
10936 final long myRxTimeMs = (rxPackets.valueAt(i) * leftOverRxTimeMs)
10937 / totalRxPackets;
10938 if (DEBUG_ENERGY) {
10939 Slog.d(TAG, " RxTime for UID " + uid.getUid() + ": " + myRxTimeMs + " ms");
10940 }
10941 uid.getOrCreateWifiControllerActivityLocked().getRxTimeCounter()
10942 .addCountLocked(myRxTimeMs);
10943 }
Adam Lesinskie08af192015-03-25 16:42:59 -070010944
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010945 // Any left over power use will be picked up by the WiFi category in BatteryStatsHelper.
10946
10947
10948 // Update WiFi controller stats.
10949 mWifiActivity.getRxTimeCounter().addCountLocked(info.getControllerRxTimeMillis());
10950 mWifiActivity.getTxTimeCounters()[0].addCountLocked(
10951 info.getControllerTxTimeMillis());
Siddharth Rayb50a6842017-12-14 15:15:28 -080010952 mWifiActivity.getScanTimeCounter().addCountLocked(
10953 info.getControllerScanTimeMillis());
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010954 mWifiActivity.getIdleTimeCounter().addCountLocked(
10955 info.getControllerIdleTimeMillis());
10956
10957 // POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
10958 final double opVolt = mPowerProfile.getAveragePower(
10959 PowerProfile.POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
10960 if (opVolt != 0) {
10961 // We store the power drain as mAms.
10962 mWifiActivity.getPowerCounter().addCountLocked(
10963 (long) (info.getControllerEnergyUsed() / opVolt));
10964 }
Blake Kragtencb308d92019-01-28 10:54:13 -080010965 // Converting uWs to mAms.
10966 // Conversion: (uWs * (1000ms / 1s) * (1mW / 1000uW)) / mV = mAms
10967 long monitoredRailChargeConsumedMaMs =
10968 (long) (mTmpRailStats.getWifiTotalEnergyUseduWs() / opVolt);
10969 mWifiActivity.getMonitoredRailChargeConsumedMaMs().addCountLocked(
10970 monitoredRailChargeConsumedMaMs);
10971 mHistoryCur.wifiRailChargeMah +=
10972 (monitoredRailChargeConsumedMaMs / MILLISECONDS_IN_HOUR);
10973 addHistoryRecordLocked(mClocks.elapsedRealtime(), mClocks.uptimeMillis());
10974 mTmpRailStats.resetWifiTotalEnergyUsed();
Adam Lesinskie08af192015-03-25 16:42:59 -070010975 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010976 }
10977 }
10978
Chenjie Yu89083392018-01-11 14:53:31 -080010979 private ModemActivityInfo mLastModemActivityInfo =
Chen Xu7322e4a2019-09-07 15:51:22 -070010980 new ModemActivityInfo(0, 0, 0, new int[0], 0);
Chenjie Yu89083392018-01-11 14:53:31 -080010981
Chenjie Yua54e54d2018-02-14 20:12:52 -080010982 private ModemActivityInfo getDeltaModemActivityInfo(ModemActivityInfo activityInfo) {
10983 if (activityInfo == null) {
10984 return null;
10985 }
10986 int[] txTimeMs = new int[ModemActivityInfo.TX_POWER_LEVELS];
10987 for (int i = 0; i < ModemActivityInfo.TX_POWER_LEVELS; i++) {
Chen Xu7322e4a2019-09-07 15:51:22 -070010988 txTimeMs[i] = activityInfo.getTransmitPowerInfo().get(i).getTimeInMillis()
10989 - mLastModemActivityInfo.getTransmitPowerInfo().get(i).getTimeInMillis();
Chenjie Yua54e54d2018-02-14 20:12:52 -080010990 }
10991 ModemActivityInfo deltaInfo = new ModemActivityInfo(activityInfo.getTimestamp(),
10992 activityInfo.getSleepTimeMillis() - mLastModemActivityInfo.getSleepTimeMillis(),
10993 activityInfo.getIdleTimeMillis() - mLastModemActivityInfo.getIdleTimeMillis(),
10994 txTimeMs,
Chen Xu7322e4a2019-09-07 15:51:22 -070010995 activityInfo.getReceiveTimeMillis() - mLastModemActivityInfo.getReceiveTimeMillis());
Chenjie Yua54e54d2018-02-14 20:12:52 -080010996 mLastModemActivityInfo = activityInfo;
10997 return deltaInfo;
10998 }
10999
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011000 /**
11001 * Distribute Cell radio energy info and network traffic to apps.
11002 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011003 public void updateMobileRadioState(@Nullable final ModemActivityInfo activityInfo) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011004 if (DEBUG_ENERGY) {
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011005 Slog.d(TAG, "Updating mobile radio stats with " + activityInfo);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011006 }
Chenjie Yua54e54d2018-02-14 20:12:52 -080011007 ModemActivityInfo deltaInfo = getDeltaModemActivityInfo(activityInfo);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011008
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011009 // Add modem tx power to history.
Chenjie Yua54e54d2018-02-14 20:12:52 -080011010 addModemTxPowerToHistory(deltaInfo);
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011011
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011012 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070011013 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011014 synchronized (mModemNetworkLock) {
11015 final NetworkStats latestStats = readNetworkStatsLocked(mModemIfaces);
11016 if (latestStats != null) {
11017 delta = NetworkStats.subtract(latestStats, mLastModemNetworkStats, null, null,
11018 mNetworkStatsPool.acquire());
11019 mNetworkStatsPool.release(mLastModemNetworkStats);
11020 mLastModemNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070011021 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011022 }
11023
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011024 synchronized (this) {
11025 if (!mOnBatteryInternal) {
11026 if (delta != null) {
11027 mNetworkStatsPool.release(delta);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011028 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011029 return;
Adam Lesinskie08af192015-03-25 16:42:59 -070011030 }
11031
Chenjie Yua54e54d2018-02-14 20:12:52 -080011032 if (deltaInfo != null) {
Siddharth Ray2038af82018-01-17 17:40:26 -080011033 mHasModemReporting = true;
11034 mModemActivity.getIdleTimeCounter().addCountLocked(
Chenjie Yua54e54d2018-02-14 20:12:52 -080011035 deltaInfo.getIdleTimeMillis());
Siddharth Rayed754702018-02-15 12:44:37 -080011036 mModemActivity.getSleepTimeCounter().addCountLocked(
11037 deltaInfo.getSleepTimeMillis());
Chen Xu7322e4a2019-09-07 15:51:22 -070011038 mModemActivity.getRxTimeCounter().addCountLocked(deltaInfo.getReceiveTimeMillis());
Siddharth Ray2038af82018-01-17 17:40:26 -080011039 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
11040 mModemActivity.getTxTimeCounters()[lvl]
Chen Xu7322e4a2019-09-07 15:51:22 -070011041 .addCountLocked(deltaInfo.getTransmitPowerInfo()
11042 .get(lvl).getTimeInMillis());
Siddharth Ray2038af82018-01-17 17:40:26 -080011043 }
11044
11045 // POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11046 final double opVolt = mPowerProfile.getAveragePower(
11047 PowerProfile.POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11048 if (opVolt != 0) {
11049 double energyUsed =
Chenjie Yua54e54d2018-02-14 20:12:52 -080011050 deltaInfo.getSleepTimeMillis() *
Siddharth Ray2038af82018-01-17 17:40:26 -080011051 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_SLEEP)
Chenjie Yua54e54d2018-02-14 20:12:52 -080011052 + deltaInfo.getIdleTimeMillis() *
Siddharth Ray2038af82018-01-17 17:40:26 -080011053 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_IDLE)
Chen Xu7322e4a2019-09-07 15:51:22 -070011054 + deltaInfo.getReceiveTimeMillis() *
Siddharth Ray2038af82018-01-17 17:40:26 -080011055 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_RX);
Chen Xu7322e4a2019-09-07 15:51:22 -070011056 List<TransmitPower> txPowerInfo = deltaInfo.getTransmitPowerInfo();
11057 for (int i = 0; i < Math.min(txPowerInfo.size(),
Chenjie Yua54e54d2018-02-14 20:12:52 -080011058 SignalStrength.NUM_SIGNAL_STRENGTH_BINS); i++) {
Chen Xu7322e4a2019-09-07 15:51:22 -070011059 energyUsed += txPowerInfo.get(i).getTimeInMillis() * mPowerProfile
11060 .getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_TX, i);
Siddharth Ray2038af82018-01-17 17:40:26 -080011061 }
11062
11063 // We store the power drain as mAms.
11064 mModemActivity.getPowerCounter().addCountLocked((long) energyUsed);
Blake Kragtencb308d92019-01-28 10:54:13 -080011065 // Converting uWs to mAms.
11066 // Conversion: (uWs * (1000ms / 1s) * (1mW / 1000uW)) / mV = mAms
11067 long monitoredRailChargeConsumedMaMs =
11068 (long) (mTmpRailStats.getCellularTotalEnergyUseduWs() / opVolt);
11069 mModemActivity.getMonitoredRailChargeConsumedMaMs().addCountLocked(
11070 monitoredRailChargeConsumedMaMs);
11071 mHistoryCur.modemRailChargeMah +=
11072 (monitoredRailChargeConsumedMaMs / MILLISECONDS_IN_HOUR);
11073 addHistoryRecordLocked(mClocks.elapsedRealtime(), mClocks.uptimeMillis());
11074 mTmpRailStats.resetCellularTotalEnergyUsed();
Siddharth Ray2038af82018-01-17 17:40:26 -080011075 }
11076 }
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070011077 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011078 long radioTime = mMobileRadioActivePerAppTimer.getTimeSinceMarkLocked(
11079 elapsedRealtimeMs * 1000);
11080 mMobileRadioActivePerAppTimer.setMark(elapsedRealtimeMs);
11081
11082 long totalRxPackets = 0;
11083 long totalTxPackets = 0;
11084 if (delta != null) {
11085 NetworkStats.Entry entry = new NetworkStats.Entry();
11086 final int size = delta.size();
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011087 for (int i = 0; i < size; i++) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011088 entry = delta.getValues(i, entry);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011089 if (entry.rxPackets == 0 && entry.txPackets == 0) {
11090 continue;
11091 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011092
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011093 if (DEBUG_ENERGY) {
11094 Slog.d(TAG, "Mobile uid " + entry.uid + ": delta rx=" + entry.rxBytes
11095 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
11096 + " txPackets=" + entry.txPackets);
11097 }
11098
11099 totalRxPackets += entry.rxPackets;
11100 totalTxPackets += entry.txPackets;
11101
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011102 final Uid u = getUidStatsLocked(mapUid(entry.uid));
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011103 u.noteNetworkActivityLocked(NETWORK_MOBILE_RX_DATA, entry.rxBytes,
11104 entry.rxPackets);
11105 u.noteNetworkActivityLocked(NETWORK_MOBILE_TX_DATA, entry.txBytes,
11106 entry.txPackets);
11107 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11108 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_RX_DATA,
11109 entry.rxBytes, entry.rxPackets);
11110 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_TX_DATA,
11111 entry.txBytes, entry.txPackets);
11112 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011113
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011114 mNetworkByteActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
11115 entry.rxBytes);
11116 mNetworkByteActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
11117 entry.txBytes);
11118 mNetworkPacketActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
11119 entry.rxPackets);
11120 mNetworkPacketActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
11121 entry.txPackets);
11122 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011123
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011124 // Now distribute proportional blame to the apps that did networking.
11125 long totalPackets = totalRxPackets + totalTxPackets;
11126 if (totalPackets > 0) {
11127 for (int i = 0; i < size; i++) {
11128 entry = delta.getValues(i, entry);
11129 if (entry.rxPackets == 0 && entry.txPackets == 0) {
11130 continue;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011131 }
11132
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011133 final Uid u = getUidStatsLocked(mapUid(entry.uid));
11134
11135 // Distribute total radio active time in to this app.
11136 final long appPackets = entry.rxPackets + entry.txPackets;
11137 final long appRadioTime = (radioTime * appPackets) / totalPackets;
11138 u.noteMobileRadioActiveTimeLocked(appRadioTime);
11139
11140 // Remove this app from the totals, so that we don't lose any time
11141 // due to rounding.
11142 radioTime -= appRadioTime;
11143 totalPackets -= appPackets;
11144
Chenjie Yua54e54d2018-02-14 20:12:52 -080011145 if (deltaInfo != null) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011146 ControllerActivityCounterImpl activityCounter =
11147 u.getOrCreateModemControllerActivityLocked();
11148 if (totalRxPackets > 0 && entry.rxPackets > 0) {
Chen Xu7322e4a2019-09-07 15:51:22 -070011149 final long rxMs = (entry.rxPackets
11150 * deltaInfo.getReceiveTimeMillis()) / totalRxPackets;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011151 activityCounter.getRxTimeCounter().addCountLocked(rxMs);
11152 }
11153
11154 if (totalTxPackets > 0 && entry.txPackets > 0) {
11155 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
11156 long txMs =
Chen Xu7322e4a2019-09-07 15:51:22 -070011157 entry.txPackets * deltaInfo.getTransmitPowerInfo()
11158 .get(lvl).getTimeInMillis();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011159 txMs /= totalTxPackets;
11160 activityCounter.getTxTimeCounters()[lvl].addCountLocked(txMs);
11161 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011162 }
11163 }
11164 }
11165 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011166
11167 if (radioTime > 0) {
11168 // Whoops, there is some radio time we can't blame on an app!
11169 mMobileRadioActiveUnknownTime.addCountLocked(radioTime);
11170 mMobileRadioActiveUnknownCount.addCountLocked(1);
11171 }
11172
11173 mNetworkStatsPool.release(delta);
11174 delta = null;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011175 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011176 }
11177 }
11178
11179 /**
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011180 * Add modem tx power to history
11181 * Device is said to be in high cellular transmit power when it has spent most of the transmit
11182 * time at the highest power level.
11183 * @param activityInfo
11184 */
Siddharth Raya67fb562018-02-28 13:46:16 -080011185 private synchronized void addModemTxPowerToHistory(final ModemActivityInfo activityInfo) {
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011186 if (activityInfo == null) {
11187 return;
11188 }
Chen Xu7322e4a2019-09-07 15:51:22 -070011189 List<TransmitPower> txPowerInfo = activityInfo.getTransmitPowerInfo();
11190 if (txPowerInfo == null || txPowerInfo.size() != ModemActivityInfo.TX_POWER_LEVELS) {
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011191 return;
11192 }
11193 final long elapsedRealtime = mClocks.elapsedRealtime();
11194 final long uptime = mClocks.uptimeMillis();
11195 int levelMaxTimeSpent = 0;
Chen Xu7322e4a2019-09-07 15:51:22 -070011196 for (int i = 1; i < txPowerInfo.size(); i++) {
11197 if (txPowerInfo.get(i).getTimeInMillis() > txPowerInfo.get(levelMaxTimeSpent)
11198 .getTimeInMillis()) {
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011199 levelMaxTimeSpent = i;
11200 }
11201 }
11202 if (levelMaxTimeSpent == ModemActivityInfo.TX_POWER_LEVELS - 1) {
Blake Kragten6bf8ef52019-03-20 17:14:58 -070011203 mHistoryCur.states2 |= HistoryItem.STATE2_CELLULAR_HIGH_TX_POWER_FLAG;
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011204 addHistoryRecordLocked(elapsedRealtime, uptime);
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011205 }
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011206 }
11207
Mike Ma561a8d92018-03-20 18:24:05 -070011208 private final class BluetoothActivityInfoCache {
11209 long idleTimeMs;
11210 long rxTimeMs;
11211 long txTimeMs;
11212 long energy;
11213
11214 SparseLongArray uidRxBytes = new SparseLongArray();
11215 SparseLongArray uidTxBytes = new SparseLongArray();
11216
11217 void set(BluetoothActivityEnergyInfo info) {
11218 idleTimeMs = info.getControllerIdleTimeMillis();
11219 rxTimeMs = info.getControllerRxTimeMillis();
11220 txTimeMs = info.getControllerTxTimeMillis();
11221 energy = info.getControllerEnergyUsed();
11222 if (info.getUidTraffic() != null) {
11223 for (UidTraffic traffic : info.getUidTraffic()) {
11224 uidRxBytes.put(traffic.getUid(), traffic.getRxBytes());
11225 uidTxBytes.put(traffic.getUid(), traffic.getTxBytes());
11226 }
11227 }
11228 }
11229 }
11230
11231 private final BluetoothActivityInfoCache mLastBluetoothActivityInfo
11232 = new BluetoothActivityInfoCache();
11233
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011234 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011235 * Distribute Bluetooth energy info and network traffic to apps.
Mike Ma561a8d92018-03-20 18:24:05 -070011236 *
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011237 * @param info The energy information from the bluetooth controller.
11238 */
11239 public void updateBluetoothStateLocked(@Nullable final BluetoothActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011240 if (DEBUG_ENERGY) {
Adam Lesinski50e47602015-12-04 17:04:54 -080011241 Slog.d(TAG, "Updating bluetooth stats: " + info);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011242 }
11243
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011244 if (info == null || !mOnBatteryInternal) {
11245 return;
11246 }
Adam Lesinskie283d332015-04-16 12:29:25 -070011247
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011248 mHasBluetoothReporting = true;
11249
Bookatz867c0d72017-03-07 18:23:42 -080011250 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Mike Ma561a8d92018-03-20 18:24:05 -070011251 final long rxTimeMs =
11252 info.getControllerRxTimeMillis() - mLastBluetoothActivityInfo.rxTimeMs;
11253 final long txTimeMs =
11254 info.getControllerTxTimeMillis() - mLastBluetoothActivityInfo.txTimeMs;
11255 final long idleTimeMs =
11256 info.getControllerIdleTimeMillis() - mLastBluetoothActivityInfo.idleTimeMs;
11257
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011258 if (DEBUG_ENERGY) {
11259 Slog.d(TAG, "------ BEGIN BLE power blaming ------");
11260 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
11261 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
Chenjie Yu89083392018-01-11 14:53:31 -080011262 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms");
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011263 }
11264
11265 long totalScanTimeMs = 0;
11266
11267 final int uidCount = mUidStats.size();
11268 for (int i = 0; i < uidCount; i++) {
11269 final Uid u = mUidStats.valueAt(i);
11270 if (u.mBluetoothScanTimer == null) {
11271 continue;
Adam Lesinskie283d332015-04-16 12:29:25 -070011272 }
Adam Lesinski50e47602015-12-04 17:04:54 -080011273
Bookatzaa4594a2017-03-24 12:39:56 -070011274 totalScanTimeMs += u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011275 elapsedRealtimeMs * 1000) / 1000;
11276 }
11277
11278 final boolean normalizeScanRxTime = (totalScanTimeMs > rxTimeMs);
11279 final boolean normalizeScanTxTime = (totalScanTimeMs > txTimeMs);
11280
11281 if (DEBUG_ENERGY) {
11282 Slog.d(TAG, "Normalizing scan power for RX=" + normalizeScanRxTime
11283 + " TX=" + normalizeScanTxTime);
11284 }
11285
11286 long leftOverRxTimeMs = rxTimeMs;
11287 long leftOverTxTimeMs = txTimeMs;
11288
11289 for (int i = 0; i < uidCount; i++) {
11290 final Uid u = mUidStats.valueAt(i);
11291 if (u.mBluetoothScanTimer == null) {
11292 continue;
11293 }
11294
Bookatzaa4594a2017-03-24 12:39:56 -070011295 long scanTimeSinceMarkMs = u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011296 elapsedRealtimeMs * 1000) / 1000;
11297 if (scanTimeSinceMarkMs > 0) {
11298 // Set the new mark so that next time we get new data since this point.
11299 u.mBluetoothScanTimer.setMark(elapsedRealtimeMs);
11300
11301 long scanTimeRxSinceMarkMs = scanTimeSinceMarkMs;
11302 long scanTimeTxSinceMarkMs = scanTimeSinceMarkMs;
11303
11304 if (normalizeScanRxTime) {
11305 // Scan time is longer than the total rx time in the controller,
11306 // so distribute the scan time proportionately. This means regular traffic
11307 // will not blamed, but scans are more expensive anyways.
11308 scanTimeRxSinceMarkMs = (rxTimeMs * scanTimeRxSinceMarkMs) / totalScanTimeMs;
11309 }
11310
11311 if (normalizeScanTxTime) {
11312 // Scan time is longer than the total tx time in the controller,
11313 // so distribute the scan time proportionately. This means regular traffic
11314 // will not blamed, but scans are more expensive anyways.
11315 scanTimeTxSinceMarkMs = (txTimeMs * scanTimeTxSinceMarkMs) / totalScanTimeMs;
11316 }
11317
11318 final ControllerActivityCounterImpl counter =
11319 u.getOrCreateBluetoothControllerActivityLocked();
11320 counter.getRxTimeCounter().addCountLocked(scanTimeRxSinceMarkMs);
11321 counter.getTxTimeCounters()[0].addCountLocked(scanTimeTxSinceMarkMs);
11322
11323 leftOverRxTimeMs -= scanTimeRxSinceMarkMs;
11324 leftOverTxTimeMs -= scanTimeTxSinceMarkMs;
11325 }
11326 }
11327
11328 if (DEBUG_ENERGY) {
Mike Ma561a8d92018-03-20 18:24:05 -070011329 Slog.d(TAG, "Left over time for traffic RX=" + leftOverRxTimeMs + " TX="
11330 + leftOverTxTimeMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011331 }
11332
11333 //
11334 // Now distribute blame to apps that did bluetooth traffic.
11335 //
11336
11337 long totalTxBytes = 0;
11338 long totalRxBytes = 0;
11339
11340 final UidTraffic[] uidTraffic = info.getUidTraffic();
Mike Ma561a8d92018-03-20 18:24:05 -070011341 final int numUids = uidTraffic != null ? uidTraffic.length : 0;
11342 for (int i = 0; i < numUids; i++) {
11343 final UidTraffic traffic = uidTraffic[i];
11344 final long rxBytes = traffic.getRxBytes() - mLastBluetoothActivityInfo.uidRxBytes.get(
11345 traffic.getUid());
11346 final long txBytes = traffic.getTxBytes() - mLastBluetoothActivityInfo.uidTxBytes.get(
11347 traffic.getUid());
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011348
11349 // Add to the global counters.
Mike Ma561a8d92018-03-20 18:24:05 -070011350 mNetworkByteActivityCounters[NETWORK_BT_RX_DATA].addCountLocked(rxBytes);
11351 mNetworkByteActivityCounters[NETWORK_BT_TX_DATA].addCountLocked(txBytes);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011352
11353 // Add to the UID counters.
11354 final Uid u = getUidStatsLocked(mapUid(traffic.getUid()));
Mike Ma561a8d92018-03-20 18:24:05 -070011355 u.noteNetworkActivityLocked(NETWORK_BT_RX_DATA, rxBytes, 0);
11356 u.noteNetworkActivityLocked(NETWORK_BT_TX_DATA, txBytes, 0);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011357
11358 // Calculate the total traffic.
Mike Ma561a8d92018-03-20 18:24:05 -070011359 totalRxBytes += rxBytes;
11360 totalTxBytes += txBytes;
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011361 }
11362
Mike Ma561a8d92018-03-20 18:24:05 -070011363 if ((totalTxBytes != 0 || totalRxBytes != 0) && (leftOverRxTimeMs != 0
11364 || leftOverTxTimeMs != 0)) {
11365 for (int i = 0; i < numUids; i++) {
11366 final UidTraffic traffic = uidTraffic[i];
11367 final int uid = traffic.getUid();
11368 final long rxBytes =
11369 traffic.getRxBytes() - mLastBluetoothActivityInfo.uidRxBytes.get(uid);
11370 final long txBytes =
11371 traffic.getTxBytes() - mLastBluetoothActivityInfo.uidTxBytes.get(uid);
Adam Lesinski50e47602015-12-04 17:04:54 -080011372
Mike Ma561a8d92018-03-20 18:24:05 -070011373 final Uid u = getUidStatsLocked(mapUid(uid));
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011374 final ControllerActivityCounterImpl counter =
11375 u.getOrCreateBluetoothControllerActivityLocked();
11376
Mike Ma561a8d92018-03-20 18:24:05 -070011377 if (totalRxBytes > 0 && rxBytes > 0) {
11378 final long timeRxMs = (leftOverRxTimeMs * rxBytes) / totalRxBytes;
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011379 if (DEBUG_ENERGY) {
Mike Ma561a8d92018-03-20 18:24:05 -070011380 Slog.d(TAG, "UID=" + uid + " rx_bytes=" + rxBytes + " rx_time=" + timeRxMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011381 }
11382 counter.getRxTimeCounter().addCountLocked(timeRxMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011383 }
11384
Mike Ma561a8d92018-03-20 18:24:05 -070011385 if (totalTxBytes > 0 && txBytes > 0) {
11386 final long timeTxMs = (leftOverTxTimeMs * txBytes) / totalTxBytes;
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011387 if (DEBUG_ENERGY) {
Mike Ma561a8d92018-03-20 18:24:05 -070011388 Slog.d(TAG, "UID=" + uid + " tx_bytes=" + txBytes + " tx_time=" + timeTxMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011389 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011390 counter.getTxTimeCounters()[0].addCountLocked(timeTxMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011391 }
Adam Lesinski50e47602015-12-04 17:04:54 -080011392 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011393 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011394
Chenjie Yu89083392018-01-11 14:53:31 -080011395 mBluetoothActivity.getRxTimeCounter().addCountLocked(rxTimeMs);
11396 mBluetoothActivity.getTxTimeCounters()[0].addCountLocked(txTimeMs);
11397 mBluetoothActivity.getIdleTimeCounter().addCountLocked(idleTimeMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011398
11399 // POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11400 final double opVolt = mPowerProfile.getAveragePower(
11401 PowerProfile.POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11402 if (opVolt != 0) {
11403 // We store the power drain as mAms.
11404 mBluetoothActivity.getPowerCounter().addCountLocked(
Mike Ma561a8d92018-03-20 18:24:05 -070011405 (long) ((info.getControllerEnergyUsed() - mLastBluetoothActivityInfo.energy)
11406 / opVolt));
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011407 }
Mike Ma561a8d92018-03-20 18:24:05 -070011408 mLastBluetoothActivityInfo.set(info);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011409 }
11410
11411 /**
Bookatz0b8a0502017-09-13 11:51:52 -070011412 * Read and record Resource Power Manager (RPM) state and voter times.
11413 * If RPM stats were fetched more recently than RPM_STATS_UPDATE_FREQ_MS ago, uses the old data
11414 * instead of fetching it anew.
Bookatz50df7112017-08-04 14:53:26 -070011415 */
11416 public void updateRpmStatsLocked() {
11417 if (mPlatformIdleStateCallback == null) return;
Bookatz0b8a0502017-09-13 11:51:52 -070011418 long now = SystemClock.elapsedRealtime();
11419 if (now - mLastRpmStatsUpdateTimeMs >= RPM_STATS_UPDATE_FREQ_MS) {
11420 mPlatformIdleStateCallback.fillLowPowerStats(mTmpRpmStats);
11421 mLastRpmStatsUpdateTimeMs = now;
11422 }
Bookatz50df7112017-08-04 14:53:26 -070011423
11424 for (Map.Entry<String, RpmStats.PowerStatePlatformSleepState> pstate
11425 : mTmpRpmStats.mPlatformLowPowerStats.entrySet()) {
11426
11427 // Update values for this platform state.
11428 final String pName = pstate.getKey();
11429 final long pTimeUs = pstate.getValue().mTimeMs * 1000;
11430 final int pCount = pstate.getValue().mCount;
11431 getRpmTimerLocked(pName).update(pTimeUs, pCount);
Bookatz82b341172017-09-07 19:06:08 -070011432 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11433 getScreenOffRpmTimerLocked(pName).update(pTimeUs, pCount);
11434 }
Bookatz50df7112017-08-04 14:53:26 -070011435
11436 // Update values for each voter of this platform state.
11437 for (Map.Entry<String, RpmStats.PowerStateElement> voter
11438 : pstate.getValue().mVoters.entrySet()) {
11439 final String vName = pName + "." + voter.getKey();
11440 final long vTimeUs = voter.getValue().mTimeMs * 1000;
11441 final int vCount = voter.getValue().mCount;
11442 getRpmTimerLocked(vName).update(vTimeUs, vCount);
Bookatz82b341172017-09-07 19:06:08 -070011443 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11444 getScreenOffRpmTimerLocked(vName).update(vTimeUs, vCount);
11445 }
Bookatz50df7112017-08-04 14:53:26 -070011446 }
11447 }
11448
11449 for (Map.Entry<String, RpmStats.PowerStateSubsystem> subsys
11450 : mTmpRpmStats.mSubsystemLowPowerStats.entrySet()) {
11451
11452 final String subsysName = subsys.getKey();
11453 for (Map.Entry<String, RpmStats.PowerStateElement> sstate
11454 : subsys.getValue().mStates.entrySet()) {
11455 final String name = subsysName + "." + sstate.getKey();
11456 final long timeUs = sstate.getValue().mTimeMs * 1000;
11457 final int count = sstate.getValue().mCount;
11458 getRpmTimerLocked(name).update(timeUs, count);
Bookatz82b341172017-09-07 19:06:08 -070011459 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11460 getScreenOffRpmTimerLocked(name).update(timeUs, count);
11461 }
Bookatz50df7112017-08-04 14:53:26 -070011462 }
11463 }
11464 }
11465
11466 /**
Blake Kragtencb308d92019-01-28 10:54:13 -080011467 * Read and record Rail Energy data.
11468 */
11469 public void updateRailStatsLocked() {
11470 if (mRailEnergyDataCallback == null || !mTmpRailStats.isRailStatsAvailable()) {
11471 return;
11472 }
11473 mRailEnergyDataCallback.fillRailDataStats(mTmpRailStats);
11474 }
11475
11476 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011477 * Read and distribute kernel wake lock use across apps.
11478 */
11479 public void updateKernelWakelocksLocked() {
11480 final KernelWakelockStats wakelockStats = mKernelWakelockReader.readKernelWakelockStats(
11481 mTmpWakelockStats);
11482 if (wakelockStats == null) {
11483 // Not crashing might make board bringup easier.
11484 Slog.w(TAG, "Couldn't get kernel wake lock stats");
11485 return;
11486 }
11487
11488 for (Map.Entry<String, KernelWakelockStats.Entry> ent : wakelockStats.entrySet()) {
11489 String name = ent.getKey();
11490 KernelWakelockStats.Entry kws = ent.getValue();
11491
11492 SamplingTimer kwlt = mKernelWakelockStats.get(name);
11493 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -070011494 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011495 mKernelWakelockStats.put(name, kwlt);
11496 }
Adam Lesinskid84ad302016-05-17 18:31:02 -070011497
Adam Lesinski757c6ea2016-04-21 09:55:41 -070011498 kwlt.update(kws.mTotalTime, kws.mCount);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011499 kwlt.setUpdateVersion(kws.mVersion);
11500 }
11501
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011502 int numWakelocksSetStale = 0;
Adam Lesinskid84ad302016-05-17 18:31:02 -070011503 // Set timers to stale if they didn't appear in /d/wakeup_sources (or /proc/wakelocks)
11504 // this time.
11505 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
11506 SamplingTimer st = ent.getValue();
11507 if (st.getUpdateVersion() != wakelockStats.kernelWakelockVersion) {
11508 st.endSample();
11509 numWakelocksSetStale++;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011510 }
11511 }
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011512
Adam Lesinskid84ad302016-05-17 18:31:02 -070011513 // Record whether we've seen a non-zero time (for debugging b/22716723).
11514 if (wakelockStats.isEmpty()) {
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011515 Slog.wtf(TAG, "All kernel wakelocks had time of zero");
11516 }
11517
11518 if (numWakelocksSetStale == mKernelWakelockStats.size()) {
11519 Slog.wtf(TAG, "All kernel wakelocks were set stale. new version=" +
11520 wakelockStats.kernelWakelockVersion);
11521 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011522 }
11523
Adam Lesinski72478f02015-06-17 15:39:43 -070011524 // We use an anonymous class to access these variables,
11525 // so they can't live on the stack or they'd have to be
11526 // final MutableLong objects (more allocations).
11527 // Used in updateCpuTimeLocked().
11528 long mTempTotalCpuUserTimeUs;
11529 long mTempTotalCpuSystemTimeUs;
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011530 long[][] mWakeLockAllocationsUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070011531
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011532 /**
James Carr3a226052016-07-01 14:49:52 -070011533 * Reads the newest memory stats from the kernel.
11534 */
11535 public void updateKernelMemoryBandwidthLocked() {
11536 mKernelMemoryBandwidthStats.updateStats();
11537 LongSparseLongArray bandwidthEntries = mKernelMemoryBandwidthStats.getBandwidthEntries();
11538 final int bandwidthEntryCount = bandwidthEntries.size();
11539 int index;
11540 for (int i = 0; i < bandwidthEntryCount; i++) {
11541 SamplingTimer timer;
11542 if ((index = mKernelMemoryStats.indexOfKey(bandwidthEntries.keyAt(i))) >= 0) {
11543 timer = mKernelMemoryStats.valueAt(index);
11544 } else {
11545 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
11546 mKernelMemoryStats.put(bandwidthEntries.keyAt(i), timer);
11547 }
11548 timer.update(bandwidthEntries.valueAt(i), 1);
11549 if (DEBUG_MEMORY) {
11550 Slog.d(TAG, String.format("Added entry %d and updated timer to: "
11551 + "mUnpluggedReportedTotalTime %d size %d", bandwidthEntries.keyAt(i),
11552 mKernelMemoryStats.get(
11553 bandwidthEntries.keyAt(i)).mUnpluggedReportedTotalTime,
11554 mKernelMemoryStats.size()));
11555 }
11556 }
11557 }
11558
Sudheer Shankac57729a2018-02-09 15:44:42 -080011559 public boolean isOnBatteryLocked() {
11560 return mOnBatteryTimeBase.isRunning();
11561 }
11562
11563 public boolean isOnBatteryScreenOffLocked() {
11564 return mOnBatteryScreenOffTimeBase.isRunning();
11565 }
11566
James Carr3a226052016-07-01 14:49:52 -070011567 /**
Adam Lesinski72478f02015-06-17 15:39:43 -070011568 * Read and distribute CPU usage across apps. If their are partial wakelocks being held
11569 * and we are on battery with screen off, we give more of the cpu time to those apps holding
11570 * wakelocks. If the screen is on, we just assign the actual cpu time an app used.
Sudheer Shankac57729a2018-02-09 15:44:42 -080011571 * It's possible this will be invoked after the internal battery/screen states are updated, so
11572 * passing the appropriate battery/screen states to try attribute the cpu times to correct
11573 * buckets.
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011574 */
Andreas Gampe3f24e692018-02-05 13:24:28 -080011575 @GuardedBy("this")
Sudheer Shankac57729a2018-02-09 15:44:42 -080011576 public void updateCpuTimeLocked(boolean onBattery, boolean onBatteryScreenOff) {
Adam Lesinski52290c9c2015-09-21 16:54:52 -070011577 if (mPowerProfile == null) {
11578 return;
11579 }
11580
Adam Lesinski72478f02015-06-17 15:39:43 -070011581 if (DEBUG_ENERGY_CPU) {
11582 Slog.d(TAG, "!Cpu updating!");
11583 }
11584
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011585 if (mCpuFreqs == null) {
Mike Ma7ab7fcd2019-01-16 15:00:40 -080011586 mCpuFreqs = mCpuUidFreqTimeReader.readFreqs(mPowerProfile);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011587 }
11588
Sudheer Shanka38383232017-07-25 09:55:03 -070011589 // Calculate the wakelocks we have to distribute amongst. The system is excluded as it is
11590 // usually holding the wakelock on behalf of an app.
11591 // And Only distribute cpu power to wakelocks if the screen is off and we're on battery.
11592 ArrayList<StopwatchTimer> partialTimersToConsider = null;
Sudheer Shankac57729a2018-02-09 15:44:42 -080011593 if (onBatteryScreenOff) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011594 partialTimersToConsider = new ArrayList<>();
11595 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070011596 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070011597 // Since the collection and blaming of wakelocks can be scheduled to run after
11598 // some delay, the mPartialTimers list may have new entries. We can't blame
11599 // the newly added timer for past cpu time, so we only consider timers that
11600 // were present for one round of collection. Once a timer has gone through
11601 // a round of collection, its mInList field is set to true.
Adam Lesinski72478f02015-06-17 15:39:43 -070011602 if (timer.mInList && timer.mUid != null && timer.mUid.mUid != Process.SYSTEM_UID) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011603 partialTimersToConsider.add(timer);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011604 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011605 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011606 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011607 markPartialTimersAsEligible();
Adam Lesinski72478f02015-06-17 15:39:43 -070011608
Sudheer Shanka38383232017-07-25 09:55:03 -070011609 // When the battery is not on, we don't attribute the cpu times to any timers but we still
11610 // need to take the snapshots.
Sudheer Shankac57729a2018-02-09 15:44:42 -080011611 if (!onBattery) {
Mike Ma7ab7fcd2019-01-16 15:00:40 -080011612 mCpuUidUserSysTimeReader.readDelta(null);
11613 mCpuUidFreqTimeReader.readDelta(null);
Mike Ma234d1822018-03-13 18:53:21 -070011614 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080011615 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
Mike Ma7ab7fcd2019-01-16 15:00:40 -080011616 mCpuUidActiveTimeReader.readDelta(null);
11617 mCpuUidClusterTimeReader.readDelta(null);
Mike Ma234d1822018-03-13 18:53:21 -070011618 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080011619 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011620 for (int cluster = mKernelCpuSpeedReaders.length - 1; cluster >= 0; --cluster) {
11621 mKernelCpuSpeedReaders[cluster].readDelta();
11622 }
11623 return;
11624 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011625
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070011626 mUserInfoProvider.refreshUserIds();
Mike Ma7ab7fcd2019-01-16 15:00:40 -080011627 final SparseLongArray updatedUids = mCpuUidFreqTimeReader.perClusterTimesAvailable()
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011628 ? null : new SparseLongArray();
Sudheer Shankac57729a2018-02-09 15:44:42 -080011629 readKernelUidCpuTimesLocked(partialTimersToConsider, updatedUids, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011630 // updatedUids=null means /proc/uid_time_in_state provides snapshots of per-cluster cpu
11631 // freqs, so no need to approximate these values.
11632 if (updatedUids != null) {
Sudheer Shankac57729a2018-02-09 15:44:42 -080011633 updateClusterSpeedTimes(updatedUids, onBattery);
Sudheer Shanka671985f2017-05-19 11:33:42 -070011634 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080011635 readKernelUidCpuFreqTimesLocked(partialTimersToConsider, onBattery, onBatteryScreenOff);
Mike Ma234d1822018-03-13 18:53:21 -070011636 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080011637 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
Sudheer Shankac57729a2018-02-09 15:44:42 -080011638 readKernelUidCpuActiveTimesLocked(onBattery);
11639 readKernelUidCpuClusterTimesLocked(onBattery);
Mike Ma234d1822018-03-13 18:53:21 -070011640 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080011641 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011642 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070011643
Sudheer Shanka38383232017-07-25 09:55:03 -070011644 /**
11645 * Mark the current partial timers as gone through a collection so that they will be
11646 * considered in the next cpu times distribution to wakelock holders.
11647 */
11648 @VisibleForTesting
11649 public void markPartialTimersAsEligible() {
11650 if (ArrayUtils.referenceEquals(mPartialTimers, mLastPartialTimers)) {
11651 // No difference, so each timer is now considered for the next collection.
11652 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
11653 mPartialTimers.get(i).mInList = true;
11654 }
11655 } else {
11656 // The lists are different, meaning we added (or removed a timer) since the last
11657 // collection.
11658 for (int i = mLastPartialTimers.size() - 1; i >= 0; --i) {
11659 mLastPartialTimers.get(i).mInList = false;
11660 }
11661 mLastPartialTimers.clear();
Adam Lesinski72478f02015-06-17 15:39:43 -070011662
Sudheer Shanka38383232017-07-25 09:55:03 -070011663 // Mark the current timers as gone through a collection.
11664 final int numPartialTimers = mPartialTimers.size();
11665 for (int i = 0; i < numPartialTimers; ++i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070011666 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070011667 timer.mInList = true;
11668 mLastPartialTimers.add(timer);
Adam Lesinski72478f02015-06-17 15:39:43 -070011669 }
11670 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011671 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011672
Sudheer Shanka38383232017-07-25 09:55:03 -070011673 /**
11674 * Take snapshot of cpu times (aggregated over all uids) at different frequencies and
11675 * calculate cpu times spent by each uid at different frequencies.
11676 *
11677 * @param updatedUids The uids for which times spent at different frequencies are calculated.
11678 */
11679 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080011680 public void updateClusterSpeedTimes(@NonNull SparseLongArray updatedUids, boolean onBattery) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070011681 long totalCpuClustersTimeMs = 0;
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011682 // Read the time spent for each cluster at various cpu frequencies.
Sudheer Shankaaf857412017-07-21 00:14:24 -070011683 final long[][] clusterSpeedTimesMs = new long[mKernelCpuSpeedReaders.length][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011684 for (int cluster = 0; cluster < mKernelCpuSpeedReaders.length; cluster++) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070011685 clusterSpeedTimesMs[cluster] = mKernelCpuSpeedReaders[cluster].readDelta();
11686 if (clusterSpeedTimesMs[cluster] != null) {
11687 for (int speed = clusterSpeedTimesMs[cluster].length - 1; speed >= 0; --speed) {
11688 totalCpuClustersTimeMs += clusterSpeedTimesMs[cluster][speed];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011689 }
11690 }
11691 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070011692 if (totalCpuClustersTimeMs != 0) {
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011693 // We have cpu times per freq aggregated over all uids but we need the times per uid.
11694 // So, we distribute total time spent by an uid to different cpu freqs based on the
11695 // amount of time cpu was running at that freq.
11696 final int updatedUidsCount = updatedUids.size();
11697 for (int i = 0; i < updatedUidsCount; ++i) {
11698 final Uid u = getUidStatsLocked(updatedUids.keyAt(i));
Sudheer Shankaaf857412017-07-21 00:14:24 -070011699 final long appCpuTimeUs = updatedUids.valueAt(i);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011700 // Add the cpu speeds to this UID.
11701 final int numClusters = mPowerProfile.getNumCpuClusters();
Sudheer Shanka38383232017-07-25 09:55:03 -070011702 if (u.mCpuClusterSpeedTimesUs == null ||
11703 u.mCpuClusterSpeedTimesUs.length != numClusters) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070011704 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011705 }
11706
Sudheer Shankaaf857412017-07-21 00:14:24 -070011707 for (int cluster = 0; cluster < clusterSpeedTimesMs.length; cluster++) {
11708 final int speedsInCluster = clusterSpeedTimesMs[cluster].length;
11709 if (u.mCpuClusterSpeedTimesUs[cluster] == null || speedsInCluster !=
11710 u.mCpuClusterSpeedTimesUs[cluster].length) {
11711 u.mCpuClusterSpeedTimesUs[cluster]
11712 = new LongSamplingCounter[speedsInCluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011713 }
11714
Sudheer Shankaaf857412017-07-21 00:14:24 -070011715 final LongSamplingCounter[] cpuSpeeds = u.mCpuClusterSpeedTimesUs[cluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011716 for (int speed = 0; speed < speedsInCluster; speed++) {
11717 if (cpuSpeeds[speed] == null) {
11718 cpuSpeeds[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
11719 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070011720 cpuSpeeds[speed].addCountLocked(appCpuTimeUs
11721 * clusterSpeedTimesMs[cluster][speed]
Sudheer Shankac57729a2018-02-09 15:44:42 -080011722 / totalCpuClustersTimeMs, onBattery);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011723 }
11724 }
11725 }
11726 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011727 }
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011728
Sudheer Shanka38383232017-07-25 09:55:03 -070011729 /**
11730 * Take a snapshot of the cpu times spent by each uid and update the corresponding counters.
11731 * If {@param partialTimers} is not null and empty, then we assign a portion of cpu times to
11732 * wakelock holders.
11733 *
11734 * @param partialTimers The wakelock holders among which the cpu times will be distributed.
11735 * @param updatedUids If not null, then the uids found in the snapshot will be added to this.
11736 */
11737 @VisibleForTesting
11738 public void readKernelUidCpuTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers,
Sudheer Shankac57729a2018-02-09 15:44:42 -080011739 @Nullable SparseLongArray updatedUids, boolean onBattery) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011740 mTempTotalCpuUserTimeUs = mTempTotalCpuSystemTimeUs = 0;
11741 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
11742 final long startTimeMs = mClocks.uptimeMillis();
Adam Lesinski72478f02015-06-17 15:39:43 -070011743
Mike Ma7ab7fcd2019-01-16 15:00:40 -080011744 mCpuUidUserSysTimeReader.readDelta((uid, timesUs) -> {
11745 long userTimeUs = timesUs[0], systemTimeUs = timesUs[1];
11746
Sudheer Shanka38383232017-07-25 09:55:03 -070011747 uid = mapUid(uid);
11748 if (Process.isIsolated(uid)) {
11749 // This could happen if the isolated uid mapping was removed before that process
11750 // was actually killed.
Mike Ma7ab7fcd2019-01-16 15:00:40 -080011751 mCpuUidUserSysTimeReader.removeUid(uid);
Sudheer Shanka38383232017-07-25 09:55:03 -070011752 Slog.d(TAG, "Got readings for an isolated uid with no mapping: " + uid);
11753 return;
11754 }
11755 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
11756 Slog.d(TAG, "Got readings for an invalid user's uid " + uid);
Mike Ma7ab7fcd2019-01-16 15:00:40 -080011757 mCpuUidUserSysTimeReader.removeUid(uid);
Sudheer Shanka38383232017-07-25 09:55:03 -070011758 return;
11759 }
11760 final Uid u = getUidStatsLocked(uid);
11761
11762 // Accumulate the total system and user time.
11763 mTempTotalCpuUserTimeUs += userTimeUs;
11764 mTempTotalCpuSystemTimeUs += systemTimeUs;
11765
11766 StringBuilder sb = null;
11767 if (DEBUG_ENERGY_CPU) {
11768 sb = new StringBuilder();
11769 sb.append(" got time for uid=").append(u.mUid).append(": u=");
11770 TimeUtils.formatDuration(userTimeUs / 1000, sb);
11771 sb.append(" s=");
11772 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
11773 sb.append("\n");
11774 }
11775
11776 if (numWakelocks > 0) {
11777 // We have wakelocks being held, so only give a portion of the
11778 // time to the process. The rest will be distributed among wakelock
11779 // holders.
11780 userTimeUs = (userTimeUs * WAKE_LOCK_WEIGHT) / 100;
11781 systemTimeUs = (systemTimeUs * WAKE_LOCK_WEIGHT) / 100;
11782 }
11783
11784 if (sb != null) {
11785 sb.append(" adding to uid=").append(u.mUid).append(": u=");
11786 TimeUtils.formatDuration(userTimeUs / 1000, sb);
11787 sb.append(" s=");
11788 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
11789 Slog.d(TAG, sb.toString());
11790 }
11791
Sudheer Shankac57729a2018-02-09 15:44:42 -080011792 u.mUserCpuTime.addCountLocked(userTimeUs, onBattery);
11793 u.mSystemCpuTime.addCountLocked(systemTimeUs, onBattery);
Sudheer Shanka38383232017-07-25 09:55:03 -070011794 if (updatedUids != null) {
11795 updatedUids.put(u.getUid(), userTimeUs + systemTimeUs);
11796 }
11797 });
11798
11799 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
11800 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
11801 Slog.d(TAG, "Reading cpu stats took " + elapsedTimeMs + "ms");
11802 }
11803
11804 if (numWakelocks > 0) {
11805 // Distribute a portion of the total cpu time to wakelock holders.
11806 mTempTotalCpuUserTimeUs = (mTempTotalCpuUserTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
11807 mTempTotalCpuSystemTimeUs =
11808 (mTempTotalCpuSystemTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
11809
11810 for (int i = 0; i < numWakelocks; ++i) {
11811 final StopwatchTimer timer = partialTimers.get(i);
11812 final int userTimeUs = (int) (mTempTotalCpuUserTimeUs / (numWakelocks - i));
11813 final int systemTimeUs = (int) (mTempTotalCpuSystemTimeUs / (numWakelocks - i));
11814
11815 if (DEBUG_ENERGY_CPU) {
11816 final StringBuilder sb = new StringBuilder();
11817 sb.append(" Distributing wakelock uid=").append(timer.mUid.mUid)
11818 .append(": u=");
11819 TimeUtils.formatDuration(userTimeUs / 1000, sb);
11820 sb.append(" s=");
11821 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
11822 Slog.d(TAG, sb.toString());
11823 }
11824
Sudheer Shankac57729a2018-02-09 15:44:42 -080011825 timer.mUid.mUserCpuTime.addCountLocked(userTimeUs, onBattery);
11826 timer.mUid.mSystemCpuTime.addCountLocked(systemTimeUs, onBattery);
Sudheer Shanka38383232017-07-25 09:55:03 -070011827 if (updatedUids != null) {
11828 final int uid = timer.mUid.getUid();
11829 updatedUids.put(uid, updatedUids.get(uid, 0) + userTimeUs + systemTimeUs);
11830 }
11831
11832 final Uid.Proc proc = timer.mUid.getProcessStatsLocked("*wakelock*");
Sudheer Shankac57729a2018-02-09 15:44:42 -080011833 proc.addCpuTimeLocked(userTimeUs / 1000, systemTimeUs / 1000, onBattery);
Sudheer Shanka38383232017-07-25 09:55:03 -070011834
11835 mTempTotalCpuUserTimeUs -= userTimeUs;
11836 mTempTotalCpuSystemTimeUs -= systemTimeUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070011837 }
11838 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011839 }
11840
Sudheer Shanka38383232017-07-25 09:55:03 -070011841 /**
11842 * Take a snapshot of the cpu times spent by each uid in each freq and update the
11843 * corresponding counters.
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011844 *
11845 * @param partialTimers The wakelock holders among which the cpu freq times will be distributed.
Sudheer Shanka38383232017-07-25 09:55:03 -070011846 */
11847 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080011848 public void readKernelUidCpuFreqTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers,
11849 boolean onBattery, boolean onBatteryScreenOff) {
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011850 final boolean perClusterTimesAvailable =
Mike Ma7ab7fcd2019-01-16 15:00:40 -080011851 mCpuUidFreqTimeReader.perClusterTimesAvailable();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011852 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
11853 final int numClusters = mPowerProfile.getNumCpuClusters();
11854 mWakeLockAllocationsUs = null;
Sudheer Shankaac5b88f2017-12-11 15:36:35 -080011855 final long startTimeMs = mClocks.uptimeMillis();
Mike Ma7ab7fcd2019-01-16 15:00:40 -080011856 mCpuUidFreqTimeReader.readDelta((uid, cpuFreqTimeMs) -> {
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011857 uid = mapUid(uid);
11858 if (Process.isIsolated(uid)) {
Mike Ma7ab7fcd2019-01-16 15:00:40 -080011859 mCpuUidFreqTimeReader.removeUid(uid);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011860 Slog.d(TAG, "Got freq readings for an isolated uid with no mapping: " + uid);
11861 return;
Sudheer Shanka38383232017-07-25 09:55:03 -070011862 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011863 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
11864 Slog.d(TAG, "Got freq readings for an invalid user's uid " + uid);
Mike Ma7ab7fcd2019-01-16 15:00:40 -080011865 mCpuUidFreqTimeReader.removeUid(uid);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011866 return;
11867 }
11868 final Uid u = getUidStatsLocked(uid);
11869 if (u.mCpuFreqTimeMs == null || u.mCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
Hui Yu8e88e952018-07-23 17:59:59 -070011870 detachIfNotNull(u.mCpuFreqTimeMs);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011871 u.mCpuFreqTimeMs = new LongSamplingCounterArray(mOnBatteryTimeBase);
11872 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080011873 u.mCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011874 if (u.mScreenOffCpuFreqTimeMs == null ||
11875 u.mScreenOffCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
Hui Yu8e88e952018-07-23 17:59:59 -070011876 detachIfNotNull(u.mScreenOffCpuFreqTimeMs);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011877 u.mScreenOffCpuFreqTimeMs = new LongSamplingCounterArray(
11878 mOnBatteryScreenOffTimeBase);
11879 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080011880 u.mScreenOffCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs, onBatteryScreenOff);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070011881
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011882 if (perClusterTimesAvailable) {
11883 if (u.mCpuClusterSpeedTimesUs == null ||
11884 u.mCpuClusterSpeedTimesUs.length != numClusters) {
Hui Yu8e88e952018-07-23 17:59:59 -070011885 detachIfNotNull(u.mCpuClusterSpeedTimesUs);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011886 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070011887 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011888 if (numWakelocks > 0 && mWakeLockAllocationsUs == null) {
11889 mWakeLockAllocationsUs = new long[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070011890 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011891
11892 int freqIndex = 0;
11893 for (int cluster = 0; cluster < numClusters; ++cluster) {
11894 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
11895 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
11896 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
Hui Yu8e88e952018-07-23 17:59:59 -070011897 detachIfNotNull(u.mCpuClusterSpeedTimesUs[cluster]);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011898 u.mCpuClusterSpeedTimesUs[cluster]
11899 = new LongSamplingCounter[speedsInCluster];
11900 }
11901 if (numWakelocks > 0 && mWakeLockAllocationsUs[cluster] == null) {
11902 mWakeLockAllocationsUs[cluster] = new long[speedsInCluster];
11903 }
11904 final LongSamplingCounter[] cpuTimesUs = u.mCpuClusterSpeedTimesUs[cluster];
11905 for (int speed = 0; speed < speedsInCluster; ++speed) {
11906 if (cpuTimesUs[speed] == null) {
11907 cpuTimesUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
11908 }
11909 final long appAllocationUs;
11910 if (mWakeLockAllocationsUs != null) {
11911 appAllocationUs =
11912 (cpuFreqTimeMs[freqIndex] * 1000 * WAKE_LOCK_WEIGHT) / 100;
11913 mWakeLockAllocationsUs[cluster][speed] +=
11914 (cpuFreqTimeMs[freqIndex] * 1000 - appAllocationUs);
11915 } else {
11916 appAllocationUs = cpuFreqTimeMs[freqIndex] * 1000;
11917 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080011918 cpuTimesUs[speed].addCountLocked(appAllocationUs, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011919 freqIndex++;
11920 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011921 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011922 }
11923 });
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011924
Sudheer Shankaac5b88f2017-12-11 15:36:35 -080011925 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
11926 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
11927 Slog.d(TAG, "Reading cpu freq times took " + elapsedTimeMs + "ms");
11928 }
11929
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011930 if (mWakeLockAllocationsUs != null) {
11931 for (int i = 0; i < numWakelocks; ++i) {
11932 final Uid u = partialTimers.get(i).mUid;
11933 if (u.mCpuClusterSpeedTimesUs == null ||
11934 u.mCpuClusterSpeedTimesUs.length != numClusters) {
Hui Yu8e88e952018-07-23 17:59:59 -070011935 detachIfNotNull(u.mCpuClusterSpeedTimesUs);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011936 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
11937 }
11938
11939 for (int cluster = 0; cluster < numClusters; ++cluster) {
11940 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
11941 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
11942 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
Hui Yu8e88e952018-07-23 17:59:59 -070011943 detachIfNotNull(u.mCpuClusterSpeedTimesUs[cluster]);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011944 u.mCpuClusterSpeedTimesUs[cluster]
11945 = new LongSamplingCounter[speedsInCluster];
11946 }
11947 final LongSamplingCounter[] cpuTimeUs = u.mCpuClusterSpeedTimesUs[cluster];
11948 for (int speed = 0; speed < speedsInCluster; ++speed) {
11949 if (cpuTimeUs[speed] == null) {
11950 cpuTimeUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
11951 }
11952 final long allocationUs =
11953 mWakeLockAllocationsUs[cluster][speed] / (numWakelocks - i);
Sudheer Shankac57729a2018-02-09 15:44:42 -080011954 cpuTimeUs[speed].addCountLocked(allocationUs, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011955 mWakeLockAllocationsUs[cluster][speed] -= allocationUs;
11956 }
11957 }
11958 }
11959 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070011960 }
11961
Mike Ma3d422c32017-10-25 11:08:57 -070011962 /**
11963 * Take a snapshot of the cpu active times spent by each uid and update the corresponding
11964 * counters.
11965 */
11966 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080011967 public void readKernelUidCpuActiveTimesLocked(boolean onBattery) {
Mike Ma3d422c32017-10-25 11:08:57 -070011968 final long startTimeMs = mClocks.uptimeMillis();
Mike Ma7ab7fcd2019-01-16 15:00:40 -080011969 mCpuUidActiveTimeReader.readDelta((uid, cpuActiveTimesMs) -> {
Mike Ma3d422c32017-10-25 11:08:57 -070011970 uid = mapUid(uid);
11971 if (Process.isIsolated(uid)) {
Mike Ma7ab7fcd2019-01-16 15:00:40 -080011972 mCpuUidActiveTimeReader.removeUid(uid);
Mike Ma3d422c32017-10-25 11:08:57 -070011973 Slog.w(TAG, "Got active times for an isolated uid with no mapping: " + uid);
11974 return;
11975 }
11976 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
11977 Slog.w(TAG, "Got active times for an invalid user's uid " + uid);
Mike Ma7ab7fcd2019-01-16 15:00:40 -080011978 mCpuUidActiveTimeReader.removeUid(uid);
Mike Ma3d422c32017-10-25 11:08:57 -070011979 return;
11980 }
11981 final Uid u = getUidStatsLocked(uid);
Mike Ma2ab01442018-02-13 14:22:47 -080011982 u.mCpuActiveTimeMs.addCountLocked(cpuActiveTimesMs, onBattery);
Mike Ma3d422c32017-10-25 11:08:57 -070011983 });
11984
11985 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
11986 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
11987 Slog.d(TAG, "Reading cpu active times took " + elapsedTimeMs + "ms");
11988 }
11989 }
11990
11991 /**
11992 * Take a snapshot of the cpu cluster times spent by each uid and update the corresponding
11993 * counters.
11994 */
11995 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080011996 public void readKernelUidCpuClusterTimesLocked(boolean onBattery) {
Mike Ma3d422c32017-10-25 11:08:57 -070011997 final long startTimeMs = mClocks.uptimeMillis();
Mike Ma7ab7fcd2019-01-16 15:00:40 -080011998 mCpuUidClusterTimeReader.readDelta((uid, cpuClusterTimesMs) -> {
Mike Ma3d422c32017-10-25 11:08:57 -070011999 uid = mapUid(uid);
12000 if (Process.isIsolated(uid)) {
Mike Ma7ab7fcd2019-01-16 15:00:40 -080012001 mCpuUidClusterTimeReader.removeUid(uid);
Mike Ma3d422c32017-10-25 11:08:57 -070012002 Slog.w(TAG, "Got cluster times for an isolated uid with no mapping: " + uid);
12003 return;
12004 }
12005 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12006 Slog.w(TAG, "Got cluster times for an invalid user's uid " + uid);
Mike Ma7ab7fcd2019-01-16 15:00:40 -080012007 mCpuUidClusterTimeReader.removeUid(uid);
Mike Ma3d422c32017-10-25 11:08:57 -070012008 return;
12009 }
12010 final Uid u = getUidStatsLocked(uid);
Mike Ma2ab01442018-02-13 14:22:47 -080012011 u.mCpuClusterTimesMs.addCountLocked(cpuClusterTimesMs, onBattery);
Mike Ma3d422c32017-10-25 11:08:57 -070012012 });
12013
12014 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12015 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12016 Slog.d(TAG, "Reading cpu cluster times took " + elapsedTimeMs + "ms");
12017 }
12018 }
12019
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012020 boolean setChargingLocked(boolean charging) {
Zhi An Ng11b63622018-12-27 16:43:34 +080012021 // if the device is no longer charging, remove the callback
12022 // if the device is now charging, it means that this is either called
12023 // 1. directly when level >= 90
12024 // 2. or from within the runnable that we deferred
Kweku Adamscf031232019-05-03 16:15:14 -070012025 // For 1. if we have an existing callback, remove it, since we will immediately send a
Zhi An Ng11b63622018-12-27 16:43:34 +080012026 // ACTION_CHARGING
12027 // For 2. we remove existing callback so we don't send multiple ACTION_CHARGING
12028 mHandler.removeCallbacks(mDeferSetCharging);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012029 if (mCharging != charging) {
12030 mCharging = charging;
12031 if (charging) {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012032 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012033 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012034 mHistoryCur.states2 &= ~HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012035 }
12036 mHandler.sendEmptyMessage(MSG_REPORT_CHARGING);
12037 return true;
12038 }
12039 return false;
12040 }
12041
Andreas Gampe3f24e692018-02-05 13:24:28 -080012042 @GuardedBy("this")
Mike Mac2f518a2017-09-19 16:06:03 -070012043 protected void setOnBatteryLocked(final long mSecRealtime, final long mSecUptime,
12044 final boolean onBattery, final int oldStatus, final int level, final int chargeUAh) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012045 boolean doWrite = false;
12046 Message m = mHandler.obtainMessage(MSG_REPORT_POWER_CHANGE);
12047 m.arg1 = onBattery ? 1 : 0;
12048 mHandler.sendMessage(m);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012049
Dianne Hackborn40c87252014-03-19 16:55:40 -070012050 final long uptime = mSecUptime * 1000;
12051 final long realtime = mSecRealtime * 1000;
Mike Mac2f518a2017-09-19 16:06:03 -070012052 final int screenState = mScreenState;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012053 if (onBattery) {
12054 // We will reset our status if we are unplugging after the
12055 // battery was last full, or the level is at 100, or
12056 // we have gone through a significant charge (from a very low
12057 // level to a now very high level).
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080012058 boolean reset = false;
Dianne Hackborn9a755432014-05-15 17:05:22 -070012059 if (!mNoAutoReset && (oldStatus == BatteryManager.BATTERY_STATUS_FULL
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012060 || level >= 90
Hui Yu0ed84f12018-06-20 19:07:56 -070012061 || (mDischargeCurrentLevel < 20 && level >= 80))) {
Dianne Hackborn73d6a822014-09-29 10:52:47 -070012062 Slog.i(TAG, "Resetting battery stats: level=" + level + " status=" + oldStatus
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070012063 + " dischargeLevel=" + mDischargeCurrentLevel
Dianne Hackborn73d6a822014-09-29 10:52:47 -070012064 + " lowAmount=" + getLowDischargeAmountSinceCharge()
12065 + " highAmount=" + getHighDischargeAmountSinceCharge());
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012066 // Before we write, collect a snapshot of the final aggregated
12067 // stats to be reported in the next checkin. Only do this if we have
12068 // a sufficient amount of data to make it interesting.
12069 if (getLowDischargeAmountSinceCharge() >= 20) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080012070 final long startTime = SystemClock.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012071 final Parcel parcel = Parcel.obtain();
12072 writeSummaryToParcel(parcel, true);
Dianne Hackborne17b4452018-01-10 13:15:40 -080012073 final long initialTime = SystemClock.uptimeMillis() - startTime;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012074 BackgroundThread.getHandler().post(new Runnable() {
12075 @Override public void run() {
12076 synchronized (mCheckinFile) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080012077 final long startTime2 = SystemClock.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012078 FileOutputStream stream = null;
12079 try {
12080 stream = mCheckinFile.startWrite();
12081 stream.write(parcel.marshall());
12082 stream.flush();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012083 mCheckinFile.finishWrite(stream);
Dianne Hackborne17b4452018-01-10 13:15:40 -080012084 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
12085 "batterystats-checkin",
12086 initialTime + SystemClock.uptimeMillis() - startTime2);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012087 } catch (IOException e) {
12088 Slog.w("BatteryStats",
12089 "Error writing checkin battery statistics", e);
12090 mCheckinFile.failWrite(stream);
12091 } finally {
12092 parcel.recycle();
12093 }
12094 }
12095 }
12096 });
12097 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012098 doWrite = true;
12099 resetAllStatsLocked();
Ying Wai (Daniel) Fan442ab762017-01-31 22:00:10 -080012100 if (chargeUAh > 0 && level > 0) {
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012101 // Only use the reported coulomb charge value if it is supported and reported.
Ying Wai (Daniel) Fan9238b612017-01-18 15:50:19 -080012102 mEstimatedBatteryCapacity = (int) ((chargeUAh / 1000) / (level / 100.0));
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012103 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012104 mDischargeStartLevel = level;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080012105 reset = true;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012106 mDischargeStepTracker.init();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012107 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012108 if (mCharging) {
12109 setChargingLocked(false);
12110 }
12111 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080012112 mOnBattery = mOnBatteryInternal = true;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012113 mLastDischargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070012114 mMinDischargeStepLevel = level;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012115 mDischargeStepTracker.clearTime();
12116 mDailyDischargeStepTracker.clearTime();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012117 mInitStepMode = mCurStepMode;
12118 mModStepMode = 0;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012119 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012120 mHistoryCur.batteryLevel = (byte)level;
12121 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
12122 if (DEBUG_HISTORY) Slog.v(TAG, "Battery unplugged to: "
12123 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012124 if (reset) {
12125 mRecordingHistory = true;
12126 startRecordingHistory(mSecRealtime, mSecUptime, reset);
12127 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070012128 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012129 mDischargeCurrentLevel = mDischargeUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070012130 if (isScreenOn(screenState)) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012131 mDischargeScreenOnUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070012132 mDischargeScreenDozeUnplugLevel = 0;
12133 mDischargeScreenOffUnplugLevel = 0;
12134 } else if (isScreenDoze(screenState)) {
12135 mDischargeScreenOnUnplugLevel = 0;
12136 mDischargeScreenDozeUnplugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012137 mDischargeScreenOffUnplugLevel = 0;
12138 } else {
12139 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012140 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012141 mDischargeScreenOffUnplugLevel = level;
12142 }
12143 mDischargeAmountScreenOn = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012144 mDischargeAmountScreenDoze = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012145 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012146 updateTimeBasesLocked(true, screenState, uptime, realtime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012147 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012148 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080012149 mOnBattery = mOnBatteryInternal = false;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012150 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012151 mHistoryCur.batteryLevel = (byte)level;
12152 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
12153 if (DEBUG_HISTORY) Slog.v(TAG, "Battery plugged to: "
12154 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -070012155 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012156 mDischargeCurrentLevel = mDischargePlugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012157 if (level < mDischargeUnplugLevel) {
12158 mLowDischargeAmountSinceCharge += mDischargeUnplugLevel-level-1;
12159 mHighDischargeAmountSinceCharge += mDischargeUnplugLevel-level;
12160 }
Mike Mac2f518a2017-09-19 16:06:03 -070012161 updateDischargeScreenLevelsLocked(screenState, screenState);
12162 updateTimeBasesLocked(false, screenState, uptime, realtime);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012163 mChargeStepTracker.init();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012164 mLastChargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070012165 mMaxChargeStepLevel = level;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012166 mInitStepMode = mCurStepMode;
12167 mModStepMode = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012168 }
12169 if (doWrite || (mLastWriteTime + (60 * 1000)) < mSecRealtime) {
Hui Yu0ed84f12018-06-20 19:07:56 -070012170 if (mStatsFile != null && mBatteryStatsHistory.getActiveFile() != null) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012171 writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012172 }
12173 }
12174 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012175
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012176 private void startRecordingHistory(final long elapsedRealtimeMs, final long uptimeMs,
12177 boolean reset) {
12178 mRecordingHistory = true;
12179 mHistoryCur.currentTime = System.currentTimeMillis();
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012180 addHistoryBufferLocked(elapsedRealtimeMs,
Dianne Hackborn37de0982014-05-09 09:32:18 -070012181 reset ? HistoryItem.CMD_RESET : HistoryItem.CMD_CURRENT_TIME,
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012182 mHistoryCur);
12183 mHistoryCur.currentTime = 0;
12184 if (reset) {
12185 initActiveHistoryEventsLocked(elapsedRealtimeMs, uptimeMs);
12186 }
12187 }
12188
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012189 private void recordCurrentTimeChangeLocked(final long currentTime, final long elapsedRealtimeMs,
12190 final long uptimeMs) {
12191 if (mRecordingHistory) {
12192 mHistoryCur.currentTime = currentTime;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012193 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_CURRENT_TIME, mHistoryCur);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012194 mHistoryCur.currentTime = 0;
12195 }
12196 }
12197
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080012198 private void recordShutdownLocked(final long elapsedRealtimeMs, final long uptimeMs) {
12199 if (mRecordingHistory) {
12200 mHistoryCur.currentTime = System.currentTimeMillis();
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012201 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_SHUTDOWN, mHistoryCur);
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080012202 mHistoryCur.currentTime = 0;
12203 }
12204 }
12205
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012206 private void scheduleSyncExternalStatsLocked(String reason, int updateFlags) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012207 if (mExternalSync != null) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012208 mExternalSync.scheduleSync(reason, updateFlags);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070012209 }
12210 }
12211
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012212 // This should probably be exposed in the API, though it's not critical
Bookatz1a1b0462018-01-12 11:47:03 -080012213 public static final int BATTERY_PLUGGED_NONE = OsProtoEnums.BATTERY_PLUGGED_NONE; // = 0
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012214
Andreas Gampe3f24e692018-02-05 13:24:28 -080012215 @GuardedBy("this")
Bookatz8c6571b2017-10-24 15:04:41 -070012216 public void setBatteryStateLocked(final int status, final int health, final int plugType,
12217 final int level, /* not final */ int temp, final int volt, final int chargeUAh,
12218 final int chargeFullUAh) {
Adam Lesinski29ddfe52017-03-29 19:29:00 -070012219 // Temperature is encoded without the signed bit, so clamp any negative temperatures to 0.
12220 temp = Math.max(0, temp);
12221
Bookatz8c6571b2017-10-24 15:04:41 -070012222 reportChangesToStatsLog(mHaveBatteryLevel ? mHistoryCur : null,
Tej Singh40298312018-02-16 00:15:09 -080012223 status, plugType, level);
Bookatz8c6571b2017-10-24 15:04:41 -070012224
Sudheer Shankac57729a2018-02-09 15:44:42 -080012225 final boolean onBattery = isOnBattery(plugType, status);
Joe Onoratoabded112016-02-08 16:49:39 -080012226 final long uptime = mClocks.uptimeMillis();
12227 final long elapsedRealtime = mClocks.elapsedRealtime();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012228 if (!mHaveBatteryLevel) {
12229 mHaveBatteryLevel = true;
12230 // We start out assuming that the device is plugged in (not
12231 // on battery). If our first report is now that we are indeed
12232 // plugged in, then twiddle our state to correctly reflect that
12233 // since we won't be going through the full setOnBattery().
12234 if (onBattery == mOnBattery) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012235 if (onBattery) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012236 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012237 } else {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012238 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012239 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012240 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012241 // Always start out assuming charging, that will be updated later.
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012242 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012243 mHistoryCur.batteryStatus = (byte)status;
12244 mHistoryCur.batteryLevel = (byte)level;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012245 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012246 mMaxChargeStepLevel = mMinDischargeStepLevel =
12247 mLastChargeStepLevel = mLastDischargeStepLevel = level;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012248 mLastChargingStateLevel = level;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012249 } else if (mCurrentBatteryLevel != level || mOnBattery != onBattery) {
12250 recordDailyStatsIfNeededLocked(level >= 100 && onBattery);
12251 }
12252 int oldStatus = mHistoryCur.batteryStatus;
12253 if (onBattery) {
12254 mDischargeCurrentLevel = level;
12255 if (!mRecordingHistory) {
12256 mRecordingHistory = true;
12257 startRecordingHistory(elapsedRealtime, uptime, true);
12258 }
Todd Poynor1acf06a2017-12-07 19:19:35 -080012259 } else if (level < 96 &&
Mike Ma99e57c32018-03-15 14:40:37 -070012260 status != BatteryManager.BATTERY_STATUS_UNKNOWN) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012261 if (!mRecordingHistory) {
12262 mRecordingHistory = true;
12263 startRecordingHistory(elapsedRealtime, uptime, true);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012264 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070012265 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012266 mCurrentBatteryLevel = level;
12267 if (mDischargePlugLevel < 0) {
12268 mDischargePlugLevel = level;
Marco Nelissend8593312009-04-30 14:45:06 -070012269 }
Adam Lesinski926969b2016-04-28 17:31:12 -070012270
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012271 if (onBattery != mOnBattery) {
12272 mHistoryCur.batteryLevel = (byte)level;
12273 mHistoryCur.batteryStatus = (byte)status;
12274 mHistoryCur.batteryHealth = (byte)health;
12275 mHistoryCur.batteryPlugType = (byte)plugType;
12276 mHistoryCur.batteryTemperature = (short)temp;
12277 mHistoryCur.batteryVoltage = (char)volt;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012278 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
12279 // Only record discharges
12280 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
12281 mDischargeCounter.addCountLocked(chargeDiff);
12282 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070012283 if (isScreenDoze(mScreenState)) {
12284 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
12285 }
Mike Ma15313c92017-11-15 17:58:21 -080012286 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
12287 mDischargeLightDozeCounter.addCountLocked(chargeDiff);
12288 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
12289 mDischargeDeepDozeCounter.addCountLocked(chargeDiff);
12290 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012291 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012292 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012293 setOnBatteryLocked(elapsedRealtime, uptime, onBattery, oldStatus, level, chargeUAh);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012294 } else {
12295 boolean changed = false;
12296 if (mHistoryCur.batteryLevel != level) {
12297 mHistoryCur.batteryLevel = (byte)level;
12298 changed = true;
Marco Nelissend8593312009-04-30 14:45:06 -070012299
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012300 // TODO(adamlesinski): Schedule the creation of a HistoryStepDetails record
12301 // which will pull external stats.
Sudheer Shanka0719c6a2018-04-24 11:12:11 -070012302 mExternalSync.scheduleSyncDueToBatteryLevelChange(
12303 mConstants.BATTERY_LEVEL_COLLECTION_DELAY_MS);
Evan Millarc64edde2009-04-18 12:26:32 -070012304 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012305 if (mHistoryCur.batteryStatus != status) {
12306 mHistoryCur.batteryStatus = (byte)status;
12307 changed = true;
12308 }
12309 if (mHistoryCur.batteryHealth != health) {
12310 mHistoryCur.batteryHealth = (byte)health;
12311 changed = true;
12312 }
12313 if (mHistoryCur.batteryPlugType != plugType) {
12314 mHistoryCur.batteryPlugType = (byte)plugType;
12315 changed = true;
12316 }
12317 if (temp >= (mHistoryCur.batteryTemperature+10)
12318 || temp <= (mHistoryCur.batteryTemperature-10)) {
12319 mHistoryCur.batteryTemperature = (short)temp;
12320 changed = true;
12321 }
12322 if (volt > (mHistoryCur.batteryVoltage+20)
12323 || volt < (mHistoryCur.batteryVoltage-20)) {
12324 mHistoryCur.batteryVoltage = (char)volt;
12325 changed = true;
12326 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012327 if (chargeUAh >= (mHistoryCur.batteryChargeUAh+10)
12328 || chargeUAh <= (mHistoryCur.batteryChargeUAh-10)) {
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012329 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
12330 // Only record discharges
12331 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
12332 mDischargeCounter.addCountLocked(chargeDiff);
12333 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070012334 if (isScreenDoze(mScreenState)) {
12335 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
12336 }
Mike Ma15313c92017-11-15 17:58:21 -080012337 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
12338 mDischargeLightDozeCounter.addCountLocked(chargeDiff);
12339 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
12340 mDischargeDeepDozeCounter.addCountLocked(chargeDiff);
12341 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012342 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012343 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski926969b2016-04-28 17:31:12 -070012344 changed = true;
12345 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012346 long modeBits = (((long)mInitStepMode) << STEP_LEVEL_INITIAL_MODE_SHIFT)
12347 | (((long)mModStepMode) << STEP_LEVEL_MODIFIED_MODE_SHIFT)
12348 | (((long)(level&0xff)) << STEP_LEVEL_LEVEL_SHIFT);
12349 if (onBattery) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012350 changed |= setChargingLocked(false);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012351 if (mLastDischargeStepLevel != level && mMinDischargeStepLevel > level) {
12352 mDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
12353 modeBits, elapsedRealtime);
12354 mDailyDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
12355 modeBits, elapsedRealtime);
12356 mLastDischargeStepLevel = level;
12357 mMinDischargeStepLevel = level;
12358 mInitStepMode = mCurStepMode;
12359 mModStepMode = 0;
12360 }
12361 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012362 if (level >= 90) {
12363 // If the battery level is at least 90%, always consider the device to be
12364 // charging even if it happens to go down a level.
12365 changed |= setChargingLocked(true);
Makoto Onuki897f6362019-02-19 12:29:33 -080012366 } else if (!mCharging) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012367 if (mLastChargeStepLevel < level) {
Zhi An Ng11b63622018-12-27 16:43:34 +080012368 // We have not reported that we are charging, but the level has gone up,
12369 // but we would like to not have tons of activity from charging-constraint
12370 // jobs, so instead of reporting ACTION_CHARGING immediately, we defer it.
Zhi An Ng11b63622018-12-27 16:43:34 +080012371 if (!mHandler.hasCallbacks(mDeferSetCharging)) {
12372 mHandler.postDelayed(
12373 mDeferSetCharging,
12374 mConstants.BATTERY_CHARGED_DELAY_MS);
12375 }
12376 } else if (mLastChargeStepLevel > level) {
12377 // if we had deferred a runnable due to charge level increasing, but then
12378 // later the charge level drops (could be due to thermal issues), we don't
12379 // want to trigger the deferred runnable, so remove it here
12380 mHandler.removeCallbacks(mDeferSetCharging);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012381 }
12382 } else {
12383 if (mLastChargeStepLevel > level) {
12384 // We had reported that the device was charging, but here we are with
12385 // power connected and the level going down. Looks like the current
12386 // power supplied isn't enough, so consider the device to now be
12387 // discharging.
12388 changed |= setChargingLocked(false);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012389 }
12390 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012391 if (mLastChargeStepLevel != level && mMaxChargeStepLevel < level) {
12392 mChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
12393 modeBits, elapsedRealtime);
12394 mDailyChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
12395 modeBits, elapsedRealtime);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012396 mMaxChargeStepLevel = level;
12397 mInitStepMode = mCurStepMode;
12398 mModStepMode = 0;
Evan Millarc64edde2009-04-18 12:26:32 -070012399 }
Kweku Adamscf031232019-05-03 16:15:14 -070012400 mLastChargeStepLevel = level;
Evan Millarc64edde2009-04-18 12:26:32 -070012401 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012402 if (changed) {
12403 addHistoryRecordLocked(elapsedRealtime, uptime);
12404 }
Evan Millarc64edde2009-04-18 12:26:32 -070012405 }
Todd Poynor1acf06a2017-12-07 19:19:35 -080012406 if (!onBattery &&
Mike Ma99e57c32018-03-15 14:40:37 -070012407 (status == BatteryManager.BATTERY_STATUS_FULL ||
12408 status == BatteryManager.BATTERY_STATUS_UNKNOWN)) {
Todd Poynor1acf06a2017-12-07 19:19:35 -080012409 // We don't record history while we are plugged in and fully charged
12410 // (or when battery is not present). The next time we are
12411 // unplugged, history will be cleared.
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012412 mRecordingHistory = DEBUG;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080012413 }
Adam Lesinski041d9172016-12-12 12:03:56 -080012414
Jocelyn Dangc627d102017-04-14 13:15:14 -070012415 if (mMinLearnedBatteryCapacity == -1) {
12416 mMinLearnedBatteryCapacity = chargeFullUAh;
12417 } else {
zhouwenjie8a871d82018-07-03 16:17:02 -070012418 mMinLearnedBatteryCapacity = Math.min(mMinLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski041d9172016-12-12 12:03:56 -080012419 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070012420 mMaxLearnedBatteryCapacity = Math.max(mMaxLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski33dac552015-03-09 15:24:48 -070012421 }
12422
Sudheer Shankac57729a2018-02-09 15:44:42 -080012423 public static boolean isOnBattery(int plugType, int status) {
12424 return plugType == BATTERY_PLUGGED_NONE && status != BatteryManager.BATTERY_STATUS_UNKNOWN;
12425 }
12426
Bookatz8c6571b2017-10-24 15:04:41 -070012427 // Inform StatsLog of setBatteryState changes.
12428 // If this is the first reporting, pass in recentPast == null.
12429 private void reportChangesToStatsLog(HistoryItem recentPast,
Tej Singh40298312018-02-16 00:15:09 -080012430 final int status, final int plugType, final int level) {
Bookatz8c6571b2017-10-24 15:04:41 -070012431
12432 if (recentPast == null || recentPast.batteryStatus != status) {
12433 StatsLog.write(StatsLog.CHARGING_STATE_CHANGED, status);
12434 }
12435 if (recentPast == null || recentPast.batteryPlugType != plugType) {
12436 StatsLog.write(StatsLog.PLUGGED_STATE_CHANGED, plugType);
12437 }
12438 if (recentPast == null || recentPast.batteryLevel != level) {
12439 StatsLog.write(StatsLog.BATTERY_LEVEL_CHANGED, level);
12440 }
Bookatz8c6571b2017-10-24 15:04:41 -070012441 }
12442
Mathew Inwoodaf972c82018-08-20 14:13:20 +010012443 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012444 public long getAwakeTimeBattery() {
Mike Ma99e57c32018-03-15 14:40:37 -070012445 // This previously evaluated to mOnBatteryTimeBase.getUptime(getBatteryUptimeLocked());
12446 // for over a decade, but surely that was a mistake.
12447 return getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012448 }
12449
Mathew Inwoodaf972c82018-08-20 14:13:20 +010012450 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012451 public long getAwakeTimePlugged() {
Joe Onoratoabded112016-02-08 16:49:39 -080012452 return (mClocks.uptimeMillis() * 1000) - getAwakeTimeBattery();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012453 }
12454
12455 @Override
12456 public long computeUptime(long curTime, int which) {
Mike Ma99e57c32018-03-15 14:40:37 -070012457 return mUptime + (curTime - mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012458 }
12459
12460 @Override
12461 public long computeRealtime(long curTime, int which) {
Mike Ma99e57c32018-03-15 14:40:37 -070012462 return mRealtime + (curTime - mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012463 }
12464
12465 @Override
Mathew Inwoodaf972c82018-08-20 14:13:20 +010012466 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012467 public long computeBatteryUptime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012468 return mOnBatteryTimeBase.computeUptime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012469 }
12470
12471 @Override
Mathew Inwoodaf972c82018-08-20 14:13:20 +010012472 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012473 public long computeBatteryRealtime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012474 return mOnBatteryTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012475 }
12476
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012477 @Override
12478 public long computeBatteryScreenOffUptime(long curTime, int which) {
12479 return mOnBatteryScreenOffTimeBase.computeUptime(curTime, which);
12480 }
12481
12482 @Override
12483 public long computeBatteryScreenOffRealtime(long curTime, int which) {
12484 return mOnBatteryScreenOffTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012485 }
12486
Dianne Hackborn260c5022014-04-29 11:23:16 -070012487 private long computeTimePerLevel(long[] steps, int numSteps) {
12488 // For now we'll do a simple average across all steps.
12489 if (numSteps <= 0) {
12490 return -1;
12491 }
12492 long total = 0;
12493 for (int i=0; i<numSteps; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012494 total += steps[i] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012495 }
12496 return total / numSteps;
12497 /*
12498 long[] buckets = new long[numSteps];
12499 int numBuckets = 0;
12500 int numToAverage = 4;
12501 int i = 0;
12502 while (i < numSteps) {
12503 long totalTime = 0;
12504 int num = 0;
12505 for (int j=0; j<numToAverage && (i+j)<numSteps; j++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012506 totalTime += steps[i+j] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012507 num++;
12508 }
12509 buckets[numBuckets] = totalTime / num;
12510 numBuckets++;
12511 numToAverage *= 2;
12512 i += num;
12513 }
12514 if (numBuckets < 1) {
12515 return -1;
12516 }
12517 long averageTime = buckets[numBuckets-1];
12518 for (i=numBuckets-2; i>=0; i--) {
12519 averageTime = (averageTime + buckets[i]) / 2;
12520 }
12521 return averageTime;
12522 */
12523 }
12524
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012525 @Override
Mathew Inwoodaf972c82018-08-20 14:13:20 +010012526 @UnsupportedAppUsage
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012527 public long computeBatteryTimeRemaining(long curTime) {
12528 if (!mOnBattery) {
12529 return -1;
12530 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070012531 /* Simple implementation just looks at the average discharge per level across the
12532 entire sample period.
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012533 int discharge = (getLowDischargeAmountSinceCharge()+getHighDischargeAmountSinceCharge())/2;
12534 if (discharge < 2) {
12535 return -1;
12536 }
12537 long duration = computeBatteryRealtime(curTime, STATS_SINCE_CHARGED);
12538 if (duration < 1000*1000) {
12539 return -1;
12540 }
12541 long usPerLevel = duration/discharge;
12542 return usPerLevel * mCurrentBatteryLevel;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012543 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012544 if (mDischargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012545 return -1;
12546 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012547 long msPerLevel = mDischargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012548 if (msPerLevel <= 0) {
12549 return -1;
12550 }
12551 return (msPerLevel * mCurrentBatteryLevel) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012552 }
12553
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012554 @Override
12555 public LevelStepTracker getDischargeLevelStepTracker() {
12556 return mDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012557 }
12558
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012559 @Override
12560 public LevelStepTracker getDailyDischargeLevelStepTracker() {
12561 return mDailyDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012562 }
12563
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012564 @Override
12565 public long computeChargeTimeRemaining(long curTime) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012566 if (mOnBattery) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012567 // Not yet working.
12568 return -1;
12569 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070012570 /* Broken
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012571 int curLevel = mCurrentBatteryLevel;
12572 int plugLevel = mDischargePlugLevel;
12573 if (plugLevel < 0 || curLevel < (plugLevel+1)) {
12574 return -1;
12575 }
12576 long duration = computeBatteryRealtime(curTime, STATS_SINCE_UNPLUGGED);
12577 if (duration < 1000*1000) {
12578 return -1;
12579 }
12580 long usPerLevel = duration/(curLevel-plugLevel);
12581 return usPerLevel * (100-curLevel);
Dianne Hackborn260c5022014-04-29 11:23:16 -070012582 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012583 if (mChargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012584 return -1;
12585 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012586 long msPerLevel = mChargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012587 if (msPerLevel <= 0) {
12588 return -1;
12589 }
12590 return (msPerLevel * (100-mCurrentBatteryLevel)) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012591 }
12592
Siddharth Raya1fd0572017-11-13 14:20:47 -080012593 /*@hide */
12594 public CellularBatteryStats getCellularBatteryStats() {
12595 CellularBatteryStats s = new CellularBatteryStats();
12596 final int which = STATS_SINCE_CHARGED;
12597 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12598 final ControllerActivityCounter counter = getModemControllerActivity();
Siddharth Rayed754702018-02-15 12:44:37 -080012599 final long sleepTimeMs = counter.getSleepTimeCounter().getCountLocked(which);
Siddharth Raya1fd0572017-11-13 14:20:47 -080012600 final long idleTimeMs = counter.getIdleTimeCounter().getCountLocked(which);
12601 final long rxTimeMs = counter.getRxTimeCounter().getCountLocked(which);
12602 final long energyConsumedMaMs = counter.getPowerCounter().getCountLocked(which);
Blake Kragtencb308d92019-01-28 10:54:13 -080012603 final long monitoredRailChargeConsumedMaMs =
12604 counter.getMonitoredRailChargeConsumedMaMs().getCountLocked(which);
Siddharth Raya1fd0572017-11-13 14:20:47 -080012605 long[] timeInRatMs = new long[BatteryStats.NUM_DATA_CONNECTION_TYPES];
12606 for (int i = 0; i < timeInRatMs.length; i++) {
12607 timeInRatMs[i] = getPhoneDataConnectionTime(i, rawRealTime, which) / 1000;
12608 }
12609 long[] timeInRxSignalStrengthLevelMs = new long[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
12610 for (int i = 0; i < timeInRxSignalStrengthLevelMs.length; i++) {
12611 timeInRxSignalStrengthLevelMs[i]
12612 = getPhoneSignalStrengthTime(i, rawRealTime, which) / 1000;
12613 }
12614 long[] txTimeMs = new long[Math.min(ModemActivityInfo.TX_POWER_LEVELS,
12615 counter.getTxTimeCounters().length)];
12616 long totalTxTimeMs = 0;
12617 for (int i = 0; i < txTimeMs.length; i++) {
12618 txTimeMs[i] = counter.getTxTimeCounters()[i].getCountLocked(which);
12619 totalTxTimeMs += txTimeMs[i];
12620 }
SongFerngWang8a5307c2019-11-04 22:17:47 +080012621 s.setLoggingDurationMillis(computeBatteryRealtime(rawRealTime, which) / 1000);
12622 s.setKernelActiveTimeMillis(getMobileRadioActiveTime(rawRealTime, which) / 1000);
Siddharth Raya1fd0572017-11-13 14:20:47 -080012623 s.setNumPacketsTx(getNetworkActivityPackets(NETWORK_MOBILE_TX_DATA, which));
12624 s.setNumBytesTx(getNetworkActivityBytes(NETWORK_MOBILE_TX_DATA, which));
12625 s.setNumPacketsRx(getNetworkActivityPackets(NETWORK_MOBILE_RX_DATA, which));
12626 s.setNumBytesRx(getNetworkActivityBytes(NETWORK_MOBILE_RX_DATA, which));
SongFerngWang8a5307c2019-11-04 22:17:47 +080012627 s.setSleepTimeMillis(sleepTimeMs);
12628 s.setIdleTimeMillis(idleTimeMs);
12629 s.setRxTimeMillis(rxTimeMs);
12630 s.setEnergyConsumedMaMillis(energyConsumedMaMs);
12631 s.setTimeInRatMicros(timeInRatMs);
12632 s.setTimeInRxSignalStrengthLevelMicros(timeInRxSignalStrengthLevelMs);
12633 s.setTxTimeMillis(txTimeMs);
12634 s.setMonitoredRailChargeConsumedMaMillis(monitoredRailChargeConsumedMaMs);
Siddharth Raya1fd0572017-11-13 14:20:47 -080012635 return s;
12636 }
12637
Blake Kragtencb308d92019-01-28 10:54:13 -080012638 /*@hide */
12639 public WifiBatteryStats getWifiBatteryStats() {
12640 WifiBatteryStats s = new WifiBatteryStats();
12641 final int which = STATS_SINCE_CHARGED;
12642 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12643 final ControllerActivityCounter counter = getWifiControllerActivity();
12644 final long idleTimeMs = counter.getIdleTimeCounter().getCountLocked(which);
12645 final long scanTimeMs = counter.getScanTimeCounter().getCountLocked(which);
12646 final long rxTimeMs = counter.getRxTimeCounter().getCountLocked(which);
12647 final long txTimeMs = counter.getTxTimeCounters()[0].getCountLocked(which);
12648 final long totalControllerActivityTimeMs
12649 = computeBatteryRealtime(SystemClock.elapsedRealtime() * 1000, which) / 1000;
12650 final long sleepTimeMs
12651 = totalControllerActivityTimeMs - (idleTimeMs + rxTimeMs + txTimeMs);
12652 final long energyConsumedMaMs = counter.getPowerCounter().getCountLocked(which);
12653 final long monitoredRailChargeConsumedMaMs =
12654 counter.getMonitoredRailChargeConsumedMaMs().getCountLocked(which);
12655 long numAppScanRequest = 0;
12656 for (int i = 0; i < mUidStats.size(); i++) {
12657 numAppScanRequest += mUidStats.valueAt(i).mWifiScanTimer.getCountLocked(which);
12658 }
12659 long[] timeInStateMs = new long[NUM_WIFI_STATES];
12660 for (int i=0; i<NUM_WIFI_STATES; i++) {
Siddharth Rayb50a6842017-12-14 15:15:28 -080012661 timeInStateMs[i] = getWifiStateTime(i, rawRealTime, which) / 1000;
Blake Kragtencb308d92019-01-28 10:54:13 -080012662 }
12663 long[] timeInSupplStateMs = new long[NUM_WIFI_SUPPL_STATES];
12664 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
12665 timeInSupplStateMs[i] = getWifiSupplStateTime(i, rawRealTime, which) / 1000;
12666 }
12667 long[] timeSignalStrengthTimeMs = new long[NUM_WIFI_SIGNAL_STRENGTH_BINS];
12668 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
12669 timeSignalStrengthTimeMs[i] = getWifiSignalStrengthTime(i, rawRealTime, which) / 1000;
12670 }
Roshan Pius848513e2019-10-11 13:44:00 -070012671 s.setLoggingDurationMillis(computeBatteryRealtime(rawRealTime, which) / 1000);
12672 s.setKernelActiveTimeMillis(getWifiActiveTime(rawRealTime, which) / 1000);
Blake Kragtencb308d92019-01-28 10:54:13 -080012673 s.setNumPacketsTx(getNetworkActivityPackets(NETWORK_WIFI_TX_DATA, which));
12674 s.setNumBytesTx(getNetworkActivityBytes(NETWORK_WIFI_TX_DATA, which));
12675 s.setNumPacketsRx(getNetworkActivityPackets(NETWORK_WIFI_RX_DATA, which));
12676 s.setNumBytesRx(getNetworkActivityBytes(NETWORK_WIFI_RX_DATA, which));
Roshan Pius848513e2019-10-11 13:44:00 -070012677 s.setSleepTimeMillis(sleepTimeMs);
12678 s.setIdleTimeMillis(idleTimeMs);
12679 s.setRxTimeMillis(rxTimeMs);
12680 s.setTxTimeMillis(txTimeMs);
12681 s.setScanTimeMillis(scanTimeMs);
12682 s.setEnergyConsumedMaMillis(energyConsumedMaMs);
Blake Kragtencb308d92019-01-28 10:54:13 -080012683 s.setNumAppScanRequest(numAppScanRequest);
Roshan Pius848513e2019-10-11 13:44:00 -070012684 s.setTimeInStateMillis(timeInStateMs);
12685 s.setTimeInSupplicantStateMillis(timeInSupplStateMs);
12686 s.setTimeInRxSignalStrengthLevelMillis(timeSignalStrengthTimeMs);
12687 s.setMonitoredRailChargeConsumedMaMillis(monitoredRailChargeConsumedMaMs);
Blake Kragtencb308d92019-01-28 10:54:13 -080012688 return s;
12689 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080012690
Siddharth Ray78ccaf52017-12-23 16:16:21 -080012691 /*@hide */
12692 public GpsBatteryStats getGpsBatteryStats() {
12693 GpsBatteryStats s = new GpsBatteryStats();
12694 final int which = STATS_SINCE_CHARGED;
12695 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12696 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
12697 s.setEnergyConsumedMaMs(getGpsBatteryDrainMaMs());
12698 long[] time = new long[GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS];
12699 for (int i=0; i<time.length; i++) {
12700 time[i] = getGpsSignalQualityTime(i, rawRealTime, which) / 1000;
12701 }
12702 s.setTimeInGpsSignalQualityLevel(time);
12703 return s;
12704 }
12705
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012706 @Override
12707 public LevelStepTracker getChargeLevelStepTracker() {
12708 return mChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012709 }
12710
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012711 @Override
12712 public LevelStepTracker getDailyChargeLevelStepTracker() {
12713 return mDailyChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012714 }
12715
Dianne Hackborn88e98df2015-03-23 13:29:14 -070012716 @Override
12717 public ArrayList<PackageChange> getDailyPackageChanges() {
12718 return mDailyPackageChanges;
12719 }
12720
Joe Onoratoe1acd632016-02-23 13:25:10 -080012721 protected long getBatteryUptimeLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080012722 return mOnBatteryTimeBase.getUptime(mClocks.uptimeMillis() * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012723 }
12724
12725 @Override
12726 public long getBatteryUptime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012727 return mOnBatteryTimeBase.getUptime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012728 }
12729
12730 @Override
Mathew Inwoodaf972c82018-08-20 14:13:20 +010012731 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012732 public long getBatteryRealtime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012733 return mOnBatteryTimeBase.getRealtime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012734 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -070012735
The Android Open Source Project10592532009-03-18 17:39:46 -070012736 @Override
Mathew Inwoodaf972c82018-08-20 14:13:20 +010012737 @UnsupportedAppUsage
Evan Millar633a1742009-04-02 16:36:33 -070012738 public int getDischargeStartLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070012739 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070012740 return getDischargeStartLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070012741 }
12742 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012743
Evan Millar633a1742009-04-02 16:36:33 -070012744 public int getDischargeStartLevelLocked() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012745 return mDischargeUnplugLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070012746 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012747
The Android Open Source Project10592532009-03-18 17:39:46 -070012748 @Override
Mathew Inwoodaf972c82018-08-20 14:13:20 +010012749 @UnsupportedAppUsage
Evan Millar633a1742009-04-02 16:36:33 -070012750 public int getDischargeCurrentLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070012751 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070012752 return getDischargeCurrentLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070012753 }
12754 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012755
Evan Millar633a1742009-04-02 16:36:33 -070012756 public int getDischargeCurrentLevelLocked() {
Dianne Hackborne4a59512010-12-07 11:08:07 -080012757 return mDischargeCurrentLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070012758 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012759
Amith Yamasanie43530a2009-08-21 13:11:37 -070012760 @Override
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012761 public int getLowDischargeAmountSinceCharge() {
12762 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080012763 int val = mLowDischargeAmountSinceCharge;
12764 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
12765 val += mDischargeUnplugLevel-mDischargeCurrentLevel-1;
12766 }
12767 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012768 }
12769 }
12770
12771 @Override
12772 public int getHighDischargeAmountSinceCharge() {
12773 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080012774 int val = mHighDischargeAmountSinceCharge;
12775 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
12776 val += mDischargeUnplugLevel-mDischargeCurrentLevel;
12777 }
12778 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012779 }
12780 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070012781
12782 @Override
Mathew Inwoodaf972c82018-08-20 14:13:20 +010012783 @UnsupportedAppUsage
Dianne Hackborn40c87252014-03-19 16:55:40 -070012784 public int getDischargeAmount(int which) {
12785 int dischargeAmount = which == STATS_SINCE_CHARGED
12786 ? getHighDischargeAmountSinceCharge()
12787 : (getDischargeStartLevel() - getDischargeCurrentLevel());
12788 if (dischargeAmount < 0) {
12789 dischargeAmount = 0;
12790 }
12791 return dischargeAmount;
12792 }
12793
Mike Mac2f518a2017-09-19 16:06:03 -070012794 @Override
Mathew Inwoodaf972c82018-08-20 14:13:20 +010012795 @UnsupportedAppUsage
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012796 public int getDischargeAmountScreenOn() {
12797 synchronized(this) {
12798 int val = mDischargeAmountScreenOn;
Mike Mac2f518a2017-09-19 16:06:03 -070012799 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012800 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
12801 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
12802 }
12803 return val;
12804 }
12805 }
12806
Mike Mac2f518a2017-09-19 16:06:03 -070012807 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012808 public int getDischargeAmountScreenOnSinceCharge() {
12809 synchronized(this) {
12810 int val = mDischargeAmountScreenOnSinceCharge;
Mike Mac2f518a2017-09-19 16:06:03 -070012811 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012812 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
12813 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
12814 }
12815 return val;
12816 }
12817 }
12818
Mike Mac2f518a2017-09-19 16:06:03 -070012819 @Override
Mathew Inwoodaf972c82018-08-20 14:13:20 +010012820 @UnsupportedAppUsage
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012821 public int getDischargeAmountScreenOff() {
12822 synchronized(this) {
12823 int val = mDischargeAmountScreenOff;
Mike Mac2f518a2017-09-19 16:06:03 -070012824 if (mOnBattery && isScreenOff(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012825 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
12826 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
12827 }
Mike Mac2f518a2017-09-19 16:06:03 -070012828 // For backward compatibility, doze discharge is counted into screen off.
12829 return val + getDischargeAmountScreenDoze();
12830 }
12831 }
12832
12833 @Override
12834 public int getDischargeAmountScreenOffSinceCharge() {
12835 synchronized(this) {
12836 int val = mDischargeAmountScreenOffSinceCharge;
12837 if (mOnBattery && isScreenOff(mScreenState)
12838 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
12839 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
12840 }
12841 // For backward compatibility, doze discharge is counted into screen off.
12842 return val + getDischargeAmountScreenDozeSinceCharge();
12843 }
12844 }
12845
12846 @Override
12847 public int getDischargeAmountScreenDoze() {
12848 synchronized(this) {
12849 int val = mDischargeAmountScreenDoze;
12850 if (mOnBattery && isScreenDoze(mScreenState)
12851 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
12852 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
12853 }
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012854 return val;
12855 }
12856 }
12857
Mike Mac2f518a2017-09-19 16:06:03 -070012858 @Override
12859 public int getDischargeAmountScreenDozeSinceCharge() {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012860 synchronized(this) {
Mike Mac2f518a2017-09-19 16:06:03 -070012861 int val = mDischargeAmountScreenDozeSinceCharge;
12862 if (mOnBattery && isScreenDoze(mScreenState)
12863 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
12864 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012865 }
12866 return val;
12867 }
12868 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012869
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012870 /**
12871 * Retrieve the statistics object for a particular uid, creating if needed.
12872 */
Mathew Inwoodaf972c82018-08-20 14:13:20 +010012873 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012874 public Uid getUidStatsLocked(int uid) {
12875 Uid u = mUidStats.get(uid);
12876 if (u == null) {
Joe Onoratoabded112016-02-08 16:49:39 -080012877 u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012878 mUidStats.put(uid, u);
12879 }
12880 return u;
12881 }
12882
Sudheer Shankab2f83c12017-11-13 19:25:01 -080012883 /**
12884 * Retrieve the statistics object for a particular uid. Returns null if the object is not
12885 * available.
12886 */
12887 public Uid getAvailableUidStatsLocked(int uid) {
12888 Uid u = mUidStats.get(uid);
12889 return u;
12890 }
12891
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070012892 public void onCleanupUserLocked(int userId) {
12893 final int firstUidForUser = UserHandle.getUid(userId, 0);
12894 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
Mike Ma234d1822018-03-13 18:53:21 -070012895 mPendingRemovedUids.add(
12896 new UidToRemove(firstUidForUser, lastUidForUser, mClocks.elapsedRealtime()));
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070012897 }
12898
12899 public void onUserRemovedLocked(int userId) {
12900 final int firstUidForUser = UserHandle.getUid(userId, 0);
12901 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
12902 mUidStats.put(firstUidForUser, null);
12903 mUidStats.put(lastUidForUser, null);
12904 final int firstIndex = mUidStats.indexOfKey(firstUidForUser);
12905 final int lastIndex = mUidStats.indexOfKey(lastUidForUser);
Hui Yu8e88e952018-07-23 17:59:59 -070012906 for (int i = firstIndex; i <= lastIndex; i++) {
12907 final Uid uid = mUidStats.valueAt(i);
12908 if (uid != null) {
12909 uid.detachFromTimeBase();
12910 }
12911 }
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070012912 mUidStats.removeAtRange(firstIndex, lastIndex - firstIndex + 1);
12913 }
12914
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012915 /**
12916 * Remove the statistics object for a particular uid.
12917 */
Mathew Inwoodaf972c82018-08-20 14:13:20 +010012918 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012919 public void removeUidStatsLocked(int uid) {
Hui Yu8e88e952018-07-23 17:59:59 -070012920 final Uid u = mUidStats.get(uid);
12921 if (u != null) {
12922 u.detachFromTimeBase();
12923 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012924 mUidStats.remove(uid);
Mike Ma234d1822018-03-13 18:53:21 -070012925 mPendingRemovedUids.add(new UidToRemove(uid, mClocks.elapsedRealtime()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012926 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -070012927
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012928 /**
12929 * Retrieve the statistics object for a particular process, creating
12930 * if needed.
12931 */
Mathew Inwoodaf972c82018-08-20 14:13:20 +010012932 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012933 public Uid.Proc getProcessStatsLocked(int uid, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070012934 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012935 Uid u = getUidStatsLocked(uid);
12936 return u.getProcessStatsLocked(name);
12937 }
12938
12939 /**
12940 * Retrieve the statistics object for a particular process, creating
12941 * if needed.
12942 */
Mathew Inwoodaf972c82018-08-20 14:13:20 +010012943 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012944 public Uid.Pkg getPackageStatsLocked(int uid, String pkg) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070012945 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012946 Uid u = getUidStatsLocked(uid);
12947 return u.getPackageStatsLocked(pkg);
12948 }
12949
12950 /**
12951 * Retrieve the statistics object for a particular service, creating
12952 * if needed.
12953 */
Mathew Inwoodaf972c82018-08-20 14:13:20 +010012954 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012955 public Uid.Pkg.Serv getServiceStatsLocked(int uid, String pkg, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070012956 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012957 Uid u = getUidStatsLocked(uid);
12958 return u.getServiceStatsLocked(pkg, name);
12959 }
12960
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012961 public void shutdownLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080012962 recordShutdownLocked(mClocks.elapsedRealtime(), mClocks.uptimeMillis());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070012963 writeSyncLocked();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012964 mShuttingDown = true;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070012965 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012966
Sudheer Shanka5c19b892018-01-05 17:25:46 -080012967 public boolean trackPerProcStateCpuTimes() {
12968 return mConstants.TRACK_CPU_TIMES_BY_PROC_STATE && mPerProcStateCpuTimesAvailable;
12969 }
12970
12971 public void systemServicesReady(Context context) {
12972 mConstants.startObserving(context.getContentResolver());
Mike Mafbc01fc2018-04-02 10:28:28 -070012973 registerUsbStateReceiver(context);
Sudheer Shanka5c19b892018-01-05 17:25:46 -080012974 }
12975
12976 @VisibleForTesting
12977 public final class Constants extends ContentObserver {
12978 public static final String KEY_TRACK_CPU_TIMES_BY_PROC_STATE
12979 = "track_cpu_times_by_proc_state";
Mike Mafae87da2018-01-19 20:07:20 -080012980 public static final String KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME
12981 = "track_cpu_active_cluster_time";
Sudheer Shankac20379e2018-02-15 00:06:21 -080012982 public static final String KEY_PROC_STATE_CPU_TIMES_READ_DELAY_MS
12983 = "proc_state_cpu_times_read_delay_ms";
Mike Ma2ab01442018-02-13 14:22:47 -080012984 public static final String KEY_KERNEL_UID_READERS_THROTTLE_TIME
12985 = "kernel_uid_readers_throttle_time";
Mike Ma234d1822018-03-13 18:53:21 -070012986 public static final String KEY_UID_REMOVE_DELAY_MS
12987 = "uid_remove_delay_ms";
Sudheer Shankae56013a2018-04-23 11:22:15 -070012988 public static final String KEY_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS
12989 = "external_stats_collection_rate_limit_ms";
Sudheer Shanka0719c6a2018-04-24 11:12:11 -070012990 public static final String KEY_BATTERY_LEVEL_COLLECTION_DELAY_MS
12991 = "battery_level_collection_delay_ms";
Hui Yu0ed84f12018-06-20 19:07:56 -070012992 public static final String KEY_MAX_HISTORY_FILES = "max_history_files";
12993 public static final String KEY_MAX_HISTORY_BUFFER_KB = "max_history_buffer_kb";
Zhi An Ng11b63622018-12-27 16:43:34 +080012994 public static final String KEY_BATTERY_CHARGED_DELAY_MS =
12995 "battery_charged_delay_ms";
Sudheer Shanka5c19b892018-01-05 17:25:46 -080012996
Sudheer Shanka71f62492018-07-13 10:41:03 -070012997 private static final boolean DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE = false;
Mike Mafae87da2018-01-19 20:07:20 -080012998 private static final boolean DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME = true;
Sudheer Shankac20379e2018-02-15 00:06:21 -080012999 private static final long DEFAULT_PROC_STATE_CPU_TIMES_READ_DELAY_MS = 5_000;
Mike Ma7ab7fcd2019-01-16 15:00:40 -080013000 private static final long DEFAULT_KERNEL_UID_READERS_THROTTLE_TIME = 1_000;
Mike Ma234d1822018-03-13 18:53:21 -070013001 private static final long DEFAULT_UID_REMOVE_DELAY_MS = 5L * 60L * 1000L;
Sudheer Shankae56013a2018-04-23 11:22:15 -070013002 private static final long DEFAULT_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS = 600_000;
Sudheer Shanka0719c6a2018-04-24 11:12:11 -070013003 private static final long DEFAULT_BATTERY_LEVEL_COLLECTION_DELAY_MS = 300_000;
Hui Yu0ed84f12018-06-20 19:07:56 -070013004 private static final int DEFAULT_MAX_HISTORY_FILES = 32;
13005 private static final int DEFAULT_MAX_HISTORY_BUFFER_KB = 128; /*Kilo Bytes*/
13006 private static final int DEFAULT_MAX_HISTORY_FILES_LOW_RAM_DEVICE = 64;
13007 private static final int DEFAULT_MAX_HISTORY_BUFFER_LOW_RAM_DEVICE_KB = 64; /*Kilo Bytes*/
Zhi An Ng11b63622018-12-27 16:43:34 +080013008 private static final int DEFAULT_BATTERY_CHARGED_DELAY_MS = 900000; /* 15 min */
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013009
13010 public boolean TRACK_CPU_TIMES_BY_PROC_STATE = DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE;
Mike Mafae87da2018-01-19 20:07:20 -080013011 public boolean TRACK_CPU_ACTIVE_CLUSTER_TIME = DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013012 public long PROC_STATE_CPU_TIMES_READ_DELAY_MS = DEFAULT_PROC_STATE_CPU_TIMES_READ_DELAY_MS;
Mike Ma7ab7fcd2019-01-16 15:00:40 -080013013 /* Do not set default value for KERNEL_UID_READERS_THROTTLE_TIME. Need to trigger an
13014 * update when startObserving. */
13015 public long KERNEL_UID_READERS_THROTTLE_TIME;
Mike Ma234d1822018-03-13 18:53:21 -070013016 public long UID_REMOVE_DELAY_MS = DEFAULT_UID_REMOVE_DELAY_MS;
Sudheer Shankae56013a2018-04-23 11:22:15 -070013017 public long EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS
13018 = DEFAULT_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS;
Sudheer Shanka0719c6a2018-04-24 11:12:11 -070013019 public long BATTERY_LEVEL_COLLECTION_DELAY_MS
13020 = DEFAULT_BATTERY_LEVEL_COLLECTION_DELAY_MS;
Hui Yu0ed84f12018-06-20 19:07:56 -070013021 public int MAX_HISTORY_FILES;
13022 public int MAX_HISTORY_BUFFER; /*Bytes*/
Zhi An Ng11b63622018-12-27 16:43:34 +080013023 public int BATTERY_CHARGED_DELAY_MS = DEFAULT_BATTERY_CHARGED_DELAY_MS;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013024
13025 private ContentResolver mResolver;
13026 private final KeyValueListParser mParser = new KeyValueListParser(',');
13027
13028 public Constants(Handler handler) {
13029 super(handler);
Hui Yu0ed84f12018-06-20 19:07:56 -070013030 if (ActivityManager.isLowRamDeviceStatic()) {
13031 MAX_HISTORY_FILES = DEFAULT_MAX_HISTORY_FILES_LOW_RAM_DEVICE;
13032 MAX_HISTORY_BUFFER = DEFAULT_MAX_HISTORY_BUFFER_LOW_RAM_DEVICE_KB * 1024;
13033 } else {
13034 MAX_HISTORY_FILES = DEFAULT_MAX_HISTORY_FILES;
13035 MAX_HISTORY_BUFFER = DEFAULT_MAX_HISTORY_BUFFER_KB * 1024;
13036 }
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013037 }
13038
13039 public void startObserving(ContentResolver resolver) {
13040 mResolver = resolver;
13041 mResolver.registerContentObserver(
13042 Settings.Global.getUriFor(Settings.Global.BATTERY_STATS_CONSTANTS),
13043 false /* notifyForDescendants */, this);
Ng Zhi An09411202019-01-23 11:46:50 -080013044 mResolver.registerContentObserver(
13045 Settings.Global.getUriFor(Settings.Global.BATTERY_CHARGING_STATE_UPDATE_DELAY),
13046 false /* notifyForDescendants */, this);
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013047 updateConstants();
13048 }
13049
13050 @Override
13051 public void onChange(boolean selfChange, Uri uri) {
Ng Zhi An09411202019-01-23 11:46:50 -080013052 if (uri.equals(
13053 Settings.Global.getUriFor(
13054 Settings.Global.BATTERY_CHARGING_STATE_UPDATE_DELAY))) {
13055 synchronized (BatteryStatsImpl.this) {
13056 updateBatteryChargedDelayMsLocked();
13057 }
13058 return;
13059 }
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013060 updateConstants();
13061 }
13062
13063 private void updateConstants() {
13064 synchronized (BatteryStatsImpl.this) {
13065 try {
13066 mParser.setString(Settings.Global.getString(mResolver,
13067 Settings.Global.BATTERY_STATS_CONSTANTS));
13068 } catch (IllegalArgumentException e) {
13069 // Failed to parse the settings string, log this and move on
13070 // with defaults.
13071 Slog.e(TAG, "Bad batterystats settings", e);
13072 }
13073
13074 updateTrackCpuTimesByProcStateLocked(TRACK_CPU_TIMES_BY_PROC_STATE,
13075 mParser.getBoolean(KEY_TRACK_CPU_TIMES_BY_PROC_STATE,
13076 DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE));
Mike Mafae87da2018-01-19 20:07:20 -080013077 TRACK_CPU_ACTIVE_CLUSTER_TIME = mParser.getBoolean(
13078 KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME, DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME);
Sudheer Shankac20379e2018-02-15 00:06:21 -080013079 updateProcStateCpuTimesReadDelayMs(PROC_STATE_CPU_TIMES_READ_DELAY_MS,
13080 mParser.getLong(KEY_PROC_STATE_CPU_TIMES_READ_DELAY_MS,
Mike Ma2ab01442018-02-13 14:22:47 -080013081 DEFAULT_PROC_STATE_CPU_TIMES_READ_DELAY_MS));
13082 updateKernelUidReadersThrottleTime(KERNEL_UID_READERS_THROTTLE_TIME,
13083 mParser.getLong(KEY_KERNEL_UID_READERS_THROTTLE_TIME,
13084 DEFAULT_KERNEL_UID_READERS_THROTTLE_TIME));
Mike Ma234d1822018-03-13 18:53:21 -070013085 updateUidRemoveDelay(
13086 mParser.getLong(KEY_UID_REMOVE_DELAY_MS, DEFAULT_UID_REMOVE_DELAY_MS));
Sudheer Shankae56013a2018-04-23 11:22:15 -070013087 EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS = mParser.getLong(
13088 KEY_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS,
13089 DEFAULT_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS);
Sudheer Shanka0719c6a2018-04-24 11:12:11 -070013090 BATTERY_LEVEL_COLLECTION_DELAY_MS = mParser.getLong(
13091 KEY_BATTERY_LEVEL_COLLECTION_DELAY_MS,
13092 DEFAULT_BATTERY_LEVEL_COLLECTION_DELAY_MS);
Hui Yu0ed84f12018-06-20 19:07:56 -070013093
13094 MAX_HISTORY_FILES = mParser.getInt(KEY_MAX_HISTORY_FILES,
13095 ActivityManager.isLowRamDeviceStatic() ?
13096 DEFAULT_MAX_HISTORY_FILES_LOW_RAM_DEVICE
13097 : DEFAULT_MAX_HISTORY_FILES);
13098 MAX_HISTORY_BUFFER = mParser.getInt(KEY_MAX_HISTORY_BUFFER_KB,
13099 ActivityManager.isLowRamDeviceStatic() ?
13100 DEFAULT_MAX_HISTORY_BUFFER_LOW_RAM_DEVICE_KB
13101 : DEFAULT_MAX_HISTORY_BUFFER_KB)
13102 * 1024;
Ng Zhi An09411202019-01-23 11:46:50 -080013103 updateBatteryChargedDelayMsLocked();
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013104 }
13105 }
13106
Ng Zhi An09411202019-01-23 11:46:50 -080013107 private void updateBatteryChargedDelayMsLocked() {
13108 // a negative value indicates that we should ignore this override
13109 final int delay = Settings.Global.getInt(mResolver,
13110 Settings.Global.BATTERY_CHARGING_STATE_UPDATE_DELAY,
13111 -1);
13112
13113 BATTERY_CHARGED_DELAY_MS = delay >= 0 ? delay : mParser.getInt(
13114 KEY_BATTERY_CHARGED_DELAY_MS,
13115 DEFAULT_BATTERY_CHARGED_DELAY_MS);
13116 }
13117
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013118 private void updateTrackCpuTimesByProcStateLocked(boolean wasEnabled, boolean isEnabled) {
13119 TRACK_CPU_TIMES_BY_PROC_STATE = isEnabled;
13120 if (isEnabled && !wasEnabled) {
Sudheer Shanka020239d2018-07-16 18:00:46 -070013121 mIsPerProcessStateCpuDataStale = true;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013122 mExternalSync.scheduleCpuSyncDueToSettingChange();
Sudheer Shankac20379e2018-02-15 00:06:21 -080013123
Mike Ma234d1822018-03-13 18:53:21 -070013124 mNumSingleUidCpuTimeReads = 0;
13125 mNumBatchedSingleUidCpuTimeReads = 0;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013126 mCpuTimeReadsTrackingStartTime = mClocks.uptimeMillis();
13127 }
13128 }
13129
13130 private void updateProcStateCpuTimesReadDelayMs(long oldDelayMillis, long newDelayMillis) {
13131 PROC_STATE_CPU_TIMES_READ_DELAY_MS = newDelayMillis;
13132 if (oldDelayMillis != newDelayMillis) {
Mike Ma234d1822018-03-13 18:53:21 -070013133 mNumSingleUidCpuTimeReads = 0;
13134 mNumBatchedSingleUidCpuTimeReads = 0;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013135 mCpuTimeReadsTrackingStartTime = mClocks.uptimeMillis();
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013136 }
13137 }
13138
Mike Ma2ab01442018-02-13 14:22:47 -080013139 private void updateKernelUidReadersThrottleTime(long oldTimeMs, long newTimeMs) {
13140 KERNEL_UID_READERS_THROTTLE_TIME = newTimeMs;
13141 if (oldTimeMs != newTimeMs) {
Mike Ma7ab7fcd2019-01-16 15:00:40 -080013142 mCpuUidUserSysTimeReader.setThrottle(KERNEL_UID_READERS_THROTTLE_TIME);
13143 mCpuUidFreqTimeReader.setThrottle(KERNEL_UID_READERS_THROTTLE_TIME);
13144 mCpuUidActiveTimeReader.setThrottle(KERNEL_UID_READERS_THROTTLE_TIME);
13145 mCpuUidClusterTimeReader
13146 .setThrottle(KERNEL_UID_READERS_THROTTLE_TIME);
Mike Ma2ab01442018-02-13 14:22:47 -080013147 }
13148 }
13149
Mike Ma234d1822018-03-13 18:53:21 -070013150 private void updateUidRemoveDelay(long newTimeMs) {
13151 UID_REMOVE_DELAY_MS = newTimeMs;
13152 clearPendingRemovedUids();
13153 }
13154
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013155 public void dumpLocked(PrintWriter pw) {
13156 pw.print(KEY_TRACK_CPU_TIMES_BY_PROC_STATE); pw.print("=");
13157 pw.println(TRACK_CPU_TIMES_BY_PROC_STATE);
Mike Mafae87da2018-01-19 20:07:20 -080013158 pw.print(KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME); pw.print("=");
13159 pw.println(TRACK_CPU_ACTIVE_CLUSTER_TIME);
Sudheer Shankac20379e2018-02-15 00:06:21 -080013160 pw.print(KEY_PROC_STATE_CPU_TIMES_READ_DELAY_MS); pw.print("=");
13161 pw.println(PROC_STATE_CPU_TIMES_READ_DELAY_MS);
Mike Ma2ab01442018-02-13 14:22:47 -080013162 pw.print(KEY_KERNEL_UID_READERS_THROTTLE_TIME); pw.print("=");
13163 pw.println(KERNEL_UID_READERS_THROTTLE_TIME);
Sudheer Shankae56013a2018-04-23 11:22:15 -070013164 pw.print(KEY_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS); pw.print("=");
13165 pw.println(EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS);
Sudheer Shanka0719c6a2018-04-24 11:12:11 -070013166 pw.print(KEY_BATTERY_LEVEL_COLLECTION_DELAY_MS); pw.print("=");
13167 pw.println(BATTERY_LEVEL_COLLECTION_DELAY_MS);
Hui Yu0ed84f12018-06-20 19:07:56 -070013168 pw.print(KEY_MAX_HISTORY_FILES); pw.print("=");
13169 pw.println(MAX_HISTORY_FILES);
13170 pw.print(KEY_MAX_HISTORY_BUFFER_KB); pw.print("=");
13171 pw.println(MAX_HISTORY_BUFFER/1024);
Zhi An Ng11b63622018-12-27 16:43:34 +080013172 pw.print(KEY_BATTERY_CHARGED_DELAY_MS); pw.print("=");
13173 pw.println(BATTERY_CHARGED_DELAY_MS);
Sudheer Shankae56013a2018-04-23 11:22:15 -070013174 }
13175 }
13176
13177 public long getExternalStatsCollectionRateLimitMs() {
13178 synchronized (this) {
13179 return mConstants.EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013180 }
13181 }
13182
Andreas Gampe3f24e692018-02-05 13:24:28 -080013183 @GuardedBy("this")
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013184 public void dumpConstantsLocked(PrintWriter pw) {
13185 mConstants.dumpLocked(pw);
13186 }
13187
Mike Ma234d1822018-03-13 18:53:21 -070013188 @GuardedBy("this")
13189 public void dumpCpuStatsLocked(PrintWriter pw) {
13190 int size = mUidStats.size();
13191 pw.println("Per UID CPU user & system time in ms:");
13192 for (int i = 0; i < size; i++) {
13193 int u = mUidStats.keyAt(i);
13194 Uid uid = mUidStats.get(u);
13195 pw.print(" "); pw.print(u); pw.print(": ");
13196 pw.print(uid.getUserCpuTimeUs(STATS_SINCE_CHARGED) / 1000); pw.print(" ");
13197 pw.println(uid.getSystemCpuTimeUs(STATS_SINCE_CHARGED) / 1000);
13198 }
13199 pw.println("Per UID CPU active time in ms:");
13200 for (int i = 0; i < size; i++) {
13201 int u = mUidStats.keyAt(i);
13202 Uid uid = mUidStats.get(u);
13203 if (uid.getCpuActiveTime() > 0) {
13204 pw.print(" "); pw.print(u); pw.print(": "); pw.println(uid.getCpuActiveTime());
13205 }
13206 }
13207 pw.println("Per UID CPU cluster time in ms:");
13208 for (int i = 0; i < size; i++) {
13209 int u = mUidStats.keyAt(i);
13210 long[] times = mUidStats.get(u).getCpuClusterTimes();
13211 if (times != null) {
13212 pw.print(" "); pw.print(u); pw.print(": "); pw.println(Arrays.toString(times));
13213 }
13214 }
13215 pw.println("Per UID CPU frequency time in ms:");
13216 for (int i = 0; i < size; i++) {
13217 int u = mUidStats.keyAt(i);
13218 long[] times = mUidStats.get(u).getCpuFreqTimes(STATS_SINCE_CHARGED);
13219 if (times != null) {
13220 pw.print(" "); pw.print(u); pw.print(": "); pw.println(Arrays.toString(times));
13221 }
13222 }
13223 }
13224
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013225 final ReentrantLock mWriteLock = new ReentrantLock();
13226
13227 public void writeAsyncLocked() {
Hui Yu0ed84f12018-06-20 19:07:56 -070013228 writeStatsLocked(false);
13229 writeHistoryLocked(false);
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013230 }
13231
13232 public void writeSyncLocked() {
Hui Yu0ed84f12018-06-20 19:07:56 -070013233 writeStatsLocked(true);
13234 writeHistoryLocked(true);
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013235 }
13236
Hui Yu0ed84f12018-06-20 19:07:56 -070013237 void writeStatsLocked(boolean sync) {
13238 if (mStatsFile == null) {
13239 Slog.w(TAG,
13240 "writeStatsLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013241 return;
13242 }
13243
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013244 if (mShuttingDown) {
13245 return;
13246 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013247
Hui Yu0ed84f12018-06-20 19:07:56 -070013248 final Parcel p = Parcel.obtain();
13249 final long start = SystemClock.uptimeMillis();
13250 writeSummaryToParcel(p, false/*history is in separate file*/);
13251 if (DEBUG) {
13252 Slog.d(TAG, "writeSummaryToParcel duration ms:"
13253 + (SystemClock.uptimeMillis() - start) + " bytes:" + p.dataSize());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013254 }
Hui Yu0ed84f12018-06-20 19:07:56 -070013255 mLastWriteTime = mClocks.elapsedRealtime();
13256 writeParcelToFileLocked(p, mStatsFile, sync);
13257 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013258
Hui Yu0ed84f12018-06-20 19:07:56 -070013259 void writeHistoryLocked(boolean sync) {
13260 if (mBatteryStatsHistory.getActiveFile() == null) {
13261 Slog.w(TAG,
13262 "writeHistoryLocked: no history file associated with this instance");
13263 return;
13264 }
13265
13266 if (mShuttingDown) {
13267 return;
13268 }
13269
13270 Parcel p = Parcel.obtain();
13271 final long start = SystemClock.uptimeMillis();
13272 writeHistoryBuffer(p, true, true);
13273 if (DEBUG) {
13274 Slog.d(TAG, "writeHistoryBuffer duration ms:"
13275 + (SystemClock.uptimeMillis() - start) + " bytes:" + p.dataSize());
13276 }
13277 writeParcelToFileLocked(p, mBatteryStatsHistory.getActiveFile(), sync);
13278 }
13279
13280 void writeParcelToFileLocked(Parcel p, AtomicFile file, boolean sync) {
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013281 if (sync) {
Hui Yu0ed84f12018-06-20 19:07:56 -070013282 commitPendingDataToDisk(p, file);
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013283 } else {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013284 BackgroundThread.getHandler().post(new Runnable() {
13285 @Override public void run() {
Hui Yu0ed84f12018-06-20 19:07:56 -070013286 commitPendingDataToDisk(p, file);
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013287 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013288 });
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013289 }
13290 }
13291
Hui Yu0ed84f12018-06-20 19:07:56 -070013292 private void commitPendingDataToDisk(Parcel p, AtomicFile file) {
Amith Yamasanid2450862017-02-07 15:58:24 -080013293 mWriteLock.lock();
Hui Yu0ed84f12018-06-20 19:07:56 -070013294 FileOutputStream fos = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013295 try {
Dianne Hackborne17b4452018-01-10 13:15:40 -080013296 final long startTime = SystemClock.uptimeMillis();
Hui Yu0ed84f12018-06-20 19:07:56 -070013297 fos = file.startWrite();
13298 fos.write(p.marshall());
13299 fos.flush();
13300 file.finishWrite(fos);
13301 if (DEBUG) {
13302 Slog.d(TAG, "commitPendingDataToDisk file:" + file.getBaseFile().getPath()
13303 + " duration ms:" + (SystemClock.uptimeMillis() - startTime)
13304 + " bytes:" + p.dataSize());
13305 }
Dianne Hackborne17b4452018-01-10 13:15:40 -080013306 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
13307 "batterystats", SystemClock.uptimeMillis() - startTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013308 } catch (IOException e) {
Hui Yu0ed84f12018-06-20 19:07:56 -070013309 Slog.w(TAG, "Error writing battery statistics", e);
13310 file.failWrite(fos);
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013311 } finally {
Hui Yu0ed84f12018-06-20 19:07:56 -070013312 p.recycle();
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013313 mWriteLock.unlock();
Suchi Amalapurapu8550f252009-09-29 15:20:32 -070013314 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013315 }
13316
Mathew Inwoodaf972c82018-08-20 14:13:20 +010013317 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013318 public void readLocked() {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013319 if (mDailyFile != null) {
13320 readDailyStatsLocked();
13321 }
13322
Hui Yu0ed84f12018-06-20 19:07:56 -070013323 if (mStatsFile == null) {
13324 Slog.w(TAG, "readLocked: no file associated with this instance");
13325 return;
13326 }
13327
Hui Yu4303dc02019-06-05 11:44:40 -070013328 final AtomicFile activeHistoryFile = mBatteryStatsHistory.getActiveFile();
13329 if (activeHistoryFile == null) {
Hui Yu0ed84f12018-06-20 19:07:56 -070013330 Slog.w(TAG,
13331 "readLocked: no history file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013332 return;
13333 }
13334
13335 mUidStats.clear();
13336
Hui Yu0ed84f12018-06-20 19:07:56 -070013337 Parcel stats = Parcel.obtain();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013338 try {
Hui Yu0ed84f12018-06-20 19:07:56 -070013339 final long start = SystemClock.uptimeMillis();
Hui Yu4303dc02019-06-05 11:44:40 -070013340 if (mStatsFile.exists()) {
13341 byte[] raw = mStatsFile.readFully();
13342 stats.unmarshall(raw, 0, raw.length);
13343 stats.setDataPosition(0);
13344 readSummaryFromParcel(stats);
13345 if (DEBUG) {
13346 Slog.d(TAG, "readLocked stats file:" + mStatsFile.getBaseFile().getPath()
13347 + " bytes:" + raw.length + " takes ms:" + (SystemClock.uptimeMillis()
13348 - start));
13349 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013350 }
Hui Yu0ed84f12018-06-20 19:07:56 -070013351 } catch (Exception e) {
13352 Slog.e(TAG, "Error reading battery statistics", e);
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013353 resetAllStatsLocked();
Hui Yu0ed84f12018-06-20 19:07:56 -070013354 } finally {
13355 stats.recycle();
13356 }
13357
13358 Parcel history = Parcel.obtain();
13359 try {
13360 final long start = SystemClock.uptimeMillis();
Hui Yu4303dc02019-06-05 11:44:40 -070013361 if (activeHistoryFile.exists()) {
13362 byte[] raw = activeHistoryFile.readFully();
13363 if (raw.length > 0) {
13364 history.unmarshall(raw, 0, raw.length);
13365 history.setDataPosition(0);
13366 readHistoryBuffer(history, true);
13367 }
13368 if (DEBUG) {
13369 Slog.d(TAG, "readLocked history file::"
13370 + activeHistoryFile.getBaseFile().getPath()
13371 + " bytes:" + raw.length + " takes ms:" + (SystemClock.uptimeMillis()
13372 - start));
13373 }
Hui Yu0ed84f12018-06-20 19:07:56 -070013374 }
13375 } catch (Exception e) {
13376 Slog.e(TAG, "Error reading battery history", e);
13377 clearHistoryLocked();
13378 mBatteryStatsHistory.resetAllFiles();
13379 } finally {
13380 history.recycle();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013381 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013382
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013383 mEndPlatformVersion = Build.ID;
13384
Hui Yu0ed84f12018-06-20 19:07:56 -070013385 if (mHistoryBuffer.dataPosition() > 0
13386 || mBatteryStatsHistory.getFilesNumbers().size() > 1) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013387 mRecordingHistory = true;
Joe Onoratoabded112016-02-08 16:49:39 -080013388 final long elapsedRealtime = mClocks.elapsedRealtime();
13389 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013390 if (USE_OLD_HISTORY) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013391 addHistoryRecordLocked(elapsedRealtime, uptime, HistoryItem.CMD_START, mHistoryCur);
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013392 }
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000013393 addHistoryBufferLocked(elapsedRealtime, HistoryItem.CMD_START, mHistoryCur);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013394 startRecordingHistory(elapsedRealtime, uptime, false);
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013395 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013396
13397 recordDailyStatsIfNeededLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013398 }
13399
13400 public int describeContents() {
13401 return 0;
13402 }
13403
Hui Yu0ed84f12018-06-20 19:07:56 -070013404 void readHistoryBuffer(Parcel in, boolean andOldHistory) throws ParcelFormatException {
13405 final int version = in.readInt();
13406 if (version != VERSION) {
13407 Slog.w("BatteryStats", "readHistoryBuffer: version got " + version
13408 + ", expected " + VERSION + "; erasing old stats");
13409 return;
13410 }
13411
Dianne Hackbornae384452011-06-28 12:33:48 -070013412 final long historyBaseTime = in.readLong();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013413
13414 mHistoryBuffer.setDataSize(0);
13415 mHistoryBuffer.setDataPosition(0);
13416
13417 int bufSize = in.readInt();
13418 int curPos = in.dataPosition();
Hui Yu0ed84f12018-06-20 19:07:56 -070013419 if (bufSize >= (mConstants.MAX_HISTORY_BUFFER*100)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013420 throw new ParcelFormatException("File corrupt: history data buffer too large " +
13421 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013422 } else if ((bufSize&~3) != bufSize) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013423 throw new ParcelFormatException("File corrupt: history data buffer not aligned " +
13424 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013425 } else {
13426 if (DEBUG_HISTORY) Slog.i(TAG, "***************** READING NEW HISTORY: " + bufSize
13427 + " bytes at " + curPos);
13428 mHistoryBuffer.appendFrom(in, curPos, bufSize);
13429 in.setDataPosition(curPos + bufSize);
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013430 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013431
Dianne Hackbornae384452011-06-28 12:33:48 -070013432 if (andOldHistory) {
13433 readOldHistory(in);
13434 }
13435
13436 if (DEBUG_HISTORY) {
13437 StringBuilder sb = new StringBuilder(128);
13438 sb.append("****************** OLD mHistoryBaseTime: ");
13439 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13440 Slog.i(TAG, sb.toString());
13441 }
13442 mHistoryBaseTime = historyBaseTime;
13443 if (DEBUG_HISTORY) {
13444 StringBuilder sb = new StringBuilder(128);
13445 sb.append("****************** NEW mHistoryBaseTime: ");
13446 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13447 Slog.i(TAG, sb.toString());
13448 }
13449
13450 // We are just arbitrarily going to insert 1 minute from the sample of
13451 // the last run until samples in this run.
13452 if (mHistoryBaseTime > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -080013453 long oldnow = mClocks.elapsedRealtime();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013454 mHistoryBaseTime = mHistoryBaseTime - oldnow + 1;
Dianne Hackbornae384452011-06-28 12:33:48 -070013455 if (DEBUG_HISTORY) {
13456 StringBuilder sb = new StringBuilder(128);
13457 sb.append("****************** ADJUSTED mHistoryBaseTime: ");
13458 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13459 Slog.i(TAG, sb.toString());
13460 }
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -070013461 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013462 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013463
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013464 void readOldHistory(Parcel in) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013465 if (!USE_OLD_HISTORY) {
13466 return;
13467 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013468 mHistory = mHistoryEnd = mHistoryCache = null;
Hui Yucb996102019-06-28 18:24:38 -070013469 while (in.dataAvail() > 0) {
13470 HistoryItem rec = new HistoryItem(in);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013471 addHistoryRecordLocked(rec);
13472 }
13473 }
13474
Hui Yu0ed84f12018-06-20 19:07:56 -070013475 void writeHistoryBuffer(Parcel out, boolean inclData, boolean andOldHistory) {
Dianne Hackbornae384452011-06-28 12:33:48 -070013476 if (DEBUG_HISTORY) {
13477 StringBuilder sb = new StringBuilder(128);
13478 sb.append("****************** WRITING mHistoryBaseTime: ");
13479 TimeUtils.formatDuration(mHistoryBaseTime, sb);
Dianne Hackborn40c87252014-03-19 16:55:40 -070013480 sb.append(" mLastHistoryElapsedRealtime: ");
13481 TimeUtils.formatDuration(mLastHistoryElapsedRealtime, sb);
Dianne Hackbornae384452011-06-28 12:33:48 -070013482 Slog.i(TAG, sb.toString());
13483 }
Hui Yu0ed84f12018-06-20 19:07:56 -070013484 out.writeInt(VERSION);
Dianne Hackborn40c87252014-03-19 16:55:40 -070013485 out.writeLong(mHistoryBaseTime + mLastHistoryElapsedRealtime);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013486 if (!inclData) {
13487 out.writeInt(0);
13488 out.writeInt(0);
13489 return;
13490 }
Hui Yu0ed84f12018-06-20 19:07:56 -070013491
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013492 out.writeInt(mHistoryBuffer.dataSize());
13493 if (DEBUG_HISTORY) Slog.i(TAG, "***************** WRITING HISTORY: "
13494 + mHistoryBuffer.dataSize() + " bytes at " + out.dataPosition());
13495 out.appendFrom(mHistoryBuffer, 0, mHistoryBuffer.dataSize());
Dianne Hackbornae384452011-06-28 12:33:48 -070013496
13497 if (andOldHistory) {
13498 writeOldHistory(out);
13499 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013500 }
13501
13502 void writeOldHistory(Parcel out) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013503 if (!USE_OLD_HISTORY) {
13504 return;
13505 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013506 HistoryItem rec = mHistory;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013507 while (rec != null) {
13508 if (rec.time >= 0) rec.writeToParcel(out, 0);
13509 rec = rec.next;
13510 }
13511 out.writeLong(-1);
13512 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013513
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013514 public void readSummaryFromParcel(Parcel in) throws ParcelFormatException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013515 final int version = in.readInt();
13516 if (version != VERSION) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013517 Slog.w("BatteryStats", "readFromParcel: version got " + version
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013518 + ", expected " + VERSION + "; erasing old stats");
13519 return;
13520 }
13521
Hui Yu0ed84f12018-06-20 19:07:56 -070013522 boolean inclHistory = in.readBoolean();
13523 if (inclHistory) {
13524 readHistoryBuffer(in, true);
13525 mBatteryStatsHistory.readFromParcel(in);
13526 }
13527
13528 mHistoryTagPool.clear();
13529 mNextHistoryTagIdx = 0;
13530 mNumHistoryTagChars = 0;
13531
13532 int numTags = in.readInt();
13533 for (int i=0; i<numTags; i++) {
13534 int idx = in.readInt();
13535 String str = in.readString();
13536 if (str == null) {
13537 throw new ParcelFormatException("null history tag string");
13538 }
13539 int uid = in.readInt();
13540 HistoryTag tag = new HistoryTag();
13541 tag.string = str;
13542 tag.uid = uid;
13543 tag.poolIdx = idx;
13544 mHistoryTagPool.put(tag, idx);
13545 if (idx >= mNextHistoryTagIdx) {
13546 mNextHistoryTagIdx = idx+1;
13547 }
13548 mNumHistoryTagChars += tag.string.length() + 1;
13549 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013550
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013551 mStartCount = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013552 mUptime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013553 mRealtime = in.readLong();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080013554 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013555 mStartPlatformVersion = in.readString();
13556 mEndPlatformVersion = in.readString();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013557 mOnBatteryTimeBase.readSummaryFromParcel(in);
13558 mOnBatteryScreenOffTimeBase.readSummaryFromParcel(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013559 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013560 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070013561 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013562 mCurrentBatteryLevel = in.readInt();
Adam Lesinskif9b20a92016-06-17 17:30:01 -070013563 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070013564 mMinLearnedBatteryCapacity = in.readInt();
13565 mMaxLearnedBatteryCapacity = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013566 mLowDischargeAmountSinceCharge = in.readInt();
13567 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013568 mDischargeAmountScreenOnSinceCharge = in.readInt();
13569 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070013570 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013571 mDischargeStepTracker.readFromParcel(in);
13572 mChargeStepTracker.readFromParcel(in);
13573 mDailyDischargeStepTracker.readFromParcel(in);
13574 mDailyChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070013575 mDischargeCounter.readSummaryFromParcelLocked(in);
13576 mDischargeScreenOffCounter.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070013577 mDischargeScreenDozeCounter.readSummaryFromParcelLocked(in);
Mike Ma15313c92017-11-15 17:58:21 -080013578 mDischargeLightDozeCounter.readSummaryFromParcelLocked(in);
13579 mDischargeDeepDozeCounter.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013580 int NPKG = in.readInt();
13581 if (NPKG > 0) {
13582 mDailyPackageChanges = new ArrayList<>(NPKG);
13583 while (NPKG > 0) {
13584 NPKG--;
13585 PackageChange pc = new PackageChange();
13586 pc.mPackageName = in.readString();
13587 pc.mUpdate = in.readInt() != 0;
Dianne Hackborn3accca02013-09-20 09:32:11 -070013588 pc.mVersionCode = in.readLong();
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013589 mDailyPackageChanges.add(pc);
13590 }
13591 } else {
13592 mDailyPackageChanges = null;
13593 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013594 mDailyStartTime = in.readLong();
13595 mNextMinDailyDeadline = in.readLong();
13596 mNextMaxDailyDeadline = in.readLong();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013597
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013598 mStartCount++;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013599
Jeff Browne95c3cd2014-05-02 16:59:26 -070013600 mScreenState = Display.STATE_UNKNOWN;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013601 mScreenOnTimer.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070013602 mScreenDozeTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn617f8772009-03-31 15:04:46 -070013603 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
13604 mScreenBrightnessTimer[i].readSummaryFromParcelLocked(in);
13605 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070013606 mInteractive = false;
13607 mInteractiveTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013608 mPhoneOn = false;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070013609 mPowerSaveModeEnabledTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070013610 mLongestLightIdleTime = in.readLong();
13611 mLongestFullIdleTime = in.readLong();
13612 mDeviceIdleModeLightTimer.readSummaryFromParcelLocked(in);
13613 mDeviceIdleModeFullTimer.readSummaryFromParcelLocked(in);
13614 mDeviceLightIdlingTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013615 mDeviceIdlingTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013616 mPhoneOnTimer.readSummaryFromParcelLocked(in);
Wink Saville52840902011-02-18 12:40:47 -080013617 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn627bba72009-03-24 22:32:56 -070013618 mPhoneSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
13619 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070013620 mPhoneSignalScanningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013621 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
13622 mPhoneDataConnectionsTimer[i].readSummaryFromParcelLocked(in);
13623 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013624 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013625 mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
13626 mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013627 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013628 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborne13c4c02014-02-11 17:18:35 -080013629 mMobileRadioActiveTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080013630 mMobileRadioActivePerAppTimer.readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013631 mMobileRadioActiveAdjustedTime.readSummaryFromParcelLocked(in);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013632 mMobileRadioActiveUnknownTime.readSummaryFromParcelLocked(in);
13633 mMobileRadioActiveUnknownCount.readSummaryFromParcelLocked(in);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080013634 mWifiMulticastWakelockTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070013635 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
The Android Open Source Project10592532009-03-18 17:39:46 -070013636 mWifiOn = false;
13637 mWifiOnTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013638 mGlobalWifiRunning = false;
13639 mGlobalWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080013640 for (int i=0; i<NUM_WIFI_STATES; i++) {
13641 mWifiStateTimer[i].readSummaryFromParcelLocked(in);
13642 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070013643 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
13644 mWifiSupplStateTimer[i].readSummaryFromParcelLocked(in);
13645 }
13646 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
13647 mWifiSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
13648 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080013649 mWifiActiveTimer.readSummaryFromParcelLocked(in);
13650 mWifiActivity.readSummaryFromParcel(in);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080013651 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
13652 mGpsSignalQualityTimer[i].readSummaryFromParcelLocked(in);
13653 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080013654 mBluetoothActivity.readSummaryFromParcel(in);
13655 mModemActivity.readSummaryFromParcel(in);
13656 mHasWifiReporting = in.readInt() != 0;
13657 mHasBluetoothReporting = in.readInt() != 0;
13658 mHasModemReporting = in.readInt() != 0;
Adam Lesinski33dac552015-03-09 15:24:48 -070013659
Mike Ma99e57c32018-03-15 14:40:37 -070013660 mNumConnectivityChange = in.readInt();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013661 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -070013662 mFlashlightOnTimer.readSummaryFromParcelLocked(in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013663 mCameraOnNesting = 0;
13664 mCameraOnTimer.readSummaryFromParcelLocked(in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013665 mBluetoothScanNesting = 0;
13666 mBluetoothScanTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013667
Bookatz50df7112017-08-04 14:53:26 -070013668 int NRPMS = in.readInt();
13669 if (NRPMS > 10000) {
13670 throw new ParcelFormatException("File corrupt: too many rpm stats " + NRPMS);
13671 }
13672 for (int irpm = 0; irpm < NRPMS; irpm++) {
13673 if (in.readInt() != 0) {
13674 String rpmName = in.readString();
13675 getRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
13676 }
13677 }
13678 int NSORPMS = in.readInt();
13679 if (NSORPMS > 10000) {
13680 throw new ParcelFormatException("File corrupt: too many screen-off rpm stats " + NSORPMS);
13681 }
13682 for (int irpm = 0; irpm < NSORPMS; irpm++) {
13683 if (in.readInt() != 0) {
13684 String rpmName = in.readString();
13685 getScreenOffRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
13686 }
13687 }
13688
Evan Millarc64edde2009-04-18 12:26:32 -070013689 int NKW = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013690 if (NKW > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013691 throw new ParcelFormatException("File corrupt: too many kernel wake locks " + NKW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013692 }
Evan Millarc64edde2009-04-18 12:26:32 -070013693 for (int ikw = 0; ikw < NKW; ikw++) {
13694 if (in.readInt() != 0) {
13695 String kwltName = in.readString();
13696 getKernelWakelockTimerLocked(kwltName).readSummaryFromParcelLocked(in);
13697 }
13698 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070013699
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013700 int NWR = in.readInt();
13701 if (NWR > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013702 throw new ParcelFormatException("File corrupt: too many wakeup reasons " + NWR);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013703 }
13704 for (int iwr = 0; iwr < NWR; iwr++) {
13705 if (in.readInt() != 0) {
13706 String reasonName = in.readString();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070013707 getWakeupReasonTimerLocked(reasonName).readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013708 }
13709 }
13710
James Carr3a226052016-07-01 14:49:52 -070013711 int NMS = in.readInt();
13712 for (int ims = 0; ims < NMS; ims++) {
13713 if (in.readInt() != 0) {
13714 long kmstName = in.readLong();
13715 getKernelMemoryTimerLocked(kmstName).readSummaryFromParcelLocked(in);
13716 }
13717 }
13718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013719 final int NU = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013720 if (NU > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013721 throw new ParcelFormatException("File corrupt: too many uids " + NU);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013722 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013723 for (int iu = 0; iu < NU; iu++) {
13724 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080013725 Uid u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013726 mUidStats.put(uid, u);
13727
Bookatz867c0d72017-03-07 18:23:42 -080013728 u.mOnBatteryBackgroundTimeBase.readSummaryFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -070013729 u.mOnBatteryScreenOffBackgroundTimeBase.readSummaryFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -080013730
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013731 u.mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013732 if (in.readInt() != 0) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013733 u.mWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013734 }
The Android Open Source Project10592532009-03-18 17:39:46 -070013735 u.mFullWifiLockOut = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013736 if (in.readInt() != 0) {
13737 u.mFullWifiLockTimer.readSummaryFromParcelLocked(in);
13738 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070013739 u.mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013740 if (in.readInt() != 0) {
Nick Pelly6ccaa542012-06-15 15:22:47 -070013741 u.mWifiScanTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013742 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070013743 u.mWifiBatchedScanBinStarted = Uid.NO_BATCHED_SCAN_STARTED;
13744 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
13745 if (in.readInt() != 0) {
13746 u.makeWifiBatchedScanBin(i, null);
13747 u.mWifiBatchedScanTimer[i].readSummaryFromParcelLocked(in);
13748 }
13749 }
Ahmed ElArabawy6f1754e2017-11-28 15:50:32 -080013750 u.mWifiMulticastWakelockCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013751 if (in.readInt() != 0) {
13752 u.mWifiMulticastTimer.readSummaryFromParcelLocked(in);
13753 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013754 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013755 u.createAudioTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013756 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013757 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013758 u.createVideoTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13759 }
13760 if (in.readInt() != 0) {
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013761 u.createFlashlightTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13762 }
13763 if (in.readInt() != 0) {
13764 u.createCameraTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13765 }
13766 if (in.readInt() != 0) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013767 u.createForegroundActivityTimerLocked().readSummaryFromParcelLocked(in);
13768 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013769 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070013770 u.createForegroundServiceTimerLocked().readSummaryFromParcelLocked(in);
13771 }
13772 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -070013773 u.createAggregatedPartialWakelockTimerLocked().readSummaryFromParcelLocked(in);
13774 }
13775 if (in.readInt() != 0) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013776 u.createBluetoothScanTimerLocked().readSummaryFromParcelLocked(in);
13777 }
Bookatz956f36bf2017-04-28 09:48:17 -070013778 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -070013779 u.createBluetoothUnoptimizedScanTimerLocked().readSummaryFromParcelLocked(in);
13780 }
13781 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -070013782 u.createBluetoothScanResultCounterLocked().readSummaryFromParcelLocked(in);
13783 }
Bookatzb1f04f32017-05-19 13:57:32 -070013784 if (in.readInt() != 0) {
13785 u.createBluetoothScanResultBgCounterLocked().readSummaryFromParcelLocked(in);
13786 }
Dianne Hackborna8d10942015-11-19 17:55:19 -080013787 u.mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -070013788 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
13789 if (in.readInt() != 0) {
13790 u.makeProcessState(i, null);
13791 u.mProcessStateTimer[i].readSummaryFromParcelLocked(in);
13792 }
13793 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013794 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013795 u.createVibratorOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013796 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070013797
Dianne Hackborn617f8772009-03-31 15:04:46 -070013798 if (in.readInt() != 0) {
13799 if (u.mUserActivityCounters == null) {
13800 u.initUserActivityLocked();
13801 }
13802 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
13803 u.mUserActivityCounters[i].readSummaryFromParcelLocked(in);
13804 }
13805 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013806
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013807 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013808 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013809 u.initNetworkActivityLocked();
13810 }
13811 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013812 u.mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
13813 u.mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013814 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013815 u.mMobileRadioActiveTime.readSummaryFromParcelLocked(in);
13816 u.mMobileRadioActiveCount.readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013817 }
13818
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013819 u.mUserCpuTime.readSummaryFromParcelLocked(in);
13820 u.mSystemCpuTime.readSummaryFromParcelLocked(in);
13821
Adam Lesinski6832f392015-09-05 18:05:40 -070013822 if (in.readInt() != 0) {
13823 final int numClusters = in.readInt();
13824 if (mPowerProfile != null && mPowerProfile.getNumCpuClusters() != numClusters) {
13825 throw new ParcelFormatException("Incompatible cpu cluster arrangement");
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013826 }
Hui Yu8e88e952018-07-23 17:59:59 -070013827 detachIfNotNull(u.mCpuClusterSpeedTimesUs);
Sudheer Shankaaf857412017-07-21 00:14:24 -070013828 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -070013829 for (int cluster = 0; cluster < numClusters; cluster++) {
Adam Lesinski6832f392015-09-05 18:05:40 -070013830 if (in.readInt() != 0) {
Adam Lesinskia57a5402015-09-28 10:21:33 -070013831 final int NSB = in.readInt();
13832 if (mPowerProfile != null &&
13833 mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != NSB) {
13834 throw new ParcelFormatException("File corrupt: too many speed bins " +
13835 NSB);
13836 }
13837
Sudheer Shankaaf857412017-07-21 00:14:24 -070013838 u.mCpuClusterSpeedTimesUs[cluster] = new LongSamplingCounter[NSB];
Adam Lesinski6832f392015-09-05 18:05:40 -070013839 for (int speed = 0; speed < NSB; speed++) {
13840 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070013841 u.mCpuClusterSpeedTimesUs[cluster][speed] = new LongSamplingCounter(
Adam Lesinski6832f392015-09-05 18:05:40 -070013842 mOnBatteryTimeBase);
Sudheer Shankaaf857412017-07-21 00:14:24 -070013843 u.mCpuClusterSpeedTimesUs[cluster][speed].readSummaryFromParcelLocked(in);
Adam Lesinski6832f392015-09-05 18:05:40 -070013844 }
13845 }
Adam Lesinskia57a5402015-09-28 10:21:33 -070013846 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070013847 u.mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -070013848 }
13849 }
13850 } else {
Hui Yu8e88e952018-07-23 17:59:59 -070013851 detachIfNotNull(u.mCpuClusterSpeedTimesUs);
Sudheer Shankaaf857412017-07-21 00:14:24 -070013852 u.mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013853 }
13854
Hui Yu8e88e952018-07-23 17:59:59 -070013855 detachIfNotNull(u.mCpuFreqTimeMs);
Sudheer Shanka59f5c002017-05-15 10:57:15 -070013856 u.mCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
13857 in, mOnBatteryTimeBase);
Hui Yu8e88e952018-07-23 17:59:59 -070013858 detachIfNotNull(u.mScreenOffCpuFreqTimeMs);
Sudheer Shanka59f5c002017-05-15 10:57:15 -070013859 u.mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
13860 in, mOnBatteryScreenOffTimeBase);
Mike Ma3d422c32017-10-25 11:08:57 -070013861
13862 u.mCpuActiveTimeMs.readSummaryFromParcelLocked(in);
13863 u.mCpuClusterTimesMs.readSummaryFromParcelLocked(in);
13864
Sudheer Shankab2f83c12017-11-13 19:25:01 -080013865 int length = in.readInt();
13866 if (length == Uid.NUM_PROCESS_STATE) {
Hui Yu8e88e952018-07-23 17:59:59 -070013867 detachIfNotNull(u.mProcStateTimeMs);
Sudheer Shankab2f83c12017-11-13 19:25:01 -080013868 u.mProcStateTimeMs = new LongSamplingCounterArray[length];
13869 for (int procState = 0; procState < length; ++procState) {
13870 u.mProcStateTimeMs[procState]
13871 = LongSamplingCounterArray.readSummaryFromParcelLocked(
13872 in, mOnBatteryTimeBase);
13873 }
13874 } else {
Hui Yu8e88e952018-07-23 17:59:59 -070013875 detachIfNotNull(u.mProcStateTimeMs);
Sudheer Shankab2f83c12017-11-13 19:25:01 -080013876 u.mProcStateTimeMs = null;
13877 }
13878 length = in.readInt();
13879 if (length == Uid.NUM_PROCESS_STATE) {
Hui Yu8e88e952018-07-23 17:59:59 -070013880 detachIfNotNull(u.mProcStateScreenOffTimeMs);
Sudheer Shankab2f83c12017-11-13 19:25:01 -080013881 u.mProcStateScreenOffTimeMs = new LongSamplingCounterArray[length];
13882 for (int procState = 0; procState < length; ++procState) {
13883 u.mProcStateScreenOffTimeMs[procState]
13884 = LongSamplingCounterArray.readSummaryFromParcelLocked(
13885 in, mOnBatteryScreenOffTimeBase);
13886 }
13887 } else {
Hui Yu8e88e952018-07-23 17:59:59 -070013888 detachIfNotNull(u.mProcStateScreenOffTimeMs);
Sudheer Shankab2f83c12017-11-13 19:25:01 -080013889 u.mProcStateScreenOffTimeMs = null;
13890 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070013891
13892 if (in.readInt() != 0) {
Hui Yu8e88e952018-07-23 17:59:59 -070013893 detachIfNotNull(u.mMobileRadioApWakeupCount);
Adam Lesinski5f056f62016-07-14 16:56:08 -070013894 u.mMobileRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
13895 u.mMobileRadioApWakeupCount.readSummaryFromParcelLocked(in);
13896 } else {
Hui Yu8e88e952018-07-23 17:59:59 -070013897 detachIfNotNull(u.mMobileRadioApWakeupCount);
Adam Lesinski5f056f62016-07-14 16:56:08 -070013898 u.mMobileRadioApWakeupCount = null;
13899 }
13900
13901 if (in.readInt() != 0) {
Hui Yu8e88e952018-07-23 17:59:59 -070013902 detachIfNotNull(u.mWifiRadioApWakeupCount);
Adam Lesinski5f056f62016-07-14 16:56:08 -070013903 u.mWifiRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
13904 u.mWifiRadioApWakeupCount.readSummaryFromParcelLocked(in);
13905 } else {
Hui Yu8e88e952018-07-23 17:59:59 -070013906 detachIfNotNull(u.mWifiRadioApWakeupCount);
Adam Lesinski5f056f62016-07-14 16:56:08 -070013907 u.mWifiRadioApWakeupCount = null;
13908 }
13909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013910 int NW = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070013911 if (NW > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013912 throw new ParcelFormatException("File corrupt: too many wake locks " + NW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013913 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013914 for (int iw = 0; iw < NW; iw++) {
13915 String wlName = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070013916 u.readWakeSummaryFromParcelLocked(wlName, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013917 }
13918
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013919 int NS = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070013920 if (NS > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013921 throw new ParcelFormatException("File corrupt: too many syncs " + NS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013922 }
13923 for (int is = 0; is < NS; is++) {
13924 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070013925 u.readSyncSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013926 }
13927
13928 int NJ = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070013929 if (NJ > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013930 throw new ParcelFormatException("File corrupt: too many job timers " + NJ);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013931 }
13932 for (int ij = 0; ij < NJ; ij++) {
13933 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070013934 u.readJobSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013935 }
13936
Dianne Hackborn94326cb2017-06-28 16:17:20 -070013937 u.readJobCompletionsFromParcelLocked(in);
13938
Amith Yamasani977e11f2018-02-16 11:29:54 -080013939 u.mJobsDeferredEventCount.readSummaryFromParcelLocked(in);
13940 u.mJobsDeferredCount.readSummaryFromParcelLocked(in);
13941 u.mJobsFreshnessTimeMs.readSummaryFromParcelLocked(in);
Hui Yu8e88e952018-07-23 17:59:59 -070013942 detachIfNotNull(u.mJobsFreshnessBuckets);
Amith Yamasani977e11f2018-02-16 11:29:54 -080013943 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
13944 if (in.readInt() != 0) {
13945 u.mJobsFreshnessBuckets[i] = new Counter(u.mBsi.mOnBatteryTimeBase);
13946 u.mJobsFreshnessBuckets[i].readSummaryFromParcelLocked(in);
13947 }
13948 }
13949
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013950 int NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080013951 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013952 throw new ParcelFormatException("File corrupt: too many sensors " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013953 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013954 for (int is = 0; is < NP; is++) {
13955 int seNumber = in.readInt();
13956 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -080013957 u.getSensorTimerLocked(seNumber, true).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013958 }
13959 }
13960
13961 NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080013962 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013963 throw new ParcelFormatException("File corrupt: too many processes " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013964 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013965 for (int ip = 0; ip < NP; ip++) {
13966 String procName = in.readString();
13967 Uid.Proc p = u.getProcessStatsLocked(procName);
Mike Ma99e57c32018-03-15 14:40:37 -070013968 p.mUserTime = in.readLong();
13969 p.mSystemTime = in.readLong();
13970 p.mForegroundTime = in.readLong();
13971 p.mStarts = in.readInt();
13972 p.mNumCrashes = in.readInt();
13973 p.mNumAnrs = in.readInt();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013974 p.readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013975 }
13976
13977 NP = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013978 if (NP > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013979 throw new ParcelFormatException("File corrupt: too many packages " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013980 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013981 for (int ip = 0; ip < NP; ip++) {
13982 String pkgName = in.readString();
Hui Yu10571e02018-08-06 13:12:40 -070013983 detachIfNotNull(u.mPackageStats.get(pkgName));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013984 Uid.Pkg p = u.getPackageStatsLocked(pkgName);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070013985 final int NWA = in.readInt();
Hui Yu0ed84f12018-06-20 19:07:56 -070013986 if (NWA > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013987 throw new ParcelFormatException("File corrupt: too many wakeup alarms " + NWA);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070013988 }
13989 p.mWakeupAlarms.clear();
Mike Ma99e57c32018-03-15 14:40:37 -070013990 for (int iwa = 0; iwa < NWA; iwa++) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -070013991 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -070013992 Counter c = new Counter(mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070013993 c.readSummaryFromParcelLocked(in);
13994 p.mWakeupAlarms.put(tag, c);
13995 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013996 NS = in.readInt();
Hui Yu0ed84f12018-06-20 19:07:56 -070013997 if (NS > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013998 throw new ParcelFormatException("File corrupt: too many services " + NS);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080013999 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014000 for (int is = 0; is < NS; is++) {
14001 String servName = in.readString();
14002 Uid.Pkg.Serv s = u.getServiceStatsLocked(pkgName, servName);
Mike Ma99e57c32018-03-15 14:40:37 -070014003 s.mStartTime = in.readLong();
14004 s.mStarts = in.readInt();
14005 s.mLaunches = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014006 }
14007 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014008 }
14009 }
14010
14011 /**
14012 * Writes a summary of the statistics to a Parcel, in a format suitable to be written to
14013 * disk. This format does not allow a lossless round-trip.
14014 *
14015 * @param out the Parcel to be written to.
14016 */
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070014017 public void writeSummaryToParcel(Parcel out, boolean inclHistory) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080014018 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014019
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014020 // Pull the clock time. This may update the time and make a new history entry
14021 // if we had originally pulled a time before the RTC was set.
Hui Yu5104da02019-06-03 13:58:20 -070014022 getStartClockTime();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014023
Joe Onoratoabded112016-02-08 16:49:39 -080014024 final long NOW_SYS = mClocks.uptimeMillis() * 1000;
14025 final long NOWREAL_SYS = mClocks.elapsedRealtime() * 1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014026
14027 out.writeInt(VERSION);
14028
Hui Yu0ed84f12018-06-20 19:07:56 -070014029 out.writeBoolean(inclHistory);
14030 if (inclHistory) {
14031 writeHistoryBuffer(out, true, true);
14032 mBatteryStatsHistory.writeToParcel(out);
14033 }
14034
14035 out.writeInt(mHistoryTagPool.size());
14036 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
14037 HistoryTag tag = ent.getKey();
14038 out.writeInt(ent.getValue());
14039 out.writeString(tag.string);
14040 out.writeInt(tag.uid);
14041 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014042
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014043 out.writeInt(mStartCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014044 out.writeLong(computeUptime(NOW_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014045 out.writeLong(computeRealtime(NOWREAL_SYS, STATS_SINCE_CHARGED));
Hui Yu5104da02019-06-03 13:58:20 -070014046 out.writeLong(mStartClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014047 out.writeString(mStartPlatformVersion);
14048 out.writeString(mEndPlatformVersion);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014049 mOnBatteryTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
14050 mOnBatteryScreenOffTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014051 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014052 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070014053 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014054 out.writeInt(mCurrentBatteryLevel);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014055 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070014056 out.writeInt(mMinLearnedBatteryCapacity);
14057 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborne4a59512010-12-07 11:08:07 -080014058 out.writeInt(getLowDischargeAmountSinceCharge());
14059 out.writeInt(getHighDischargeAmountSinceCharge());
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014060 out.writeInt(getDischargeAmountScreenOnSinceCharge());
14061 out.writeInt(getDischargeAmountScreenOffSinceCharge());
Mike Mac2f518a2017-09-19 16:06:03 -070014062 out.writeInt(getDischargeAmountScreenDozeSinceCharge());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014063 mDischargeStepTracker.writeToParcel(out);
14064 mChargeStepTracker.writeToParcel(out);
14065 mDailyDischargeStepTracker.writeToParcel(out);
14066 mDailyChargeStepTracker.writeToParcel(out);
Adam Lesinski67c134f2016-06-10 15:15:08 -070014067 mDischargeCounter.writeSummaryFromParcelLocked(out);
14068 mDischargeScreenOffCounter.writeSummaryFromParcelLocked(out);
Mike Mac2f518a2017-09-19 16:06:03 -070014069 mDischargeScreenDozeCounter.writeSummaryFromParcelLocked(out);
Mike Ma15313c92017-11-15 17:58:21 -080014070 mDischargeLightDozeCounter.writeSummaryFromParcelLocked(out);
14071 mDischargeDeepDozeCounter.writeSummaryFromParcelLocked(out);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014072 if (mDailyPackageChanges != null) {
14073 final int NPKG = mDailyPackageChanges.size();
14074 out.writeInt(NPKG);
14075 for (int i=0; i<NPKG; i++) {
14076 PackageChange pc = mDailyPackageChanges.get(i);
14077 out.writeString(pc.mPackageName);
14078 out.writeInt(pc.mUpdate ? 1 : 0);
Dianne Hackborn3accca02013-09-20 09:32:11 -070014079 out.writeLong(pc.mVersionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014080 }
14081 } else {
14082 out.writeInt(0);
14083 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014084 out.writeLong(mDailyStartTime);
14085 out.writeLong(mNextMinDailyDeadline);
14086 out.writeLong(mNextMaxDailyDeadline);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014087
14088 mScreenOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Mike Mac2f518a2017-09-19 16:06:03 -070014089 mScreenDozeTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070014090 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014091 mScreenBrightnessTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070014092 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070014093 mInteractiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070014094 mPowerSaveModeEnabledTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014095 out.writeLong(mLongestLightIdleTime);
14096 out.writeLong(mLongestFullIdleTime);
14097 mDeviceIdleModeLightTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14098 mDeviceIdleModeFullTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14099 mDeviceLightIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014100 mDeviceIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014101 mPhoneOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Wink Saville52840902011-02-18 12:40:47 -080014102 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014103 mPhoneSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070014104 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014105 mPhoneSignalScanningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070014106 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014107 mPhoneDataConnectionsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070014108 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014109 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014110 mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
14111 mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014112 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014113 mMobileRadioActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14114 mMobileRadioActivePerAppTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014115 mMobileRadioActiveAdjustedTime.writeSummaryFromParcelLocked(out);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080014116 mMobileRadioActiveUnknownTime.writeSummaryFromParcelLocked(out);
14117 mMobileRadioActiveUnknownCount.writeSummaryFromParcelLocked(out);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014118 mWifiMulticastWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014119 mWifiOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14120 mGlobalWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080014121 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014122 mWifiStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080014123 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014124 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
14125 mWifiSupplStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14126 }
14127 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
14128 mWifiSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14129 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014130 mWifiActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14131 mWifiActivity.writeSummaryToParcel(out);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014132 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14133 mGpsSignalQualityTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14134 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014135 mBluetoothActivity.writeSummaryToParcel(out);
14136 mModemActivity.writeSummaryToParcel(out);
14137 out.writeInt(mHasWifiReporting ? 1 : 0);
14138 out.writeInt(mHasBluetoothReporting ? 1 : 0);
14139 out.writeInt(mHasModemReporting ? 1 : 0);
14140
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014141 out.writeInt(mNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070014142 mFlashlightOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014143 mCameraOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014144 mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014145
Bookatz50df7112017-08-04 14:53:26 -070014146 out.writeInt(mRpmStats.size());
14147 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
14148 Timer rpmt = ent.getValue();
14149 if (rpmt != null) {
14150 out.writeInt(1);
14151 out.writeString(ent.getKey());
14152 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14153 } else {
14154 out.writeInt(0);
14155 }
14156 }
14157 out.writeInt(mScreenOffRpmStats.size());
14158 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
14159 Timer rpmt = ent.getValue();
14160 if (rpmt != null) {
14161 out.writeInt(1);
14162 out.writeString(ent.getKey());
14163 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14164 } else {
14165 out.writeInt(0);
14166 }
14167 }
14168
Evan Millarc64edde2009-04-18 12:26:32 -070014169 out.writeInt(mKernelWakelockStats.size());
14170 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
14171 Timer kwlt = ent.getValue();
14172 if (kwlt != null) {
14173 out.writeInt(1);
14174 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014175 kwlt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14176 } else {
14177 out.writeInt(0);
14178 }
14179 }
14180
14181 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014182 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
14183 SamplingTimer timer = ent.getValue();
14184 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014185 out.writeInt(1);
14186 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014187 timer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Evan Millarc64edde2009-04-18 12:26:32 -070014188 } else {
14189 out.writeInt(0);
14190 }
14191 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014192
James Carr3a226052016-07-01 14:49:52 -070014193 out.writeInt(mKernelMemoryStats.size());
14194 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
14195 Timer kmt = mKernelMemoryStats.valueAt(i);
14196 if (kmt != null) {
14197 out.writeInt(1);
14198 out.writeLong(mKernelMemoryStats.keyAt(i));
14199 kmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14200 } else {
14201 out.writeInt(0);
14202 }
14203 }
14204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014205 final int NU = mUidStats.size();
14206 out.writeInt(NU);
14207 for (int iu = 0; iu < NU; iu++) {
14208 out.writeInt(mUidStats.keyAt(iu));
14209 Uid u = mUidStats.valueAt(iu);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014210
Bookatz867c0d72017-03-07 18:23:42 -080014211 u.mOnBatteryBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatzc8c44962017-05-11 12:12:54 -070014212 u.mOnBatteryScreenOffBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatz867c0d72017-03-07 18:23:42 -080014213
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014214 if (u.mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014215 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014216 u.mWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014217 } else {
14218 out.writeInt(0);
14219 }
14220 if (u.mFullWifiLockTimer != null) {
14221 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014222 u.mFullWifiLockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014223 } else {
14224 out.writeInt(0);
14225 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070014226 if (u.mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014227 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014228 u.mWifiScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014229 } else {
14230 out.writeInt(0);
14231 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070014232 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
14233 if (u.mWifiBatchedScanTimer[i] != null) {
14234 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014235 u.mWifiBatchedScanTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Robert Greenwalta029ea12013-09-25 16:38:12 -070014236 } else {
14237 out.writeInt(0);
14238 }
14239 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014240 if (u.mWifiMulticastTimer != null) {
14241 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014242 u.mWifiMulticastTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014243 } else {
14244 out.writeInt(0);
14245 }
14246 if (u.mAudioTurnedOnTimer != null) {
14247 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014248 u.mAudioTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014249 } else {
14250 out.writeInt(0);
14251 }
14252 if (u.mVideoTurnedOnTimer != null) {
14253 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014254 u.mVideoTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014255 } else {
14256 out.writeInt(0);
14257 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014258 if (u.mFlashlightTurnedOnTimer != null) {
14259 out.writeInt(1);
14260 u.mFlashlightTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14261 } else {
14262 out.writeInt(0);
14263 }
14264 if (u.mCameraTurnedOnTimer != null) {
14265 out.writeInt(1);
14266 u.mCameraTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14267 } else {
14268 out.writeInt(0);
14269 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014270 if (u.mForegroundActivityTimer != null) {
14271 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014272 u.mForegroundActivityTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014273 } else {
14274 out.writeInt(0);
14275 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070014276 if (u.mForegroundServiceTimer != null) {
14277 out.writeInt(1);
14278 u.mForegroundServiceTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14279 } else {
14280 out.writeInt(0);
14281 }
Bookatzc8c44962017-05-11 12:12:54 -070014282 if (u.mAggregatedPartialWakelockTimer != null) {
14283 out.writeInt(1);
14284 u.mAggregatedPartialWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14285 } else {
14286 out.writeInt(0);
14287 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014288 if (u.mBluetoothScanTimer != null) {
14289 out.writeInt(1);
14290 u.mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14291 } else {
14292 out.writeInt(0);
14293 }
Bookatzb1f04f32017-05-19 13:57:32 -070014294 if (u.mBluetoothUnoptimizedScanTimer != null) {
14295 out.writeInt(1);
14296 u.mBluetoothUnoptimizedScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14297 } else {
14298 out.writeInt(0);
14299 }
Bookatz956f36bf2017-04-28 09:48:17 -070014300 if (u.mBluetoothScanResultCounter != null) {
14301 out.writeInt(1);
14302 u.mBluetoothScanResultCounter.writeSummaryFromParcelLocked(out);
14303 } else {
14304 out.writeInt(0);
14305 }
Bookatzb1f04f32017-05-19 13:57:32 -070014306 if (u.mBluetoothScanResultBgCounter != null) {
14307 out.writeInt(1);
14308 u.mBluetoothScanResultBgCounter.writeSummaryFromParcelLocked(out);
14309 } else {
14310 out.writeInt(0);
14311 }
Dianne Hackborn61659e52014-07-09 16:13:01 -070014312 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
14313 if (u.mProcessStateTimer[i] != null) {
14314 out.writeInt(1);
14315 u.mProcessStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14316 } else {
14317 out.writeInt(0);
14318 }
14319 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014320 if (u.mVibratorOnTimer != null) {
14321 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014322 u.mVibratorOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014323 } else {
14324 out.writeInt(0);
14325 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014326
Dianne Hackborn617f8772009-03-31 15:04:46 -070014327 if (u.mUserActivityCounters == null) {
14328 out.writeInt(0);
14329 } else {
14330 out.writeInt(1);
14331 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
14332 u.mUserActivityCounters[i].writeSummaryFromParcelLocked(out);
14333 }
14334 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014335
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014336 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014337 out.writeInt(0);
14338 } else {
14339 out.writeInt(1);
14340 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014341 u.mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
14342 u.mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014343 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080014344 u.mMobileRadioActiveTime.writeSummaryFromParcelLocked(out);
14345 u.mMobileRadioActiveCount.writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014346 }
14347
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014348 u.mUserCpuTime.writeSummaryFromParcelLocked(out);
14349 u.mSystemCpuTime.writeSummaryFromParcelLocked(out);
14350
Sudheer Shankaaf857412017-07-21 00:14:24 -070014351 if (u.mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -070014352 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -070014353 out.writeInt(u.mCpuClusterSpeedTimesUs.length);
14354 for (LongSamplingCounter[] cpuSpeeds : u.mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -070014355 if (cpuSpeeds != null) {
14356 out.writeInt(1);
14357 out.writeInt(cpuSpeeds.length);
14358 for (LongSamplingCounter c : cpuSpeeds) {
14359 if (c != null) {
14360 out.writeInt(1);
14361 c.writeSummaryFromParcelLocked(out);
14362 } else {
14363 out.writeInt(0);
14364 }
14365 }
14366 } else {
14367 out.writeInt(0);
14368 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014369 }
Adam Lesinski6832f392015-09-05 18:05:40 -070014370 } else {
14371 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014372 }
14373
Sudheer Shanka59f5c002017-05-15 10:57:15 -070014374 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mCpuFreqTimeMs);
14375 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mScreenOffCpuFreqTimeMs);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070014376
Mike Ma3d422c32017-10-25 11:08:57 -070014377 u.mCpuActiveTimeMs.writeSummaryFromParcelLocked(out);
14378 u.mCpuClusterTimesMs.writeSummaryToParcelLocked(out);
14379
Sudheer Shankab2f83c12017-11-13 19:25:01 -080014380 if (u.mProcStateTimeMs != null) {
14381 out.writeInt(u.mProcStateTimeMs.length);
14382 for (LongSamplingCounterArray counters : u.mProcStateTimeMs) {
14383 LongSamplingCounterArray.writeSummaryToParcelLocked(out, counters);
14384 }
14385 } else {
14386 out.writeInt(0);
14387 }
14388 if (u.mProcStateScreenOffTimeMs != null) {
14389 out.writeInt(u.mProcStateScreenOffTimeMs.length);
14390 for (LongSamplingCounterArray counters : u.mProcStateScreenOffTimeMs) {
14391 LongSamplingCounterArray.writeSummaryToParcelLocked(out, counters);
14392 }
14393 } else {
14394 out.writeInt(0);
14395 }
14396
Adam Lesinski5f056f62016-07-14 16:56:08 -070014397 if (u.mMobileRadioApWakeupCount != null) {
14398 out.writeInt(1);
14399 u.mMobileRadioApWakeupCount.writeSummaryFromParcelLocked(out);
14400 } else {
14401 out.writeInt(0);
14402 }
14403
14404 if (u.mWifiRadioApWakeupCount != null) {
14405 out.writeInt(1);
14406 u.mWifiRadioApWakeupCount.writeSummaryFromParcelLocked(out);
14407 } else {
14408 out.writeInt(0);
14409 }
14410
Dianne Hackbornd953c532014-08-16 18:17:38 -070014411 final ArrayMap<String, Uid.Wakelock> wakeStats = u.mWakelockStats.getMap();
14412 int NW = wakeStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014413 out.writeInt(NW);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014414 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014415 out.writeString(wakeStats.keyAt(iw));
14416 Uid.Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014417 if (wl.mTimerFull != null) {
14418 out.writeInt(1);
14419 wl.mTimerFull.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14420 } else {
14421 out.writeInt(0);
14422 }
14423 if (wl.mTimerPartial != null) {
14424 out.writeInt(1);
14425 wl.mTimerPartial.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14426 } else {
14427 out.writeInt(0);
14428 }
14429 if (wl.mTimerWindow != null) {
14430 out.writeInt(1);
14431 wl.mTimerWindow.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14432 } else {
14433 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014434 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070014435 if (wl.mTimerDraw != null) {
Adam Lesinski9425fe22015-06-19 12:02:13 -070014436 out.writeInt(1);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070014437 wl.mTimerDraw.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9425fe22015-06-19 12:02:13 -070014438 } else {
14439 out.writeInt(0);
14440 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014441 }
14442
Bookatz2bffb5b2017-04-13 11:59:33 -070014443 final ArrayMap<String, DualTimer> syncStats = u.mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014444 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014445 out.writeInt(NS);
14446 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014447 out.writeString(syncStats.keyAt(is));
14448 syncStats.valueAt(is).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014449 }
14450
Bookatzaa4594a2017-03-24 12:39:56 -070014451 final ArrayMap<String, DualTimer> jobStats = u.mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014452 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014453 out.writeInt(NJ);
14454 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014455 out.writeString(jobStats.keyAt(ij));
14456 jobStats.valueAt(ij).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014457 }
14458
Dianne Hackborn94326cb2017-06-28 16:17:20 -070014459 u.writeJobCompletionsToParcelLocked(out);
14460
Amith Yamasani977e11f2018-02-16 11:29:54 -080014461 u.mJobsDeferredEventCount.writeSummaryFromParcelLocked(out);
14462 u.mJobsDeferredCount.writeSummaryFromParcelLocked(out);
14463 u.mJobsFreshnessTimeMs.writeSummaryFromParcelLocked(out);
14464 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
14465 if (u.mJobsFreshnessBuckets[i] != null) {
Adam Lesinski14082082018-02-23 12:35:55 -080014466 out.writeInt(1);
Amith Yamasani977e11f2018-02-16 11:29:54 -080014467 u.mJobsFreshnessBuckets[i].writeSummaryFromParcelLocked(out);
14468 } else {
14469 out.writeInt(0);
14470 }
14471 }
14472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014473 int NSE = u.mSensorStats.size();
14474 out.writeInt(NSE);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014475 for (int ise=0; ise<NSE; ise++) {
14476 out.writeInt(u.mSensorStats.keyAt(ise));
14477 Uid.Sensor se = u.mSensorStats.valueAt(ise);
14478 if (se.mTimer != null) {
14479 out.writeInt(1);
14480 se.mTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14481 } else {
14482 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014483 }
14484 }
14485
14486 int NP = u.mProcessStats.size();
14487 out.writeInt(NP);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014488 for (int ip=0; ip<NP; ip++) {
14489 out.writeString(u.mProcessStats.keyAt(ip));
14490 Uid.Proc ps = u.mProcessStats.valueAt(ip);
14491 out.writeLong(ps.mUserTime);
14492 out.writeLong(ps.mSystemTime);
14493 out.writeLong(ps.mForegroundTime);
14494 out.writeInt(ps.mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014495 out.writeInt(ps.mNumCrashes);
14496 out.writeInt(ps.mNumAnrs);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014497 ps.writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014498 }
14499
14500 NP = u.mPackageStats.size();
14501 out.writeInt(NP);
14502 if (NP > 0) {
14503 for (Map.Entry<String, BatteryStatsImpl.Uid.Pkg> ent
14504 : u.mPackageStats.entrySet()) {
14505 out.writeString(ent.getKey());
14506 Uid.Pkg ps = ent.getValue();
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014507 final int NWA = ps.mWakeupAlarms.size();
14508 out.writeInt(NWA);
14509 for (int iwa=0; iwa<NWA; iwa++) {
14510 out.writeString(ps.mWakeupAlarms.keyAt(iwa));
14511 ps.mWakeupAlarms.valueAt(iwa).writeSummaryFromParcelLocked(out);
14512 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014513 NS = ps.mServiceStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014514 out.writeInt(NS);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014515 for (int is=0; is<NS; is++) {
14516 out.writeString(ps.mServiceStats.keyAt(is));
14517 BatteryStatsImpl.Uid.Pkg.Serv ss = ps.mServiceStats.valueAt(is);
14518 long time = ss.getStartTimeToNowLocked(
14519 mOnBatteryTimeBase.getUptime(NOW_SYS));
14520 out.writeLong(time);
14521 out.writeInt(ss.mStarts);
14522 out.writeInt(ss.mLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014523 }
14524 }
14525 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014526 }
14527 }
14528
14529 public void readFromParcel(Parcel in) {
14530 readFromParcelLocked(in);
14531 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014533 void readFromParcelLocked(Parcel in) {
14534 int magic = in.readInt();
14535 if (magic != MAGIC) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014536 throw new ParcelFormatException("Bad magic number: #" + Integer.toHexString(magic));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014537 }
14538
Hui Yu0ed84f12018-06-20 19:07:56 -070014539 readHistoryBuffer(in, false);
14540 mBatteryStatsHistory.readFromParcel(in);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014542 mStartCount = in.readInt();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080014543 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014544 mStartPlatformVersion = in.readString();
14545 mEndPlatformVersion = in.readString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014546 mUptime = in.readLong();
14547 mUptimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014548 mRealtime = in.readLong();
14549 mRealtimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014550 mOnBattery = in.readInt() != 0;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014551 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070014552 mMinLearnedBatteryCapacity = in.readInt();
14553 mMaxLearnedBatteryCapacity = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014554 mOnBatteryInternal = false; // we are no longer really running.
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014555 mOnBatteryTimeBase.readFromParcel(in);
14556 mOnBatteryScreenOffTimeBase.readFromParcel(in);
14557
Jeff Browne95c3cd2014-05-02 16:59:26 -070014558 mScreenState = Display.STATE_UNKNOWN;
Joe Onoratoabded112016-02-08 16:49:39 -080014559 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070014560 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014561 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014562 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
14563 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014564 }
Dianne Hackborn29325132014-05-21 15:01:03 -070014565 mInteractive = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014566 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014567 mPhoneOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014568 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
14569 mOnBatteryTimeBase, in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014570 mLongestLightIdleTime = in.readLong();
14571 mLongestFullIdleTime = in.readLong();
Joe Onoratoabded112016-02-08 16:49:39 -080014572 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -14, null,
14573 mOnBatteryTimeBase, in);
14574 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -11, null,
14575 mOnBatteryTimeBase, in);
14576 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null,
14577 mOnBatteryTimeBase, in);
14578 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase, in);
14579 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014580 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014581 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014582 null, mOnBatteryTimeBase, in);
14583 }
Joe Onoratoabded112016-02-08 16:49:39 -080014584 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
14585 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014586 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014587 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014588 null, mOnBatteryTimeBase, in);
14589 }
14590 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
14591 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
14592 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
14593 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014594 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Joe Onoratoabded112016-02-08 16:49:39 -080014595 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null,
14596 mOnBatteryTimeBase, in);
Kweku Adams87b19ec2017-10-09 12:40:03 -070014597 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
Joe Onoratoabded112016-02-08 16:49:39 -080014598 mOnBatteryTimeBase, in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014599 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014600 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
14601 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase, in);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014602 mWifiMulticastWakelockTimer = new StopwatchTimer(mClocks, null, -4, null,
14603 mOnBatteryTimeBase, in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070014604 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014605 mWifiOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014606 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014607 mGlobalWifiRunning = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014608 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null,
14609 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014610 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014611 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014612 null, mOnBatteryTimeBase, in);
14613 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014614 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014615 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070014616 null, mOnBatteryTimeBase, in);
14617 }
14618 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014619 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070014620 null, mOnBatteryTimeBase, in);
14621 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014622 mWifiActiveTimer = new StopwatchTimer(mClocks, null, -900, null,
14623 mOnBatteryTimeBase, in);
14624 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14625 NUM_WIFI_TX_LEVELS, in);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014626 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14627 mGpsSignalQualityTimer[i] = new StopwatchTimer(mClocks, null, -1000-i,
14628 null, mOnBatteryTimeBase, in);
14629 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014630 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14631 NUM_BT_TX_LEVELS, in);
14632 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14633 ModemActivityInfo.TX_POWER_LEVELS, in);
14634 mHasWifiReporting = in.readInt() != 0;
14635 mHasBluetoothReporting = in.readInt() != 0;
14636 mHasModemReporting = in.readInt() != 0;
14637
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014638 mNumConnectivityChange = in.readInt();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014639 mAudioOnNesting = 0;
Mike Ma99e57c32018-03-15 14:40:37 -070014640 // TODO: It's likely a mistake that mAudioOnTimer/mVideoOnTimer don't write/read to parcel!
Joe Onoratoabded112016-02-08 16:49:39 -080014641 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014642 mVideoOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014643 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014644 mFlashlightOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014645 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014646 mCameraOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014647 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014648 mBluetoothScanNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014649 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014650 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014651 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070014652 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014653 mCurrentBatteryLevel = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014654 mLowDischargeAmountSinceCharge = in.readInt();
14655 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014656 mDischargeAmountScreenOn = in.readInt();
14657 mDischargeAmountScreenOnSinceCharge = in.readInt();
14658 mDischargeAmountScreenOff = in.readInt();
14659 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070014660 mDischargeAmountScreenDoze = in.readInt();
14661 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014662 mDischargeStepTracker.readFromParcel(in);
14663 mChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070014664 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070014665 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase, in);
14666 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Ma15313c92017-11-15 17:58:21 -080014667 mDischargeLightDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
14668 mDischargeDeepDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014669 mLastWriteTime = in.readLong();
14670
Bookatz50df7112017-08-04 14:53:26 -070014671 mRpmStats.clear();
14672 int NRPMS = in.readInt();
14673 for (int irpm = 0; irpm < NRPMS; irpm++) {
14674 if (in.readInt() != 0) {
14675 String rpmName = in.readString();
14676 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
14677 mRpmStats.put(rpmName, rpmt);
14678 }
14679 }
14680 mScreenOffRpmStats.clear();
14681 int NSORPMS = in.readInt();
14682 for (int irpm = 0; irpm < NSORPMS; irpm++) {
14683 if (in.readInt() != 0) {
14684 String rpmName = in.readString();
14685 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
14686 mScreenOffRpmStats.put(rpmName, rpmt);
14687 }
14688 }
14689
Evan Millarc64edde2009-04-18 12:26:32 -070014690 mKernelWakelockStats.clear();
14691 int NKW = in.readInt();
14692 for (int ikw = 0; ikw < NKW; ikw++) {
14693 if (in.readInt() != 0) {
14694 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080014695 SamplingTimer kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -070014696 mKernelWakelockStats.put(wakelockName, kwlt);
14697 }
14698 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014699
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014700 mWakeupReasonStats.clear();
14701 int NWR = in.readInt();
14702 for (int iwr = 0; iwr < NWR; iwr++) {
14703 if (in.readInt() != 0) {
14704 String reasonName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080014705 SamplingTimer timer = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014706 mWakeupReasonStats.put(reasonName, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014707 }
14708 }
14709
James Carr3a226052016-07-01 14:49:52 -070014710 mKernelMemoryStats.clear();
14711 int nmt = in.readInt();
14712 for (int imt = 0; imt < nmt; imt++) {
14713 if (in.readInt() != 0) {
14714 Long bucket = in.readLong();
14715 SamplingTimer kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
14716 mKernelMemoryStats.put(bucket, kmt);
14717 }
14718 }
14719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014720 mPartialTimers.clear();
14721 mFullTimers.clear();
14722 mWindowTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014723 mWifiRunningTimers.clear();
14724 mFullWifiLockTimers.clear();
Nick Pelly6ccaa542012-06-15 15:22:47 -070014725 mWifiScanTimers.clear();
Robert Greenwalta029ea12013-09-25 16:38:12 -070014726 mWifiBatchedScanTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014727 mWifiMulticastTimers.clear();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014728 mAudioTurnedOnTimers.clear();
14729 mVideoTurnedOnTimers.clear();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014730 mFlashlightTurnedOnTimers.clear();
14731 mCameraTurnedOnTimers.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014732
14733 int numUids = in.readInt();
14734 mUidStats.clear();
14735 for (int i = 0; i < numUids; i++) {
14736 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080014737 Uid u = new Uid(this, uid);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014738 u.readFromParcelLocked(mOnBatteryTimeBase, mOnBatteryScreenOffTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014739 mUidStats.append(uid, u);
14740 }
14741 }
14742
14743 public void writeToParcel(Parcel out, int flags) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014744 writeToParcelLocked(out, true, flags);
14745 }
14746
14747 public void writeToParcelWithoutUids(Parcel out, int flags) {
14748 writeToParcelLocked(out, false, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014749 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014750
14751 @SuppressWarnings("unused")
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014752 void writeToParcelLocked(Parcel out, boolean inclUids, int flags) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014753 // Need to update with current kernel wake lock counts.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080014754 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014755
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014756 // Pull the clock time. This may update the time and make a new history entry
14757 // if we had originally pulled a time before the RTC was set.
Hui Yu5104da02019-06-03 13:58:20 -070014758 getStartClockTime();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014759
Joe Onoratoabded112016-02-08 16:49:39 -080014760 final long uSecUptime = mClocks.uptimeMillis() * 1000;
14761 final long uSecRealtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014762 final long batteryRealtime = mOnBatteryTimeBase.getRealtime(uSecRealtime);
14763 final long batteryScreenOffRealtime = mOnBatteryScreenOffTimeBase.getRealtime(uSecRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014765 out.writeInt(MAGIC);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014766
Hui Yu0ed84f12018-06-20 19:07:56 -070014767 writeHistoryBuffer(out, true, false);
14768 mBatteryStatsHistory.writeToParcel(out);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014770 out.writeInt(mStartCount);
Hui Yu5104da02019-06-03 13:58:20 -070014771 out.writeLong(mStartClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014772 out.writeString(mStartPlatformVersion);
14773 out.writeString(mEndPlatformVersion);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014774 out.writeLong(mUptime);
14775 out.writeLong(mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014776 out.writeLong(mRealtime);
14777 out.writeLong(mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014778 out.writeInt(mOnBattery ? 1 : 0);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014779 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070014780 out.writeInt(mMinLearnedBatteryCapacity);
14781 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014782 mOnBatteryTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
14783 mOnBatteryScreenOffTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
14784
14785 mScreenOnTimer.writeToParcel(out, uSecRealtime);
Mike Mac2f518a2017-09-19 16:06:03 -070014786 mScreenDozeTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014787 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
14788 mScreenBrightnessTimer[i].writeToParcel(out, uSecRealtime);
14789 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070014790 mInteractiveTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070014791 mPowerSaveModeEnabledTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014792 out.writeLong(mLongestLightIdleTime);
14793 out.writeLong(mLongestFullIdleTime);
14794 mDeviceIdleModeLightTimer.writeToParcel(out, uSecRealtime);
14795 mDeviceIdleModeFullTimer.writeToParcel(out, uSecRealtime);
14796 mDeviceLightIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014797 mDeviceIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014798 mPhoneOnTimer.writeToParcel(out, uSecRealtime);
14799 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
14800 mPhoneSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
14801 }
14802 mPhoneSignalScanningTimer.writeToParcel(out, uSecRealtime);
14803 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
14804 mPhoneDataConnectionsTimer[i].writeToParcel(out, uSecRealtime);
14805 }
14806 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
14807 mNetworkByteActivityCounters[i].writeToParcel(out);
14808 mNetworkPacketActivityCounters[i].writeToParcel(out);
14809 }
14810 mMobileRadioActiveTimer.writeToParcel(out, uSecRealtime);
14811 mMobileRadioActivePerAppTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014812 mMobileRadioActiveAdjustedTime.writeToParcel(out);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014813 mMobileRadioActiveUnknownTime.writeToParcel(out);
14814 mMobileRadioActiveUnknownCount.writeToParcel(out);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014815 mWifiMulticastWakelockTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014816 mWifiOnTimer.writeToParcel(out, uSecRealtime);
14817 mGlobalWifiRunningTimer.writeToParcel(out, uSecRealtime);
14818 for (int i=0; i<NUM_WIFI_STATES; i++) {
14819 mWifiStateTimer[i].writeToParcel(out, uSecRealtime);
14820 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014821 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
14822 mWifiSupplStateTimer[i].writeToParcel(out, uSecRealtime);
14823 }
14824 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
14825 mWifiSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
14826 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014827 mWifiActiveTimer.writeToParcel(out, uSecRealtime);
14828 mWifiActivity.writeToParcel(out, 0);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014829 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14830 mGpsSignalQualityTimer[i].writeToParcel(out, uSecRealtime);
14831 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014832 mBluetoothActivity.writeToParcel(out, 0);
14833 mModemActivity.writeToParcel(out, 0);
14834 out.writeInt(mHasWifiReporting ? 1 : 0);
14835 out.writeInt(mHasBluetoothReporting ? 1 : 0);
14836 out.writeInt(mHasModemReporting ? 1 : 0);
14837
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014838 out.writeInt(mNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070014839 mFlashlightOnTimer.writeToParcel(out, uSecRealtime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014840 mCameraOnTimer.writeToParcel(out, uSecRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014841 mBluetoothScanTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014842 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014843 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070014844 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014845 out.writeInt(mCurrentBatteryLevel);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014846 out.writeInt(mLowDischargeAmountSinceCharge);
14847 out.writeInt(mHighDischargeAmountSinceCharge);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014848 out.writeInt(mDischargeAmountScreenOn);
14849 out.writeInt(mDischargeAmountScreenOnSinceCharge);
14850 out.writeInt(mDischargeAmountScreenOff);
14851 out.writeInt(mDischargeAmountScreenOffSinceCharge);
Mike Mac2f518a2017-09-19 16:06:03 -070014852 out.writeInt(mDischargeAmountScreenDoze);
14853 out.writeInt(mDischargeAmountScreenDozeSinceCharge);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014854 mDischargeStepTracker.writeToParcel(out);
14855 mChargeStepTracker.writeToParcel(out);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070014856 mDischargeCounter.writeToParcel(out);
14857 mDischargeScreenOffCounter.writeToParcel(out);
Mike Mac2f518a2017-09-19 16:06:03 -070014858 mDischargeScreenDozeCounter.writeToParcel(out);
Mike Ma15313c92017-11-15 17:58:21 -080014859 mDischargeLightDozeCounter.writeToParcel(out);
14860 mDischargeDeepDozeCounter.writeToParcel(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014861 out.writeLong(mLastWriteTime);
14862
Bookatz50df7112017-08-04 14:53:26 -070014863 out.writeInt(mRpmStats.size());
14864 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
14865 SamplingTimer rpmt = ent.getValue();
14866 if (rpmt != null) {
14867 out.writeInt(1);
14868 out.writeString(ent.getKey());
14869 rpmt.writeToParcel(out, uSecRealtime);
14870 } else {
14871 out.writeInt(0);
14872 }
14873 }
14874 out.writeInt(mScreenOffRpmStats.size());
14875 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
14876 SamplingTimer rpmt = ent.getValue();
14877 if (rpmt != null) {
14878 out.writeInt(1);
14879 out.writeString(ent.getKey());
14880 rpmt.writeToParcel(out, uSecRealtime);
14881 } else {
14882 out.writeInt(0);
14883 }
14884 }
14885
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014886 if (inclUids) {
14887 out.writeInt(mKernelWakelockStats.size());
14888 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
14889 SamplingTimer kwlt = ent.getValue();
14890 if (kwlt != null) {
14891 out.writeInt(1);
14892 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014893 kwlt.writeToParcel(out, uSecRealtime);
14894 } else {
14895 out.writeInt(0);
14896 }
14897 }
14898 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014899 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
14900 SamplingTimer timer = ent.getValue();
14901 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014902 out.writeInt(1);
14903 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014904 timer.writeToParcel(out, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014905 } else {
14906 out.writeInt(0);
14907 }
Evan Millarc64edde2009-04-18 12:26:32 -070014908 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014909 } else {
Bookatzba78b2b2017-10-10 11:06:33 -070014910 out.writeInt(0);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014911 out.writeInt(0);
Evan Millarc64edde2009-04-18 12:26:32 -070014912 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070014913
James Carr3a226052016-07-01 14:49:52 -070014914 out.writeInt(mKernelMemoryStats.size());
14915 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
14916 SamplingTimer kmt = mKernelMemoryStats.valueAt(i);
14917 if (kmt != null) {
14918 out.writeInt(1);
14919 out.writeLong(mKernelMemoryStats.keyAt(i));
14920 kmt.writeToParcel(out, uSecRealtime);
14921 } else {
14922 out.writeInt(0);
14923 }
14924 }
14925
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014926 if (inclUids) {
14927 int size = mUidStats.size();
14928 out.writeInt(size);
14929 for (int i = 0; i < size; i++) {
14930 out.writeInt(mUidStats.keyAt(i));
14931 Uid uid = mUidStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014932
Bookatz867c0d72017-03-07 18:23:42 -080014933 uid.writeToParcelLocked(out, uSecUptime, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014934 }
14935 } else {
14936 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014937 }
14938 }
14939
Mathew Inwoodaf972c82018-08-20 14:13:20 +010014940 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014941 public static final Parcelable.Creator<BatteryStatsImpl> CREATOR =
14942 new Parcelable.Creator<BatteryStatsImpl>() {
14943 public BatteryStatsImpl createFromParcel(Parcel in) {
14944 return new BatteryStatsImpl(in);
14945 }
14946
14947 public BatteryStatsImpl[] newArray(int size) {
14948 return new BatteryStatsImpl[size];
14949 }
14950 };
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014951
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014952 public void prepareForDumpLocked() {
14953 // Need to retrieve current kernel wake lock stats before printing.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080014954 pullPendingStateUpdatesLocked();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014955
14956 // Pull the clock time. This may update the time and make a new history entry
14957 // if we had originally pulled a time before the RTC was set.
14958 getStartClockTime();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014959 }
14960
Dianne Hackbornc51cf032014-03-02 19:08:15 -080014961 public void dumpLocked(Context context, PrintWriter pw, int flags, int reqUid, long histStart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014962 if (DEBUG) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014963 pw.println("mOnBatteryTimeBase:");
14964 mOnBatteryTimeBase.dump(pw, " ");
14965 pw.println("mOnBatteryScreenOffTimeBase:");
14966 mOnBatteryScreenOffTimeBase.dump(pw, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014967 Printer pr = new PrintWriterPrinter(pw);
Mike Mac2f518a2017-09-19 16:06:03 -070014968 pr.println("*** Screen on timer:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014969 mScreenOnTimer.logState(pr, " ");
Mike Mac2f518a2017-09-19 16:06:03 -070014970 pr.println("*** Screen doze timer:");
14971 mScreenDozeTimer.logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070014972 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014973 pr.println("*** Screen brightness #" + i + ":");
14974 mScreenBrightnessTimer[i].logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070014975 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070014976 pr.println("*** Interactive timer:");
14977 mInteractiveTimer.logState(pr, " ");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070014978 pr.println("*** Power save mode timer:");
14979 mPowerSaveModeEnabledTimer.logState(pr, " ");
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014980 pr.println("*** Device idle mode light timer:");
14981 mDeviceIdleModeLightTimer.logState(pr, " ");
14982 pr.println("*** Device idle mode full timer:");
14983 mDeviceIdleModeFullTimer.logState(pr, " ");
14984 pr.println("*** Device light idling timer:");
14985 mDeviceLightIdlingTimer.logState(pr, " ");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014986 pr.println("*** Device idling timer:");
14987 mDeviceIdlingTimer.logState(pr, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014988 pr.println("*** Phone timer:");
14989 mPhoneOnTimer.logState(pr, " ");
Wink Saville52840902011-02-18 12:40:47 -080014990 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3251b902014-06-20 14:40:53 -070014991 pr.println("*** Phone signal strength #" + i + ":");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014992 mPhoneSignalStrengthsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070014993 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070014994 pr.println("*** Signal scanning :");
14995 mPhoneSignalScanningTimer.logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070014996 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014997 pr.println("*** Data connection type #" + i + ":");
14998 mPhoneDataConnectionsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070014999 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070015000 pr.println("*** mMobileRadioPowerState=" + mMobileRadioPowerState);
Dianne Hackborne13c4c02014-02-11 17:18:35 -080015001 pr.println("*** Mobile network active timer:");
15002 mMobileRadioActiveTimer.logState(pr, " ");
Dianne Hackborna1bd7922014-03-21 11:07:11 -070015003 pr.println("*** Mobile network active adjusted timer:");
15004 mMobileRadioActiveAdjustedTime.logState(pr, " ");
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080015005 pr.println("*** Wifi Multicast WakeLock Timer:");
15006 mWifiMulticastWakelockTimer.logState(pr, " ");
Dianne Hackborn0c820db2015-04-14 17:47:34 -070015007 pr.println("*** mWifiRadioPowerState=" + mWifiRadioPowerState);
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015008 pr.println("*** Wifi timer:");
15009 mWifiOnTimer.logState(pr, " ");
15010 pr.println("*** WifiRunning timer:");
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070015011 mGlobalWifiRunningTimer.logState(pr, " ");
Dianne Hackbornca1bf212014-02-14 14:18:36 -080015012 for (int i=0; i<NUM_WIFI_STATES; i++) {
15013 pr.println("*** Wifi state #" + i + ":");
15014 mWifiStateTimer[i].logState(pr, " ");
15015 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070015016 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
15017 pr.println("*** Wifi suppl state #" + i + ":");
15018 mWifiSupplStateTimer[i].logState(pr, " ");
15019 }
15020 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
15021 pr.println("*** Wifi signal strength #" + i + ":");
15022 mWifiSignalStrengthsTimer[i].logState(pr, " ");
15023 }
Siddharth Ray78ccaf52017-12-23 16:16:21 -080015024 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
15025 pr.println("*** GPS signal quality #" + i + ":");
15026 mGpsSignalQualityTimer[i].logState(pr, " ");
15027 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -070015028 pr.println("*** Flashlight timer:");
15029 mFlashlightOnTimer.logState(pr, " ");
Ruben Brunk6d2c3632015-05-26 17:32:16 -070015030 pr.println("*** Camera timer:");
15031 mCameraOnTimer.logState(pr, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015032 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -080015033 super.dumpLocked(context, pw, flags, reqUid, histStart);
Sudheer Shankac20379e2018-02-15 00:06:21 -080015034 pw.print("Total cpu time reads: ");
Mike Ma234d1822018-03-13 18:53:21 -070015035 pw.println(mNumSingleUidCpuTimeReads);
Sudheer Shankac20379e2018-02-15 00:06:21 -080015036 pw.print("Batched cpu time reads: ");
Mike Ma234d1822018-03-13 18:53:21 -070015037 pw.println(mNumBatchedSingleUidCpuTimeReads);
Sudheer Shankac20379e2018-02-15 00:06:21 -080015038 pw.print("Batching Duration (min): ");
15039 pw.println((mClocks.uptimeMillis() - mCpuTimeReadsTrackingStartTime) / (60 * 1000));
Mike Ma234d1822018-03-13 18:53:21 -070015040 pw.print("All UID cpu time reads since the later of device start or stats reset: ");
15041 pw.println(mNumAllUidCpuTimeReads);
15042 pw.print("UIDs removed since the later of device start or stats reset: ");
15043 pw.println(mNumUidsRemoved);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015044 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015045}