blob: 10c32a3b7a367bfd2176b9ed3c25b570268f8097 [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 Inwoodc185f082018-08-20 14:28:54 +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;
33import android.net.NetworkStats;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080034import android.net.Uri;
Adam Lesinski33dac552015-03-09 15:24:48 -070035import android.net.wifi.WifiActivityEnergyInfo;
Dianne Hackborn3251b902014-06-20 14:40:53 -070036import android.net.wifi.WifiManager;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070037import android.os.BatteryManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.os.BatteryStats;
Dianne Hackborncd0e3352014-08-07 17:08:09 -070039import android.os.Build;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070040import android.os.FileUtils;
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;
Amith Yamasanif37447b2009-10-08 18:28:01 -070063import android.telephony.ServiceState;
Wink Savillee9b06d72009-05-18 21:47:50 -070064import android.telephony.SignalStrength;
Dianne Hackborn627bba72009-03-24 22:32:56 -070065import android.telephony.TelephonyManager;
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -070066import android.text.TextUtils;
Dianne Hackborn61659e52014-07-09 16:13:01 -070067import android.util.ArrayMap;
Sudheer Shankab2f83c12017-11-13 19:25:01 -080068import android.util.IntArray;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080069import android.util.KeyValueListParser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.util.Log;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070071import android.util.LogWriter;
James Carr3a226052016-07-01 14:49:52 -070072import android.util.LongSparseArray;
73import android.util.LongSparseLongArray;
Dianne Hackbornd953c532014-08-16 18:17:38 -070074import android.util.MutableInt;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070075import android.util.Pools;
Dianne Hackborn1d442e02009-04-20 18:14:05 -070076import android.util.PrintWriterPrinter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.util.Printer;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070078import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079import android.util.SparseArray;
Dianne Hackborn099bc622014-01-22 13:39:16 -080080import android.util.SparseIntArray;
Adam Lesinskie08af192015-03-25 16:42:59 -070081import android.util.SparseLongArray;
Bookatzc1a050a2017-10-10 15:49:28 -070082import android.util.StatsLog;
Dianne Hackbornae384452011-06-28 12:33:48 -070083import android.util.TimeUtils;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080084import android.util.Xml;
Jeff Browne95c3cd2014-05-02 16:59:26 -070085import android.view.Display;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086
Adam Lesinski14ae39a2017-05-26 11:50:40 -070087import com.android.internal.annotations.GuardedBy;
Adam Lesinski98f0d462016-04-19 16:46:20 -070088import com.android.internal.annotations.VisibleForTesting;
Siddharth Ray78ccaf52017-12-23 16:16:21 -080089import com.android.internal.location.gnssmetrics.GnssMetrics;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070090import com.android.internal.net.NetworkStatsFactory;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080091import com.android.internal.util.ArrayUtils;
Dianne Hackborn8c841092013-06-24 13:46:13 -070092import com.android.internal.util.FastPrintWriter;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080093import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070094import com.android.internal.util.JournaledFile;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080095import com.android.internal.util.XmlUtils;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070096
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070097import libcore.util.EmptyArray;
Mike Ma234d1822018-03-13 18:53:21 -070098
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080099import org.xmlpull.v1.XmlPullParser;
100import org.xmlpull.v1.XmlPullParserException;
101import org.xmlpull.v1.XmlSerializer;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700102
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800103import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104import java.io.File;
105import java.io.FileInputStream;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800106import java.io.FileNotFoundException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import java.io.FileOutputStream;
108import java.io.IOException;
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700109import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100110import java.nio.charset.StandardCharsets;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111import java.util.ArrayList;
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700112import java.util.Arrays;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800113import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114import java.util.HashMap;
Evan Millarc64edde2009-04-18 12:26:32 -0700115import java.util.Iterator;
Mike Ma234d1822018-03-13 18:53:21 -0700116import java.util.LinkedList;
117import java.util.List;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import java.util.Map;
Mike Ma234d1822018-03-13 18:53:21 -0700119import java.util.Queue;
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700120import java.util.concurrent.Future;
Christopher Tate4cee7252010-03-19 14:50:40 -0700121import java.util.concurrent.atomic.AtomicInteger;
Dianne Hackbornce2ef762010-09-20 11:39:14 -0700122import java.util.concurrent.locks.ReentrantLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123
124/**
125 * All information we are collecting about things that can happen that impact
126 * battery life. All times are represented in microseconds except where indicated
127 * otherwise.
128 */
Joe Onoratoabded112016-02-08 16:49:39 -0800129public class BatteryStatsImpl extends BatteryStats {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130 private static final String TAG = "BatteryStatsImpl";
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800131 private static final boolean DEBUG = false;
Adam Lesinskia7c90c82015-06-18 14:52:24 -0700132 public static final boolean DEBUG_ENERGY = false;
Adam Lesinski50e47602015-12-04 17:04:54 -0800133 private static final boolean DEBUG_ENERGY_CPU = DEBUG_ENERGY;
James Carr3a226052016-07-01 14:49:52 -0700134 private static final boolean DEBUG_MEMORY = false;
Dianne Hackborn32907cf2010-06-10 17:50:20 -0700135 private static final boolean DEBUG_HISTORY = false;
Dianne Hackborne8c88e62011-08-17 19:09:09 -0700136 private static final boolean USE_OLD_HISTORY = false; // for debugging.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700137
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700138 // TODO: remove "tcp" from network methods, since we measure total stats.
139
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140 // In-memory Parcel magic number, used to detect attempts to unmarshall bad data
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700141 private static final int MAGIC = 0xBA757475; // 'BATSTATS'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142
143 // Current on-disk Parcel version
Mike Ma561a8d92018-03-20 18:24:05 -0700144 private static final int VERSION = 177 + (USE_OLD_HISTORY ? 1000 : 0);
Amith Yamasanie43530a2009-08-21 13:11:37 -0700145
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700146 // Maximum number of items we will record in the history.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100147 private static final int MAX_HISTORY_ITEMS;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700148
Dianne Hackbornf47d8f22010-10-08 10:46:55 -0700149 // No, really, THIS is the maximum number of items we will record in the history.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100150 private static final int MAX_MAX_HISTORY_ITEMS;
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
157 static final int MAX_HISTORY_BUFFER; // 256KB
158 static final int MAX_MAX_HISTORY_BUFFER; // 320KB
159
160 static {
161 if (ActivityManager.isLowRamDeviceStatic()) {
162 MAX_HISTORY_ITEMS = 800;
163 MAX_MAX_HISTORY_ITEMS = 1200;
164 MAX_WAKELOCKS_PER_UID = 40;
165 MAX_HISTORY_BUFFER = 96*1024; // 96KB
166 MAX_MAX_HISTORY_BUFFER = 128*1024; // 128KB
167 } else {
Makoto Onuki44d64602018-01-18 08:44:28 -0800168 MAX_HISTORY_ITEMS = 4000;
169 MAX_MAX_HISTORY_ITEMS = 6000;
170 MAX_WAKELOCKS_PER_UID = 200;
171 MAX_HISTORY_BUFFER = 512*1024; // 512KB
172 MAX_MAX_HISTORY_BUFFER = 640*1024; // 640KB
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100173 }
174 }
Dianne Hackbornc24ab862011-10-18 15:55:03 -0700175
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800176 // Number of transmit power states the Wifi controller can be in.
177 private static final int NUM_WIFI_TX_LEVELS = 1;
178
179 // Number of transmit power states the Bluetooth controller can be in.
180 private static final int NUM_BT_TX_LEVELS = 1;
181
Sudheer Shanka38383232017-07-25 09:55:03 -0700182 /**
183 * Holding a wakelock costs more than just using the cpu.
184 * Currently, we assign only half the cpu time to an app that is running but
185 * not holding a wakelock. The apps holding wakelocks get the rest of the blame.
186 * If no app is holding a wakelock, then the distribution is normal.
187 */
188 @VisibleForTesting
189 public static final int WAKE_LOCK_WEIGHT = 50;
190
Joe Onoratoabded112016-02-08 16:49:39 -0800191 protected Clocks mClocks;
192
Dianne Hackborn1afd1c92010-03-18 22:47:17 -0700193 private final JournaledFile mFile;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700194 public final AtomicFile mCheckinFile;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800195 public final AtomicFile mDailyFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196
Sudheer Shankac57729a2018-02-09 15:44:42 -0800197 static final int MSG_REPORT_CPU_UPDATE_NEEDED = 1;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700198 static final int MSG_REPORT_POWER_CHANGE = 2;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700199 static final int MSG_REPORT_CHARGING = 3;
Fyodor Kupolov8aa51242018-04-23 12:44:51 -0700200 static final int MSG_REPORT_RESET_STATS = 4;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700201 static final long DELAY_UPDATE_WAKELOCKS = 5*1000;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700202
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700203 private final KernelWakelockReader mKernelWakelockReader = new KernelWakelockReader();
204 private final KernelWakelockStats mTmpWakelockStats = new KernelWakelockStats();
205
Sudheer Shanka38383232017-07-25 09:55:03 -0700206 @VisibleForTesting
207 protected KernelUidCpuTimeReader mKernelUidCpuTimeReader = new KernelUidCpuTimeReader();
208 @VisibleForTesting
209 protected KernelCpuSpeedReader[] mKernelCpuSpeedReaders;
210 @VisibleForTesting
211 protected KernelUidCpuFreqTimeReader mKernelUidCpuFreqTimeReader =
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700212 new KernelUidCpuFreqTimeReader();
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800213 @VisibleForTesting
Mike Ma3d422c32017-10-25 11:08:57 -0700214 protected KernelUidCpuActiveTimeReader mKernelUidCpuActiveTimeReader =
215 new KernelUidCpuActiveTimeReader();
216 @VisibleForTesting
217 protected KernelUidCpuClusterTimeReader mKernelUidCpuClusterTimeReader =
218 new KernelUidCpuClusterTimeReader();
219 @VisibleForTesting
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800220 protected KernelSingleUidTimeReader mKernelSingleUidTimeReader;
Adam Lesinski06af1fa2015-05-05 17:35:35 -0700221
James Carr3a226052016-07-01 14:49:52 -0700222 private final KernelMemoryBandwidthStats mKernelMemoryBandwidthStats
223 = new KernelMemoryBandwidthStats();
224 private final LongSparseArray<SamplingTimer> mKernelMemoryStats = new LongSparseArray<>();
225 public LongSparseArray<SamplingTimer> getKernelMemoryStats() {
226 return mKernelMemoryStats;
227 }
228
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800229 @GuardedBy("this")
230 public boolean mPerProcStateCpuTimesAvailable = true;
231
232 /**
233 * Uids for which per-procstate cpu times need to be updated.
234 *
235 * Contains uid -> procState mappings.
236 */
237 @GuardedBy("this")
238 @VisibleForTesting
239 protected final SparseIntArray mPendingUids = new SparseIntArray();
240
Sudheer Shankac20379e2018-02-15 00:06:21 -0800241 @GuardedBy("this")
Mike Ma234d1822018-03-13 18:53:21 -0700242 private long mNumSingleUidCpuTimeReads;
Sudheer Shankac20379e2018-02-15 00:06:21 -0800243 @GuardedBy("this")
Mike Ma234d1822018-03-13 18:53:21 -0700244 private long mNumBatchedSingleUidCpuTimeReads;
Sudheer Shankac20379e2018-02-15 00:06:21 -0800245 @GuardedBy("this")
246 private long mCpuTimeReadsTrackingStartTime = SystemClock.uptimeMillis();
Mike Ma234d1822018-03-13 18:53:21 -0700247 @GuardedBy("this")
248 private int mNumUidsRemoved;
249 @GuardedBy("this")
250 private int mNumAllUidCpuTimeReads;
Sudheer Shankac20379e2018-02-15 00:06:21 -0800251
Bookatz0b8a0502017-09-13 11:51:52 -0700252 /** Container for Resource Power Manager stats. Updated by updateRpmStatsLocked. */
Bookatz50df7112017-08-04 14:53:26 -0700253 private final RpmStats mTmpRpmStats = new RpmStats();
Bookatz0b8a0502017-09-13 11:51:52 -0700254 /** The soonest the RPM stats can be updated after it was last updated. */
255 private static final long RPM_STATS_UPDATE_FREQ_MS = 1000;
256 /** Last time that RPM stats were updated by updateRpmStatsLocked. */
257 private long mLastRpmStatsUpdateTimeMs = -RPM_STATS_UPDATE_FREQ_MS;
Mike Ma234d1822018-03-13 18:53:21 -0700258 /**
259 * Use a queue to delay removing UIDs from {@link KernelUidCpuTimeReader},
260 * {@link KernelUidCpuActiveTimeReader}, {@link KernelUidCpuClusterTimeReader},
261 * {@link KernelUidCpuFreqTimeReader} and from the Kernel.
262 *
263 * Isolated and invalid UID info must be removed to conserve memory. However, STATSD and
264 * Batterystats both need to access UID cpu time. To resolve this race condition, only
265 * Batterystats shall remove UIDs, and a delay {@link Constants#UID_REMOVE_DELAY_MS} is
266 * implemented so that STATSD can capture those UID times before they are deleted.
267 */
268 @GuardedBy("this")
269 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
270 protected Queue<UidToRemove> mPendingRemovedUids = new LinkedList<>();
271
272 @VisibleForTesting
273 public final class UidToRemove {
274 int startUid;
275 int endUid;
276 long timeAddedInQueue;
277
278 /** Remove just one UID */
279 public UidToRemove(int uid, long timestamp) {
280 this(uid, uid, timestamp);
281 }
282
283 /** Remove a range of UIDs, startUid must be smaller than endUid. */
284 public UidToRemove(int startUid, int endUid, long timestamp) {
285 this.startUid = startUid;
286 this.endUid = endUid;
287 timeAddedInQueue = timestamp;
288 }
289
290 void remove() {
291 if (startUid == endUid) {
292 mKernelUidCpuTimeReader.removeUid(startUid);
293 mKernelUidCpuFreqTimeReader.removeUid(startUid);
294 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
295 mKernelUidCpuActiveTimeReader.removeUid(startUid);
296 mKernelUidCpuClusterTimeReader.removeUid(startUid);
297 }
298 if (mKernelSingleUidTimeReader != null) {
299 mKernelSingleUidTimeReader.removeUid(startUid);
300 }
301 mNumUidsRemoved++;
302 } else if (startUid < endUid) {
303 mKernelUidCpuFreqTimeReader.removeUidsInRange(startUid, endUid);
304 mKernelUidCpuTimeReader.removeUidsInRange(startUid, endUid);
305 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
306 mKernelUidCpuActiveTimeReader.removeUidsInRange(startUid, endUid);
307 mKernelUidCpuClusterTimeReader.removeUidsInRange(startUid, endUid);
308 }
309 if (mKernelSingleUidTimeReader != null) {
310 mKernelSingleUidTimeReader.removeUidsInRange(startUid, endUid);
311 }
312 // Treat as one. We don't know how many uids there are in between.
313 mNumUidsRemoved++;
314 } else {
315 Slog.w(TAG, "End UID " + endUid + " is smaller than start UID " + startUid);
316 }
317 }
318 }
Bookatz50df7112017-08-04 14:53:26 -0700319
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700320 public interface BatteryCallback {
321 public void batteryNeedsCpuUpdate();
322 public void batteryPowerChanged(boolean onBattery);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700323 public void batterySendBroadcast(Intent intent);
Fyodor Kupolov8aa51242018-04-23 12:44:51 -0700324 public void batteryStatsReset();
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700325 }
326
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700327 public interface PlatformIdleStateCallback {
Bookatz50df7112017-08-04 14:53:26 -0700328 public void fillLowPowerStats(RpmStats rpmStats);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700329 public String getPlatformLowPowerStats();
Ahmed ElArabawyd8b44112017-05-23 21:25:02 +0000330 public String getSubsystemLowPowerStats();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700331 }
332
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700333 public static abstract class UserInfoProvider {
334 private int[] userIds;
335 protected abstract @Nullable int[] getUserIds();
Sudheer Shanka38383232017-07-25 09:55:03 -0700336 @VisibleForTesting
337 public final void refreshUserIds() {
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700338 userIds = getUserIds();
339 }
Sudheer Shanka38383232017-07-25 09:55:03 -0700340 @VisibleForTesting
341 public boolean exists(int userId) {
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700342 return userIds != null ? ArrayUtils.contains(userIds, userId) : true;
343 }
344 }
345
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700346 private final PlatformIdleStateCallback mPlatformIdleStateCallback;
347
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700348 final class MyHandler extends Handler {
Jeff Brown6f357d32014-01-15 20:40:55 -0800349 public MyHandler(Looper looper) {
350 super(looper, null, true);
351 }
352
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700353 @Override
354 public void handleMessage(Message msg) {
355 BatteryCallback cb = mCallback;
356 switch (msg.what) {
Sudheer Shankac57729a2018-02-09 15:44:42 -0800357 case MSG_REPORT_CPU_UPDATE_NEEDED:
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700358 if (cb != null) {
359 cb.batteryNeedsCpuUpdate();
360 }
361 break;
362 case MSG_REPORT_POWER_CHANGE:
363 if (cb != null) {
364 cb.batteryPowerChanged(msg.arg1 != 0);
365 }
366 break;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700367 case MSG_REPORT_CHARGING:
368 if (cb != null) {
369 final String action;
370 synchronized (BatteryStatsImpl.this) {
371 action = mCharging ? BatteryManager.ACTION_CHARGING
372 : BatteryManager.ACTION_DISCHARGING;
373 }
374 Intent intent = new Intent(action);
375 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
376 cb.batterySendBroadcast(intent);
377 }
378 break;
Fyodor Kupolov8aa51242018-04-23 12:44:51 -0700379 case MSG_REPORT_RESET_STATS:
380 if (cb != null) {
381 cb.batteryStatsReset();
382 }
383 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700384 }
385 }
386
Sudheer Shankac57729a2018-02-09 15:44:42 -0800387 public void postBatteryNeedsCpuUpdateMsg() {
388 mHandler.sendEmptyMessage(MSG_REPORT_CPU_UPDATE_NEEDED);
389 }
390
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800391 /**
392 * Update per-freq cpu times for all the uids in {@link #mPendingUids}.
393 */
Sudheer Shankae544d162017-12-28 17:06:20 -0800394 public void updateProcStateCpuTimes(boolean onBattery, boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800395 final SparseIntArray uidStates;
396 synchronized (BatteryStatsImpl.this) {
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800397 if (!mConstants.TRACK_CPU_TIMES_BY_PROC_STATE) {
398 return;
399 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800400 if(!initKernelSingleUidTimeReaderLocked()) {
401 return;
402 }
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800403 // If the KernelSingleUidTimeReader has stale cpu times, then we shouldn't try to
404 // compute deltas since it might result in mis-attributing cpu times to wrong states.
405 if (mKernelSingleUidTimeReader.hasStaleData()) {
406 mPendingUids.clear();
407 return;
408 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800409
410 if (mPendingUids.size() == 0) {
411 return;
412 }
413 uidStates = mPendingUids.clone();
414 mPendingUids.clear();
415 }
416 for (int i = uidStates.size() - 1; i >= 0; --i) {
417 final int uid = uidStates.keyAt(i);
418 final int procState = uidStates.valueAt(i);
419 final int[] isolatedUids;
420 final Uid u;
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800421 synchronized (BatteryStatsImpl.this) {
422 // It's possible that uid no longer exists and any internal references have
423 // already been deleted, so using {@link #getAvailableUidStatsLocked} to avoid
424 // creating an UidStats object if it doesn't already exist.
425 u = getAvailableUidStatsLocked(uid);
426 if (u == null) {
427 continue;
428 }
429 if (u.mChildUids == null) {
430 isolatedUids = null;
431 } else {
432 isolatedUids = u.mChildUids.toArray();
433 for (int j = isolatedUids.length - 1; j >= 0; --j) {
434 isolatedUids[j] = u.mChildUids.get(j);
435 }
436 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800437 }
438 long[] cpuTimesMs = mKernelSingleUidTimeReader.readDeltaMs(uid);
439 if (isolatedUids != null) {
440 for (int j = isolatedUids.length - 1; j >= 0; --j) {
441 cpuTimesMs = addCpuTimes(cpuTimesMs,
442 mKernelSingleUidTimeReader.readDeltaMs(isolatedUids[j]));
443 }
444 }
445 if (onBattery && cpuTimesMs != null) {
446 synchronized (BatteryStatsImpl.this) {
Sudheer Shankae544d162017-12-28 17:06:20 -0800447 u.addProcStateTimesMs(procState, cpuTimesMs, onBattery);
448 u.addProcStateScreenOffTimesMs(procState, cpuTimesMs, onBatteryScreenOff);
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800449 }
450 }
451 }
452 }
453
Mike Ma234d1822018-03-13 18:53:21 -0700454 public void clearPendingRemovedUids() {
455 long cutOffTime = mClocks.elapsedRealtime() - mConstants.UID_REMOVE_DELAY_MS;
456 while (!mPendingRemovedUids.isEmpty()
457 && mPendingRemovedUids.peek().timeAddedInQueue < cutOffTime) {
458 mPendingRemovedUids.poll().remove();
459 }
460 }
461
Sudheer Shankae544d162017-12-28 17:06:20 -0800462 public void copyFromAllUidsCpuTimes() {
463 synchronized (BatteryStatsImpl.this) {
464 copyFromAllUidsCpuTimes(
465 mOnBatteryTimeBase.isRunning(), mOnBatteryScreenOffTimeBase.isRunning());
466 }
467 }
468
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800469 /**
470 * When the battery/screen state changes, we don't attribute the cpu times to any process
471 * but we still need to snapshots of all uids to get correct deltas later on. Since we
472 * already read this data for updating per-freq cpu times, we can use the same data for
473 * per-procstate cpu times.
474 */
Sudheer Shankae544d162017-12-28 17:06:20 -0800475 public void copyFromAllUidsCpuTimes(boolean onBattery, boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800476 synchronized (BatteryStatsImpl.this) {
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800477 if (!mConstants.TRACK_CPU_TIMES_BY_PROC_STATE) {
478 return;
479 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800480 if(!initKernelSingleUidTimeReaderLocked()) {
481 return;
482 }
483
484 final SparseArray<long[]> allUidCpuFreqTimesMs =
485 mKernelUidCpuFreqTimeReader.getAllUidCpuFreqTimeMs();
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800486 // If the KernelSingleUidTimeReader has stale cpu times, then we shouldn't try to
487 // compute deltas since it might result in mis-attributing cpu times to wrong states.
488 if (mKernelSingleUidTimeReader.hasStaleData()) {
489 mKernelSingleUidTimeReader.setAllUidsCpuTimesMs(allUidCpuFreqTimesMs);
490 mKernelSingleUidTimeReader.markDataAsStale(false);
491 mPendingUids.clear();
492 return;
493 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800494 for (int i = allUidCpuFreqTimesMs.size() - 1; i >= 0; --i) {
495 final int uid = allUidCpuFreqTimesMs.keyAt(i);
496 final Uid u = getAvailableUidStatsLocked(mapUid(uid));
497 if (u == null) {
498 continue;
499 }
500 final long[] cpuTimesMs = allUidCpuFreqTimesMs.valueAt(i);
501 if (cpuTimesMs == null) {
502 continue;
503 }
504 final long[] deltaTimesMs = mKernelSingleUidTimeReader.computeDelta(
505 uid, cpuTimesMs.clone());
Sudheer Shankae544d162017-12-28 17:06:20 -0800506 if (onBattery && deltaTimesMs != null) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800507 final int procState;
508 final int idx = mPendingUids.indexOfKey(uid);
509 if (idx >= 0) {
510 procState = mPendingUids.valueAt(idx);
511 mPendingUids.removeAt(idx);
512 } else {
513 procState = u.mProcessState;
514 }
515 if (procState >= 0 && procState < Uid.NUM_PROCESS_STATE) {
Sudheer Shankae544d162017-12-28 17:06:20 -0800516 u.addProcStateTimesMs(procState, deltaTimesMs, onBattery);
517 u.addProcStateScreenOffTimesMs(procState, deltaTimesMs, onBatteryScreenOff);
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800518 }
519 }
520 }
521 }
522 }
523
524 @VisibleForTesting
525 public long[] addCpuTimes(long[] timesA, long[] timesB) {
526 if (timesA != null && timesB != null) {
527 for (int i = timesA.length - 1; i >= 0; --i) {
528 timesA[i] += timesB[i];
529 }
530 return timesA;
531 }
532 return timesA == null ? (timesB == null ? null : timesB) : timesA;
533 }
534
535 @GuardedBy("this")
536 private boolean initKernelSingleUidTimeReaderLocked() {
537 if (mKernelSingleUidTimeReader == null) {
538 if (mPowerProfile == null) {
539 return false;
540 }
541 if (mCpuFreqs == null) {
542 mCpuFreqs = mKernelUidCpuFreqTimeReader.readFreqs(mPowerProfile);
543 }
544 if (mCpuFreqs != null) {
545 mKernelSingleUidTimeReader = new KernelSingleUidTimeReader(mCpuFreqs.length);
546 } else {
547 mPerProcStateCpuTimesAvailable = mKernelUidCpuFreqTimeReader.allUidTimesAvailable();
548 return false;
549 }
550 }
551 mPerProcStateCpuTimesAvailable = mKernelUidCpuFreqTimeReader.allUidTimesAvailable()
552 && mKernelSingleUidTimeReader.singleUidCpuTimesAvailable();
553 return true;
554 }
555
Joe Onoratoabded112016-02-08 16:49:39 -0800556 public interface Clocks {
557 public long elapsedRealtime();
558 public long uptimeMillis();
559 }
560
561 public static class SystemClocks implements Clocks {
562 public long elapsedRealtime() {
563 return SystemClock.elapsedRealtime();
564 }
565
566 public long uptimeMillis() {
567 return SystemClock.uptimeMillis();
568 }
569 }
570
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700571 public interface ExternalStatsSync {
Adam Lesinski14ae39a2017-05-26 11:50:40 -0700572 int UPDATE_CPU = 0x01;
573 int UPDATE_WIFI = 0x02;
574 int UPDATE_RADIO = 0x04;
575 int UPDATE_BT = 0x08;
Bookatz50df7112017-08-04 14:53:26 -0700576 int UPDATE_RPM = 0x10; // 16
577 int UPDATE_ALL = UPDATE_CPU | UPDATE_WIFI | UPDATE_RADIO | UPDATE_BT | UPDATE_RPM;
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800578
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700579 Future<?> scheduleSync(String reason, int flags);
580 Future<?> scheduleCpuSyncDueToRemovedUid(int uid);
Sudheer Shankac20379e2018-02-15 00:06:21 -0800581 Future<?> scheduleReadProcStateCpuTimes(boolean onBattery, boolean onBatteryScreenOff,
582 long delayMillis);
Sudheer Shankae544d162017-12-28 17:06:20 -0800583 Future<?> scheduleCopyFromAllUidsCpuTimes(boolean onBattery, boolean onBatteryScreenOff);
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800584 Future<?> scheduleCpuSyncDueToSettingChange();
Sudheer Shankac57729a2018-02-09 15:44:42 -0800585 Future<?> scheduleCpuSyncDueToScreenStateChange(boolean onBattery,
586 boolean onBatteryScreenOff);
587 Future<?> scheduleCpuSyncDueToWakelockChange(long delayMillis);
588 void cancelCpuSyncDueToWakelockChange();
Sudheer Shanka0719c6a2018-04-24 11:12:11 -0700589 Future<?> scheduleSyncDueToBatteryLevelChange(long delayMillis);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700590 }
591
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800592 public Handler mHandler;
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700593 private ExternalStatsSync mExternalSync = null;
Sudheer Shanka38383232017-07-25 09:55:03 -0700594 @VisibleForTesting
595 protected UserInfoProvider mUserInfoProvider = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700596
597 private BatteryCallback mCallback;
598
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800599 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -0800600 * Mapping isolated uids to the actual owning app uid.
601 */
602 final SparseIntArray mIsolatedUids = new SparseIntArray();
603
604 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605 * The statistics we have collected organized by uids.
606 */
Adam Lesinski50e47602015-12-04 17:04:54 -0800607 final SparseArray<BatteryStatsImpl.Uid> mUidStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608
609 // A set of pools of currently active timers. When a timer is queried, we will divide the
610 // elapsed time by the number of active timers to arrive at that timer's share of the time.
611 // In order to do this, we must refresh each timer whenever the number of active timers
612 // changes.
Sudheer Shanka38383232017-07-25 09:55:03 -0700613 @VisibleForTesting
Mathew Inwoodc185f082018-08-20 14:28:54 +0100614 @UnsupportedAppUsage
Sudheer Shanka38383232017-07-25 09:55:03 -0700615 protected ArrayList<StopwatchTimer> mPartialTimers = new ArrayList<>();
Mathew Inwoodc185f082018-08-20 14:28:54 +0100616 @UnsupportedAppUsage
Adam Lesinskie08af192015-03-25 16:42:59 -0700617 final ArrayList<StopwatchTimer> mFullTimers = new ArrayList<>();
Mathew Inwoodc185f082018-08-20 14:28:54 +0100618 @UnsupportedAppUsage
Adam Lesinskie08af192015-03-25 16:42:59 -0700619 final ArrayList<StopwatchTimer> mWindowTimers = new ArrayList<>();
Jeff Brown6a8bd7b2015-06-19 15:07:51 -0700620 final ArrayList<StopwatchTimer> mDrawTimers = new ArrayList<>();
Adam Lesinskie08af192015-03-25 16:42:59 -0700621 final SparseArray<ArrayList<StopwatchTimer>> mSensorTimers = new SparseArray<>();
622 final ArrayList<StopwatchTimer> mWifiRunningTimers = new ArrayList<>();
623 final ArrayList<StopwatchTimer> mFullWifiLockTimers = new ArrayList<>();
624 final ArrayList<StopwatchTimer> mWifiMulticastTimers = new ArrayList<>();
625 final ArrayList<StopwatchTimer> mWifiScanTimers = new ArrayList<>();
626 final SparseArray<ArrayList<StopwatchTimer>> mWifiBatchedScanTimers = new SparseArray<>();
627 final ArrayList<StopwatchTimer> mAudioTurnedOnTimers = new ArrayList<>();
628 final ArrayList<StopwatchTimer> mVideoTurnedOnTimers = new ArrayList<>();
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700629 final ArrayList<StopwatchTimer> mFlashlightTurnedOnTimers = new ArrayList<>();
630 final ArrayList<StopwatchTimer> mCameraTurnedOnTimers = new ArrayList<>();
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800631 final ArrayList<StopwatchTimer> mBluetoothScanOnTimers = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700633 // Last partial timers we use for distributing CPU usage.
Sudheer Shanka38383232017-07-25 09:55:03 -0700634 @VisibleForTesting
635 protected ArrayList<StopwatchTimer> mLastPartialTimers = new ArrayList<>();
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800637 // These are the objects that will want to do something when the device
638 // is unplugged from power.
Joe Onoratoabded112016-02-08 16:49:39 -0800639 protected final TimeBase mOnBatteryTimeBase = new TimeBase();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800640
641 // These are the objects that will want to do something when the device
Mike Mac2f518a2017-09-19 16:06:03 -0700642 // is unplugged from power *and* the screen is off or doze.
643 protected final TimeBase mOnBatteryScreenOffTimeBase = new TimeBase();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800644
645 // Set to true when we want to distribute CPU across wakelocks for the next
646 // CPU update, even if we aren't currently running wake locks.
647 boolean mDistributeWakelockCpu;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700648
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700649 boolean mShuttingDown;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700650
Dianne Hackborn37de0982014-05-09 09:32:18 -0700651 final HistoryEventTracker mActiveEvents = new HistoryEventTracker();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800652
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700653 long mHistoryBaseTime;
Narayan Kamath695cf722017-12-21 18:32:47 +0000654 protected boolean mHaveBatteryLevel = false;
655 protected boolean mRecordingHistory = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700656 int mNumHistoryItems;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700657
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700658 final Parcel mHistoryBuffer = Parcel.obtain();
659 final HistoryItem mHistoryLastWritten = new HistoryItem();
660 final HistoryItem mHistoryLastLastWritten = new HistoryItem();
Dianne Hackborn1fadab52011-04-14 17:57:33 -0700661 final HistoryItem mHistoryReadTmp = new HistoryItem();
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700662 final HistoryItem mHistoryAddTmp = new HistoryItem();
Adam Lesinskie08af192015-03-25 16:42:59 -0700663 final HashMap<HistoryTag, Integer> mHistoryTagPool = new HashMap<>();
Dianne Hackborn099bc622014-01-22 13:39:16 -0800664 String[] mReadHistoryStrings;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -0800665 int[] mReadHistoryUids;
666 int mReadHistoryChars;
667 int mNextHistoryTagIdx = 0;
668 int mNumHistoryTagChars = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700669 int mHistoryBufferLastPos = -1;
670 boolean mHistoryOverflow = false;
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700671 int mActiveHistoryStates = 0xffffffff;
672 int mActiveHistoryStates2 = 0xffffffff;
Dianne Hackborn40c87252014-03-19 16:55:40 -0700673 long mLastHistoryElapsedRealtime = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700674 long mTrackRunningHistoryElapsedRealtime = 0;
675 long mTrackRunningHistoryUptime = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700676
677 final HistoryItem mHistoryCur = new HistoryItem();
678
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700679 HistoryItem mHistory;
680 HistoryItem mHistoryEnd;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700681 HistoryItem mHistoryLastEnd;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700682 HistoryItem mHistoryCache;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700683
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800684 // Used by computeHistoryStepDetails
685 HistoryStepDetails mLastHistoryStepDetails = null;
686 byte mLastHistoryStepLevel = 0;
687 final HistoryStepDetails mCurHistoryStepDetails = new HistoryStepDetails();
688 final HistoryStepDetails mReadHistoryStepDetails = new HistoryStepDetails();
689 final HistoryStepDetails mTmpHistoryStepDetails = new HistoryStepDetails();
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700690
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800691 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700692 * Total time (in milliseconds) spent executing in user code.
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800693 */
694 long mLastStepCpuUserTime;
695 long mCurStepCpuUserTime;
696 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700697 * Total time (in milliseconds) spent executing in kernel code.
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800698 */
699 long mLastStepCpuSystemTime;
700 long mCurStepCpuSystemTime;
701 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700702 * Times from /proc/stat (but measured in milliseconds).
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800703 */
704 long mLastStepStatUserTime;
705 long mLastStepStatSystemTime;
706 long mLastStepStatIOWaitTime;
707 long mLastStepStatIrqTime;
708 long mLastStepStatSoftIrqTime;
709 long mLastStepStatIdleTime;
710 long mCurStepStatUserTime;
711 long mCurStepStatSystemTime;
712 long mCurStepStatIOWaitTime;
713 long mCurStepStatIrqTime;
714 long mCurStepStatSoftIrqTime;
715 long mCurStepStatIdleTime;
716
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700717 private HistoryItem mHistoryIterator;
718 private boolean mReadOverflow;
719 private boolean mIteratingHistory;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 int mStartCount;
722
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -0800723 long mStartClockTime;
Dianne Hackborncd0e3352014-08-07 17:08:09 -0700724 String mStartPlatformVersion;
725 String mEndPlatformVersion;
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -0800726
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727 long mUptime;
728 long mUptimeStart;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 long mRealtime;
730 long mRealtimeStart;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700731
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800732 int mWakeLockNesting;
733 boolean mWakeLockImportant;
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700734 public boolean mRecordAllHistory;
Dianne Hackborn9a755432014-05-15 17:05:22 -0700735 boolean mNoAutoReset;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800736
Mike Mac2f518a2017-09-19 16:06:03 -0700737 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
738 protected int mScreenState = Display.STATE_UNKNOWN;
739 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
740 protected StopwatchTimer mScreenOnTimer;
741 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
742 protected StopwatchTimer mScreenDozeTimer;
Amith Yamasani3718aaa2009-06-09 06:32:35 -0700743
Dianne Hackborn617f8772009-03-31 15:04:46 -0700744 int mScreenBrightnessBin = -1;
Evan Millarc64edde2009-04-18 12:26:32 -0700745 final StopwatchTimer[] mScreenBrightnessTimer = new StopwatchTimer[NUM_SCREEN_BRIGHTNESS_BINS];
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700746
Amith Yamasani674c9bb2017-02-01 09:45:17 -0800747 boolean mPretendScreenOff;
748
Jeff Browne95c3cd2014-05-02 16:59:26 -0700749 boolean mInteractive;
750 StopwatchTimer mInteractiveTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700751
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700752 boolean mPowerSaveModeEnabled;
753 StopwatchTimer mPowerSaveModeEnabledTimer;
754
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700755 boolean mDeviceIdling;
756 StopwatchTimer mDeviceIdlingTimer;
757
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700758 boolean mDeviceLightIdling;
759 StopwatchTimer mDeviceLightIdlingTimer;
760
761 int mDeviceIdleMode;
762 long mLastIdleTimeStart;
763 long mLongestLightIdleTime;
764 long mLongestFullIdleTime;
765 StopwatchTimer mDeviceIdleModeLightTimer;
766 StopwatchTimer mDeviceIdleModeFullTimer;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800768 boolean mPhoneOn;
Evan Millarc64edde2009-04-18 12:26:32 -0700769 StopwatchTimer mPhoneOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700770
Dianne Hackborn10eaa852014-07-22 22:54:55 -0700771 int mAudioOnNesting;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700772 StopwatchTimer mAudioOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700773
Dianne Hackborn10eaa852014-07-22 22:54:55 -0700774 int mVideoOnNesting;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700775 StopwatchTimer mVideoOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700776
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700777 int mFlashlightOnNesting;
Dianne Hackbornabc7c492014-06-30 16:57:46 -0700778 StopwatchTimer mFlashlightOnTimer;
779
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700780 int mCameraOnNesting;
781 StopwatchTimer mCameraOnTimer;
782
Mike Mafbc01fc2018-04-02 10:28:28 -0700783 private static final int USB_DATA_UNKNOWN = 0;
784 private static final int USB_DATA_DISCONNECTED = 1;
785 private static final int USB_DATA_CONNECTED = 2;
786 int mUsbDataState = USB_DATA_UNKNOWN;
Mike Ma926a97c2018-03-25 02:32:35 -0700787
Siddharth Ray78ccaf52017-12-23 16:16:21 -0800788 int mGpsSignalQualityBin = -1;
Narayan Kamathefa0fe62018-02-05 16:04:43 +0000789 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
790 protected final StopwatchTimer[] mGpsSignalQualityTimer =
Siddharth Ray78ccaf52017-12-23 16:16:21 -0800791 new StopwatchTimer[GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS];
792
Dianne Hackborn627bba72009-03-24 22:32:56 -0700793 int mPhoneSignalStrengthBin = -1;
Dianne Hackborne4a59512010-12-07 11:08:07 -0800794 int mPhoneSignalStrengthBinRaw = -1;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700795 final StopwatchTimer[] mPhoneSignalStrengthsTimer =
Wink Saville52840902011-02-18 12:40:47 -0800796 new StopwatchTimer[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
Amith Yamasanif37447b2009-10-08 18:28:01 -0700797
798 StopwatchTimer mPhoneSignalScanningTimer;
799
Dianne Hackborn627bba72009-03-24 22:32:56 -0700800 int mPhoneDataConnectionType = -1;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700801 final StopwatchTimer[] mPhoneDataConnectionsTimer =
Evan Millarc64edde2009-04-18 12:26:32 -0700802 new StopwatchTimer[NUM_DATA_CONNECTION_TYPES];
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700803
Dianne Hackborn57ed6a62013-12-09 18:15:56 -0800804 final LongSamplingCounter[] mNetworkByteActivityCounters =
805 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
806 final LongSamplingCounter[] mNetworkPacketActivityCounters =
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700807 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
808
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800809 /**
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -0800810 * The WiFi Overall wakelock timer
811 * This timer tracks the actual aggregate time for which MC wakelocks are enabled
812 * since addition of per UID timers would not result in an accurate value due to overlapp of
813 * per uid wakelock timers
814 */
815 StopwatchTimer mWifiMulticastWakelockTimer;
816
817 /**
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800818 * The WiFi controller activity (time in tx, rx, idle, and power consumed) for the device.
819 */
820 ControllerActivityCounterImpl mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -0700821
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800822 /**
823 * The Bluetooth controller activity (time in tx, rx, idle, and power consumed) for the device.
824 */
825 ControllerActivityCounterImpl mBluetoothActivity;
826
827 /**
828 * The Modem controller activity (time in tx, rx, idle, and power consumed) for the device.
829 */
830 ControllerActivityCounterImpl mModemActivity;
831
832 /**
833 * Whether the device supports WiFi controller energy reporting. This is set to true on
834 * the first WiFi energy report. See {@link #mWifiActivity}.
835 */
836 boolean mHasWifiReporting = false;
837
838 /**
839 * Whether the device supports Bluetooth controller energy reporting. This is set to true on
840 * the first Bluetooth energy report. See {@link #mBluetoothActivity}.
841 */
842 boolean mHasBluetoothReporting = false;
843
844 /**
845 * Whether the device supports Modem controller energy reporting. This is set to true on
846 * the first Modem energy report. See {@link #mModemActivity}.
847 */
848 boolean mHasModemReporting = false;
Adam Lesinski33dac552015-03-09 15:24:48 -0700849
The Android Open Source Project10592532009-03-18 17:39:46 -0700850 boolean mWifiOn;
Evan Millarc64edde2009-04-18 12:26:32 -0700851 StopwatchTimer mWifiOnTimer;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -0700852
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700853 boolean mGlobalWifiRunning;
854 StopwatchTimer mGlobalWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700855
Dianne Hackbornca1bf212014-02-14 14:18:36 -0800856 int mWifiState = -1;
857 final StopwatchTimer[] mWifiStateTimer = new StopwatchTimer[NUM_WIFI_STATES];
858
Dianne Hackborn3251b902014-06-20 14:40:53 -0700859 int mWifiSupplState = -1;
860 final StopwatchTimer[] mWifiSupplStateTimer = new StopwatchTimer[NUM_WIFI_SUPPL_STATES];
861
862 int mWifiSignalStrengthBin = -1;
863 final StopwatchTimer[] mWifiSignalStrengthsTimer =
864 new StopwatchTimer[NUM_WIFI_SIGNAL_STRENGTH_BINS];
865
Siddharth Rayb50a6842017-12-14 15:15:28 -0800866 StopwatchTimer mWifiActiveTimer;
867
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800868 int mBluetoothScanNesting;
Bookatz867c0d72017-03-07 18:23:42 -0800869 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
870 protected StopwatchTimer mBluetoothScanTimer;
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800871
Siddharth Rayf5e796a2018-01-22 18:18:17 -0800872 boolean mIsCellularTxPowerHigh = false;
873
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700874 int mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackbornf7097a52014-05-13 09:56:14 -0700875 long mMobileRadioActiveStartTime;
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800876 StopwatchTimer mMobileRadioActiveTimer;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800877 StopwatchTimer mMobileRadioActivePerAppTimer;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700878 LongSamplingCounter mMobileRadioActiveAdjustedTime;
Dianne Hackbornd45665b2014-02-26 12:35:32 -0800879 LongSamplingCounter mMobileRadioActiveUnknownTime;
880 LongSamplingCounter mMobileRadioActiveUnknownCount;
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800881
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700882 int mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884 /**
885 * These provide time bases that discount the time the device is plugged
886 * in to power.
887 */
888 boolean mOnBattery;
Sudheer Shanka38383232017-07-25 09:55:03 -0700889 @VisibleForTesting
890 protected boolean mOnBatteryInternal;
Amith Yamasani3718aaa2009-06-09 06:32:35 -0700891
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700892 /**
893 * External reporting of whether the device is actually charging.
894 */
895 boolean mCharging = true;
896 int mLastChargingStateLevel;
897
The Android Open Source Project10592532009-03-18 17:39:46 -0700898 /*
899 * These keep track of battery levels (1-100) at the last plug event and the last unplug event.
900 */
Evan Millar633a1742009-04-02 16:36:33 -0700901 int mDischargeStartLevel;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700902 int mDischargeUnplugLevel;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700903 int mDischargePlugLevel;
Evan Millar633a1742009-04-02 16:36:33 -0700904 int mDischargeCurrentLevel;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700905 int mCurrentBatteryLevel;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -0700906 int mLowDischargeAmountSinceCharge;
907 int mHighDischargeAmountSinceCharge;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -0800908 int mDischargeScreenOnUnplugLevel;
909 int mDischargeScreenOffUnplugLevel;
Mike Mac2f518a2017-09-19 16:06:03 -0700910 int mDischargeScreenDozeUnplugLevel;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -0800911 int mDischargeAmountScreenOn;
912 int mDischargeAmountScreenOnSinceCharge;
913 int mDischargeAmountScreenOff;
914 int mDischargeAmountScreenOffSinceCharge;
Mike Mac2f518a2017-09-19 16:06:03 -0700915 int mDischargeAmountScreenDoze;
916 int mDischargeAmountScreenDozeSinceCharge;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700917
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700918 private LongSamplingCounter mDischargeScreenOffCounter;
Mike Mac2f518a2017-09-19 16:06:03 -0700919 private LongSamplingCounter mDischargeScreenDozeCounter;
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700920 private LongSamplingCounter mDischargeCounter;
Mike Ma15313c92017-11-15 17:58:21 -0800921 private LongSamplingCounter mDischargeLightDozeCounter;
922 private LongSamplingCounter mDischargeDeepDozeCounter;
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700923
Dianne Hackborncd0e3352014-08-07 17:08:09 -0700924 static final int MAX_LEVEL_STEPS = 200;
Dianne Hackborn260c5022014-04-29 11:23:16 -0700925
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700926 int mInitStepMode = 0;
927 int mCurStepMode = 0;
928 int mModStepMode = 0;
929
Dianne Hackborn260c5022014-04-29 11:23:16 -0700930 int mLastDischargeStepLevel;
Dianne Hackborn29325132014-05-21 15:01:03 -0700931 int mMinDischargeStepLevel;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800932 final LevelStepTracker mDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS);
933 final LevelStepTracker mDailyDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700934 ArrayList<PackageChange> mDailyPackageChanges;
Dianne Hackborn260c5022014-04-29 11:23:16 -0700935
936 int mLastChargeStepLevel;
Dianne Hackborn29325132014-05-21 15:01:03 -0700937 int mMaxChargeStepLevel;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800938 final LevelStepTracker mChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS);
939 final LevelStepTracker mDailyChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2);
940
941 static final int MAX_DAILY_ITEMS = 10;
942
943 long mDailyStartTime = 0;
944 long mNextMinDailyDeadline = 0;
945 long mNextMaxDailyDeadline = 0;
946
947 final ArrayList<DailyItem> mDailyItems = new ArrayList<>();
Dianne Hackborn260c5022014-04-29 11:23:16 -0700948
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 long mLastWriteTime = 0; // Milliseconds
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700950
Amith Yamasanif37447b2009-10-08 18:28:01 -0700951 private int mPhoneServiceState = -1;
Dianne Hackborne4a59512010-12-07 11:08:07 -0800952 private int mPhoneServiceStateRaw = -1;
953 private int mPhoneSimStateRaw = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -0700954
Dianne Hackborn1e01d162014-12-04 17:46:42 -0800955 private int mNumConnectivityChange;
956 private int mLoadedNumConnectivityChange;
957 private int mUnpluggedNumConnectivityChange;
958
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700959 private int mEstimatedBatteryCapacity = -1;
960
Jocelyn Dangc627d102017-04-14 13:15:14 -0700961 private int mMinLearnedBatteryCapacity = -1;
962 private int mMaxLearnedBatteryCapacity = -1;
Adam Lesinski041d9172016-12-12 12:03:56 -0800963
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700964 private long[] mCpuFreqs;
965
Sudheer Shanka38383232017-07-25 09:55:03 -0700966 @VisibleForTesting
967 protected PowerProfile mPowerProfile;
Adam Lesinskie08af192015-03-25 16:42:59 -0700968
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800969 @GuardedBy("this")
970 private final Constants mConstants;
971
Evan Millarc64edde2009-04-18 12:26:32 -0700972 /*
Bookatz50df7112017-08-04 14:53:26 -0700973 * Holds a SamplingTimer associated with each Resource Power Manager state and voter,
974 * recording their times when on-battery (regardless of screen state).
975 */
976 private final HashMap<String, SamplingTimer> mRpmStats = new HashMap<>();
977 /** Times for each Resource Power Manager state and voter when screen-off and on-battery. */
978 private final HashMap<String, SamplingTimer> mScreenOffRpmStats = new HashMap<>();
979
980 @Override
981 public Map<String, ? extends Timer> getRpmStats() {
982 return mRpmStats;
983 }
984
Bookatz82b341172017-09-07 19:06:08 -0700985 // TODO: Note: screenOffRpmStats has been disabled via SCREEN_OFF_RPM_STATS_ENABLED.
Bookatz50df7112017-08-04 14:53:26 -0700986 @Override
987 public Map<String, ? extends Timer> getScreenOffRpmStats() {
988 return mScreenOffRpmStats;
989 }
990
991 /*
Evan Millarc64edde2009-04-18 12:26:32 -0700992 * Holds a SamplingTimer associated with each kernel wakelock name being tracked.
993 */
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700994 private final HashMap<String, SamplingTimer> mKernelWakelockStats = new HashMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700995
Mathew Inwoodc185f082018-08-20 14:28:54 +0100996 @UnsupportedAppUsage
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700997 public Map<String, ? extends Timer> getKernelWakelockStats() {
Evan Millarc64edde2009-04-18 12:26:32 -0700998 return mKernelWakelockStats;
999 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001000
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001001 String mLastWakeupReason = null;
1002 long mLastWakeupUptimeMs = 0;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07001003 private final HashMap<String, SamplingTimer> mWakeupReasonStats = new HashMap<>();
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001004
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07001005 public Map<String, ? extends Timer> getWakeupReasonStats() {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001006 return mWakeupReasonStats;
1007 }
1008
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001009 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -07001010 public long getUahDischarge(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -07001011 return mDischargeCounter.getCountLocked(which);
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001012 }
1013
1014 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -07001015 public long getUahDischargeScreenOff(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -07001016 return mDischargeScreenOffCounter.getCountLocked(which);
1017 }
1018
1019 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -07001020 public long getUahDischargeScreenDoze(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -07001021 return mDischargeScreenDozeCounter.getCountLocked(which);
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001022 }
1023
Adam Lesinskif9b20a92016-06-17 17:30:01 -07001024 @Override
Mike Ma15313c92017-11-15 17:58:21 -08001025 public long getUahDischargeLightDoze(int which) {
1026 return mDischargeLightDozeCounter.getCountLocked(which);
1027 }
1028
1029 @Override
1030 public long getUahDischargeDeepDoze(int which) {
1031 return mDischargeDeepDozeCounter.getCountLocked(which);
1032 }
1033
1034 @Override
Adam Lesinskif9b20a92016-06-17 17:30:01 -07001035 public int getEstimatedBatteryCapacity() {
1036 return mEstimatedBatteryCapacity;
1037 }
1038
Jocelyn Dangc627d102017-04-14 13:15:14 -07001039 @Override
1040 public int getMinLearnedBatteryCapacity() {
1041 return mMinLearnedBatteryCapacity;
1042 }
1043
1044 @Override
1045 public int getMaxLearnedBatteryCapacity() {
1046 return mMaxLearnedBatteryCapacity;
1047 }
1048
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 public BatteryStatsImpl() {
Joe Onoratoabded112016-02-08 16:49:39 -08001050 this(new SystemClocks());
1051 }
1052
1053 public BatteryStatsImpl(Clocks clocks) {
1054 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07001055 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07001056 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08001057 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001058 mHandler = null;
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07001059 mPlatformIdleStateCallback = null;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -07001060 mUserInfoProvider = null;
Sudheer Shanka5c19b892018-01-05 17:25:46 -08001061 mConstants = new Constants(mHandler);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07001062 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 }
1064
Joe Onoratoabded112016-02-08 16:49:39 -08001065 private void init(Clocks clocks) {
1066 mClocks = clocks;
Joe Onoratoabded112016-02-08 16:49:39 -08001067 }
1068
Adam Lesinski14ae39a2017-05-26 11:50:40 -07001069 public interface TimeBaseObs {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001070 void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime);
1071 void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime);
1072 }
1073
Joe Onoratoabded112016-02-08 16:49:39 -08001074 // methods are protected not private to be VisibleForTesting
1075 public static class TimeBase {
1076 protected final ArrayList<TimeBaseObs> mObservers = new ArrayList<>();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001077
Joe Onoratoabded112016-02-08 16:49:39 -08001078 protected long mUptime;
1079 protected long mRealtime;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001080
Joe Onoratoabded112016-02-08 16:49:39 -08001081 protected boolean mRunning;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001082
Joe Onoratoabded112016-02-08 16:49:39 -08001083 protected long mPastUptime;
1084 protected long mUptimeStart;
1085 protected long mPastRealtime;
1086 protected long mRealtimeStart;
1087 protected long mUnpluggedUptime;
1088 protected long mUnpluggedRealtime;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001089
1090 public void dump(PrintWriter pw, String prefix) {
1091 StringBuilder sb = new StringBuilder(128);
1092 pw.print(prefix); pw.print("mRunning="); pw.println(mRunning);
1093 sb.setLength(0);
1094 sb.append(prefix);
1095 sb.append("mUptime=");
Dianne Hackborn4590e522014-03-24 13:36:46 -07001096 formatTimeMs(sb, mUptime / 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001097 pw.println(sb.toString());
1098 sb.setLength(0);
1099 sb.append(prefix);
1100 sb.append("mRealtime=");
Dianne Hackborn4590e522014-03-24 13:36:46 -07001101 formatTimeMs(sb, mRealtime / 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001102 pw.println(sb.toString());
1103 sb.setLength(0);
1104 sb.append(prefix);
1105 sb.append("mPastUptime=");
1106 formatTimeMs(sb, mPastUptime / 1000); sb.append("mUptimeStart=");
1107 formatTimeMs(sb, mUptimeStart / 1000);
1108 sb.append("mUnpluggedUptime="); formatTimeMs(sb, mUnpluggedUptime / 1000);
1109 pw.println(sb.toString());
1110 sb.setLength(0);
1111 sb.append(prefix);
1112 sb.append("mPastRealtime=");
1113 formatTimeMs(sb, mPastRealtime / 1000); sb.append("mRealtimeStart=");
1114 formatTimeMs(sb, mRealtimeStart / 1000);
1115 sb.append("mUnpluggedRealtime="); formatTimeMs(sb, mUnpluggedRealtime / 1000);
1116 pw.println(sb.toString());
1117 }
1118
1119 public void add(TimeBaseObs observer) {
1120 mObservers.add(observer);
1121 }
1122
1123 public void remove(TimeBaseObs observer) {
1124 if (!mObservers.remove(observer)) {
1125 Slog.wtf(TAG, "Removed unknown observer: " + observer);
1126 }
1127 }
1128
Joe Onoratoabded112016-02-08 16:49:39 -08001129 public boolean hasObserver(TimeBaseObs observer) {
1130 return mObservers.contains(observer);
1131 }
1132
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001133 public void init(long uptime, long realtime) {
1134 mRealtime = 0;
1135 mUptime = 0;
1136 mPastUptime = 0;
1137 mPastRealtime = 0;
1138 mUptimeStart = uptime;
1139 mRealtimeStart = realtime;
1140 mUnpluggedUptime = getUptime(mUptimeStart);
1141 mUnpluggedRealtime = getRealtime(mRealtimeStart);
1142 }
1143
1144 public void reset(long uptime, long realtime) {
1145 if (!mRunning) {
1146 mPastUptime = 0;
1147 mPastRealtime = 0;
1148 } else {
1149 mUptimeStart = uptime;
1150 mRealtimeStart = realtime;
Joe Onoratoabded112016-02-08 16:49:39 -08001151 // TODO: Since mUptimeStart was just reset and we are running, getUptime will
1152 // just return mPastUptime. Also, are we sure we don't want to reset that?
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001153 mUnpluggedUptime = getUptime(uptime);
Joe Onoratoabded112016-02-08 16:49:39 -08001154 // TODO: likewise.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001155 mUnpluggedRealtime = getRealtime(realtime);
1156 }
1157 }
1158
1159 public long computeUptime(long curTime, int which) {
1160 switch (which) {
1161 case STATS_SINCE_CHARGED:
1162 return mUptime + getUptime(curTime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001163 case STATS_CURRENT:
1164 return getUptime(curTime);
1165 case STATS_SINCE_UNPLUGGED:
1166 return getUptime(curTime) - mUnpluggedUptime;
1167 }
1168 return 0;
1169 }
1170
1171 public long computeRealtime(long curTime, int which) {
1172 switch (which) {
1173 case STATS_SINCE_CHARGED:
1174 return mRealtime + getRealtime(curTime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001175 case STATS_CURRENT:
1176 return getRealtime(curTime);
1177 case STATS_SINCE_UNPLUGGED:
1178 return getRealtime(curTime) - mUnpluggedRealtime;
1179 }
1180 return 0;
1181 }
1182
1183 public long getUptime(long curTime) {
1184 long time = mPastUptime;
1185 if (mRunning) {
1186 time += curTime - mUptimeStart;
1187 }
1188 return time;
1189 }
1190
1191 public long getRealtime(long curTime) {
1192 long time = mPastRealtime;
1193 if (mRunning) {
1194 time += curTime - mRealtimeStart;
1195 }
1196 return time;
1197 }
1198
1199 public long getUptimeStart() {
1200 return mUptimeStart;
1201 }
1202
1203 public long getRealtimeStart() {
1204 return mRealtimeStart;
1205 }
1206
1207 public boolean isRunning() {
1208 return mRunning;
1209 }
1210
1211 public boolean setRunning(boolean running, long uptime, long realtime) {
1212 if (mRunning != running) {
1213 mRunning = running;
1214 if (running) {
1215 mUptimeStart = uptime;
1216 mRealtimeStart = realtime;
1217 long batteryUptime = mUnpluggedUptime = getUptime(uptime);
1218 long batteryRealtime = mUnpluggedRealtime = getRealtime(realtime);
1219
1220 for (int i = mObservers.size() - 1; i >= 0; i--) {
1221 mObservers.get(i).onTimeStarted(realtime, batteryUptime, batteryRealtime);
1222 }
1223 } else {
1224 mPastUptime += uptime - mUptimeStart;
1225 mPastRealtime += realtime - mRealtimeStart;
1226
1227 long batteryUptime = getUptime(uptime);
1228 long batteryRealtime = getRealtime(realtime);
1229
1230 for (int i = mObservers.size() - 1; i >= 0; i--) {
1231 mObservers.get(i).onTimeStopped(realtime, batteryUptime, batteryRealtime);
1232 }
1233 }
1234 return true;
1235 }
1236 return false;
1237 }
1238
1239 public void readSummaryFromParcel(Parcel in) {
1240 mUptime = in.readLong();
1241 mRealtime = in.readLong();
1242 }
1243
1244 public void writeSummaryToParcel(Parcel out, long uptime, long realtime) {
1245 out.writeLong(computeUptime(uptime, STATS_SINCE_CHARGED));
1246 out.writeLong(computeRealtime(realtime, STATS_SINCE_CHARGED));
1247 }
1248
1249 public void readFromParcel(Parcel in) {
1250 mRunning = false;
1251 mUptime = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001252 mPastUptime = in.readLong();
1253 mUptimeStart = in.readLong();
Dianne Hackbornef640cd2014-03-25 14:41:05 -07001254 mRealtime = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001255 mPastRealtime = in.readLong();
1256 mRealtimeStart = in.readLong();
1257 mUnpluggedUptime = in.readLong();
1258 mUnpluggedRealtime = in.readLong();
1259 }
1260
1261 public void writeToParcel(Parcel out, long uptime, long realtime) {
1262 final long runningUptime = getUptime(uptime);
1263 final long runningRealtime = getRealtime(realtime);
1264 out.writeLong(mUptime);
1265 out.writeLong(runningUptime);
1266 out.writeLong(mUptimeStart);
Dianne Hackbornef640cd2014-03-25 14:41:05 -07001267 out.writeLong(mRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001268 out.writeLong(runningRealtime);
1269 out.writeLong(mRealtimeStart);
1270 out.writeLong(mUnpluggedUptime);
1271 out.writeLong(mUnpluggedRealtime);
1272 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001273 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 /**
Dianne Hackborn617f8772009-03-31 15:04:46 -07001276 * State for keeping track of counting information.
1277 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001278 public static class Counter extends BatteryStats.Counter implements TimeBaseObs {
Mathew Inwoodc185f082018-08-20 14:28:54 +01001279 @UnsupportedAppUsage
Christopher Tate4cee7252010-03-19 14:50:40 -07001280 final AtomicInteger mCount = new AtomicInteger();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001281 final TimeBase mTimeBase;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001282 int mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001283 int mUnpluggedCount;
1284 int mPluggedCount;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001285
Bookatz8c6f3c52017-05-24 12:00:17 -07001286 public Counter(TimeBase timeBase, Parcel in) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001287 mTimeBase = timeBase;
Christopher Tate4cee7252010-03-19 14:50:40 -07001288 mPluggedCount = in.readInt();
1289 mCount.set(mPluggedCount);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001290 mLoadedCount = in.readInt();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001291 mUnpluggedCount = in.readInt();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001292 timeBase.add(this);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001293 }
1294
Bookatz8c6f3c52017-05-24 12:00:17 -07001295 public Counter(TimeBase timeBase) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001296 mTimeBase = timeBase;
1297 timeBase.add(this);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001298 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001299
Dianne Hackborn617f8772009-03-31 15:04:46 -07001300 public void writeToParcel(Parcel out) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001301 out.writeInt(mCount.get());
Dianne Hackborn617f8772009-03-31 15:04:46 -07001302 out.writeInt(mLoadedCount);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001303 out.writeInt(mUnpluggedCount);
1304 }
1305
Bookatz8c6f3c52017-05-24 12:00:17 -07001306 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001307 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001308 mUnpluggedCount = mPluggedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001309 }
1310
Bookatz8c6f3c52017-05-24 12:00:17 -07001311 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001312 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001313 mPluggedCount = mCount.get();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001314 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001315
Dianne Hackborn617f8772009-03-31 15:04:46 -07001316 /**
1317 * Writes a possibly null Counter to a Parcel.
1318 *
1319 * @param out the Parcel to be written to.
1320 * @param counter a Counter, or null.
1321 */
Amith Yamasani977e11f2018-02-16 11:29:54 -08001322 public static void writeCounterToParcel(Parcel out, @Nullable Counter counter) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07001323 if (counter == null) {
1324 out.writeInt(0); // indicates null
1325 return;
1326 }
1327 out.writeInt(1); // indicates non-null
1328
1329 counter.writeToParcel(out);
1330 }
1331
Amith Yamasani977e11f2018-02-16 11:29:54 -08001332 /**
1333 * Reads a Counter that was written using {@link #writeCounterToParcel(Parcel, Counter)}.
1334 * @param timeBase the timebase to assign to the Counter
1335 * @param in the parcel to read from
1336 * @return the Counter or null.
1337 */
1338 public static @Nullable Counter readCounterFromParcel(TimeBase timeBase, Parcel in) {
1339 if (in.readInt() == 0) {
1340 return null;
1341 }
1342 return new Counter(timeBase, in);
1343 }
1344
Dianne Hackborn617f8772009-03-31 15:04:46 -07001345 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001346 public int getCountLocked(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001347 int val = mCount.get();
1348 if (which == STATS_SINCE_UNPLUGGED) {
1349 val -= mUnpluggedCount;
1350 } else if (which != STATS_SINCE_CHARGED) {
1351 val -= mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001352 }
1353
1354 return val;
1355 }
1356
1357 public void logState(Printer pw, String prefix) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001358 pw.println(prefix + "mCount=" + mCount.get()
Bookatz8c6f3c52017-05-24 12:00:17 -07001359 + " mLoadedCount=" + mLoadedCount
Dianne Hackborn617f8772009-03-31 15:04:46 -07001360 + " mUnpluggedCount=" + mUnpluggedCount
1361 + " mPluggedCount=" + mPluggedCount);
1362 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001363
Bookatz8c6f3c52017-05-24 12:00:17 -07001364 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1365 public void stepAtomic() {
1366 if (mTimeBase.isRunning()) {
1367 mCount.incrementAndGet();
1368 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001369 }
1370
Bookatz4ebc0642017-05-11 12:21:19 -07001371 void addAtomic(int delta) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001372 if (mTimeBase.isRunning()) {
1373 mCount.addAndGet(delta);
1374 }
Bookatz4ebc0642017-05-11 12:21:19 -07001375 }
1376
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001377 /**
1378 * Clear state of this counter.
1379 */
1380 void reset(boolean detachIfReset) {
1381 mCount.set(0);
Bookatz8c6f3c52017-05-24 12:00:17 -07001382 mLoadedCount = mPluggedCount = mUnpluggedCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001383 if (detachIfReset) {
1384 detach();
1385 }
1386 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001387
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001388 void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001389 mTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001390 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001391
Bookatz8c6f3c52017-05-24 12:00:17 -07001392 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1393 public void writeSummaryFromParcelLocked(Parcel out) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001394 int count = mCount.get();
1395 out.writeInt(count);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001396 }
1397
Bookatz8c6f3c52017-05-24 12:00:17 -07001398 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1399 public void readSummaryFromParcelLocked(Parcel in) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001400 mLoadedCount = in.readInt();
1401 mCount.set(mLoadedCount);
Christopher Tate4cee7252010-03-19 14:50:40 -07001402 mUnpluggedCount = mPluggedCount = mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001403 }
1404 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07001405
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001406 @VisibleForTesting
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001407 public static class LongSamplingCounterArray extends LongCounterArray implements TimeBaseObs {
1408 final TimeBase mTimeBase;
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001409 public long[] mCounts;
1410 public long[] mLoadedCounts;
1411 public long[] mUnpluggedCounts;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001412
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001413 private LongSamplingCounterArray(TimeBase timeBase, Parcel in) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001414 mTimeBase = timeBase;
Sudheer Shankae544d162017-12-28 17:06:20 -08001415 mCounts = in.createLongArray();
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001416 mLoadedCounts = in.createLongArray();
1417 mUnpluggedCounts = in.createLongArray();
1418 timeBase.add(this);
1419 }
1420
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001421 public LongSamplingCounterArray(TimeBase timeBase) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001422 mTimeBase = timeBase;
1423 timeBase.add(this);
1424 }
1425
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001426 private void writeToParcel(Parcel out) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001427 out.writeLongArray(mCounts);
1428 out.writeLongArray(mLoadedCounts);
1429 out.writeLongArray(mUnpluggedCounts);
1430 }
1431
1432 @Override
1433 public void onTimeStarted(long elapsedRealTime, long baseUptime, long baseRealtime) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001434 mUnpluggedCounts = copyArray(mCounts, mUnpluggedCounts);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001435 }
1436
1437 @Override
1438 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001439 }
1440
1441 @Override
1442 public long[] getCountsLocked(int which) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001443 long[] val = copyArray(mCounts, null);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001444 if (which == STATS_SINCE_UNPLUGGED) {
1445 subtract(val, mUnpluggedCounts);
1446 } else if (which != STATS_SINCE_CHARGED) {
1447 subtract(val, mLoadedCounts);
1448 }
1449 return val;
1450 }
1451
1452 @Override
1453 public void logState(Printer pw, String prefix) {
1454 pw.println(prefix + "mCounts=" + Arrays.toString(mCounts)
1455 + " mLoadedCounts=" + Arrays.toString(mLoadedCounts)
Sudheer Shankae544d162017-12-28 17:06:20 -08001456 + " mUnpluggedCounts=" + Arrays.toString(mUnpluggedCounts));
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001457 }
1458
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001459 public void addCountLocked(long[] counts) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001460 addCountLocked(counts, mTimeBase.isRunning());
1461 }
1462
1463 public void addCountLocked(long[] counts, boolean isRunning) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001464 if (counts == null) {
1465 return;
1466 }
Sudheer Shankae544d162017-12-28 17:06:20 -08001467 if (isRunning) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001468 if (mCounts == null) {
1469 mCounts = new long[counts.length];
1470 }
1471 for (int i = 0; i < counts.length; ++i) {
1472 mCounts[i] += counts[i];
1473 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001474 }
1475 }
1476
Sudheer Shankab8ad5942017-08-08 12:16:09 -07001477 public int getSize() {
1478 return mCounts == null ? 0 : mCounts.length;
1479 }
1480
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001481 /**
1482 * Clear state of this counter.
1483 */
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001484 public void reset(boolean detachIfReset) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001485 fillArray(mCounts, 0);
1486 fillArray(mLoadedCounts, 0);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001487 fillArray(mUnpluggedCounts, 0);
1488 if (detachIfReset) {
1489 detach();
1490 }
1491 }
1492
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001493 public void detach() {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001494 mTimeBase.remove(this);
1495 }
1496
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001497 private void writeSummaryToParcelLocked(Parcel out) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001498 out.writeLongArray(mCounts);
1499 }
1500
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001501 private void readSummaryFromParcelLocked(Parcel in) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001502 mCounts = in.createLongArray();
1503 mLoadedCounts = copyArray(mCounts, mLoadedCounts);
1504 mUnpluggedCounts = copyArray(mCounts, mUnpluggedCounts);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001505 }
1506
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001507 public static void writeToParcel(Parcel out, LongSamplingCounterArray counterArray) {
1508 if (counterArray != null) {
1509 out.writeInt(1);
1510 counterArray.writeToParcel(out);
1511 } else {
1512 out.writeInt(0);
1513 }
1514 }
1515
1516 public static LongSamplingCounterArray readFromParcel(Parcel in, TimeBase timeBase) {
1517 if (in.readInt() != 0) {
1518 return new LongSamplingCounterArray(timeBase, in);
1519 } else {
1520 return null;
1521 }
1522 }
1523
1524 public static void writeSummaryToParcelLocked(Parcel out,
1525 LongSamplingCounterArray counterArray) {
1526 if (counterArray != null) {
1527 out.writeInt(1);
1528 counterArray.writeSummaryToParcelLocked(out);
1529 } else {
1530 out.writeInt(0);
1531 }
1532 }
1533
1534 public static LongSamplingCounterArray readSummaryFromParcelLocked(Parcel in,
1535 TimeBase timeBase) {
1536 if (in.readInt() != 0) {
1537 final LongSamplingCounterArray counterArray
1538 = new LongSamplingCounterArray(timeBase);
1539 counterArray.readSummaryFromParcelLocked(in);
1540 return counterArray;
1541 } else {
1542 return null;
1543 }
1544 }
1545
Bookatz8c6f3c52017-05-24 12:00:17 -07001546 private static void fillArray(long[] a, long val) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001547 if (a != null) {
1548 Arrays.fill(a, val);
1549 }
1550 }
1551
Bookatz8c6f3c52017-05-24 12:00:17 -07001552 private static void subtract(@NonNull long[] val, long[] toSubtract) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001553 if (toSubtract == null) {
1554 return;
1555 }
1556 for (int i = 0; i < val.length; i++) {
1557 val[i] -= toSubtract[i];
1558 }
1559 }
1560
Bookatz8c6f3c52017-05-24 12:00:17 -07001561 private static long[] copyArray(long[] src, long[] dest) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001562 if (src == null) {
1563 return null;
1564 } else {
1565 if (dest == null) {
1566 dest = new long[src.length];
1567 }
1568 System.arraycopy(src, 0, dest, 0, src.length);
1569 return dest;
1570 }
1571 }
1572 }
1573
Mike Ma561a8d92018-03-20 18:24:05 -07001574 @VisibleForTesting
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001575 public static class LongSamplingCounter extends LongCounter implements TimeBaseObs {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001576 final TimeBase mTimeBase;
Mike Ma561a8d92018-03-20 18:24:05 -07001577 public long mCount;
1578 public long mCurrentCount;
1579 public long mLoadedCount;
1580 public long mUnpluggedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001581
Mike Ma561a8d92018-03-20 18:24:05 -07001582 public LongSamplingCounter(TimeBase timeBase, Parcel in) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001583 mTimeBase = timeBase;
Sudheer Shankac57729a2018-02-09 15:44:42 -08001584 mCount = in.readLong();
Mike Ma561a8d92018-03-20 18:24:05 -07001585 mCurrentCount = in.readLong();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001586 mLoadedCount = in.readLong();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001587 mUnpluggedCount = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001588 timeBase.add(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001589 }
1590
Mike Ma561a8d92018-03-20 18:24:05 -07001591 public LongSamplingCounter(TimeBase timeBase) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001592 mTimeBase = timeBase;
1593 timeBase.add(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001594 }
1595
1596 public void writeToParcel(Parcel out) {
1597 out.writeLong(mCount);
Mike Ma561a8d92018-03-20 18:24:05 -07001598 out.writeLong(mCurrentCount);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001599 out.writeLong(mLoadedCount);
1600 out.writeLong(mUnpluggedCount);
1601 }
1602
1603 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001604 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Sudheer Shankac57729a2018-02-09 15:44:42 -08001605 mUnpluggedCount = mCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001606 }
1607
1608 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001609 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001610 }
1611
1612 public long getCountLocked(int which) {
Sudheer Shankac57729a2018-02-09 15:44:42 -08001613 long val = mCount;
Dianne Hackborn4590e522014-03-24 13:36:46 -07001614 if (which == STATS_SINCE_UNPLUGGED) {
1615 val -= mUnpluggedCount;
1616 } else if (which != STATS_SINCE_CHARGED) {
1617 val -= mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001618 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001619 return val;
1620 }
1621
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001622 @Override
1623 public void logState(Printer pw, String prefix) {
1624 pw.println(prefix + "mCount=" + mCount
Mike Ma561a8d92018-03-20 18:24:05 -07001625 + " mCurrentCount=" + mCurrentCount
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001626 + " mLoadedCount=" + mLoadedCount
Sudheer Shankac57729a2018-02-09 15:44:42 -08001627 + " mUnpluggedCount=" + mUnpluggedCount);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001628 }
1629
Mike Ma561a8d92018-03-20 18:24:05 -07001630 public void addCountLocked(long count) {
1631 update(mCurrentCount + count, mTimeBase.isRunning());
Sudheer Shankac57729a2018-02-09 15:44:42 -08001632 }
1633
Mike Ma561a8d92018-03-20 18:24:05 -07001634 public void addCountLocked(long count, boolean isRunning) {
1635 update(mCurrentCount + count, isRunning);
1636 }
1637
1638 public void update(long count) {
1639 update(count, mTimeBase.isRunning());
1640 }
1641
1642 public void update(long count, boolean isRunning) {
1643 if (count < mCurrentCount) {
1644 mCurrentCount = 0;
Bookatz8c6f3c52017-05-24 12:00:17 -07001645 }
Mike Ma561a8d92018-03-20 18:24:05 -07001646 if (isRunning) {
1647 mCount += count - mCurrentCount;
1648 }
1649 mCurrentCount = count;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001650 }
1651
1652 /**
1653 * Clear state of this counter.
1654 */
Mike Ma561a8d92018-03-20 18:24:05 -07001655 public void reset(boolean detachIfReset) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001656 mCount = 0;
Sudheer Shankac57729a2018-02-09 15:44:42 -08001657 mLoadedCount = mUnpluggedCount = 0;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001658 if (detachIfReset) {
1659 detach();
1660 }
1661 }
1662
Mike Ma561a8d92018-03-20 18:24:05 -07001663 public void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001664 mTimeBase.remove(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001665 }
1666
Mike Ma561a8d92018-03-20 18:24:05 -07001667 public void writeSummaryFromParcelLocked(Parcel out) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001668 out.writeLong(mCount);
1669 }
1670
Mike Ma561a8d92018-03-20 18:24:05 -07001671 public void readSummaryFromParcelLocked(Parcel in) {
1672 mCount = mUnpluggedCount= mLoadedCount = in.readLong();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001673 }
1674 }
1675
Dianne Hackborn617f8772009-03-31 15:04:46 -07001676 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 * State for keeping track of timing information.
1678 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001679 public static abstract class Timer extends BatteryStats.Timer implements TimeBaseObs {
Joe Onoratoabded112016-02-08 16:49:39 -08001680 protected final Clocks mClocks;
1681 protected final int mType;
1682 protected final TimeBase mTimeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001683
Joe Onoratoabded112016-02-08 16:49:39 -08001684 protected int mCount;
1685 protected int mLoadedCount;
1686 protected int mLastCount;
1687 protected int mUnpluggedCount;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001688
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 // Times are in microseconds for better accuracy when dividing by the
1690 // lock count, and are in "battery realtime" units.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 /**
1693 * The total time we have accumulated since the start of the original
1694 * boot, to the last time something interesting happened in the
1695 * current run.
1696 */
Joe Onoratoabded112016-02-08 16:49:39 -08001697 protected long mTotalTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699 /**
1700 * The total time we loaded for the previous runs. Subtract this from
1701 * mTotalTime to find the time for the current run of the system.
1702 */
Joe Onoratoabded112016-02-08 16:49:39 -08001703 protected long mLoadedTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 /**
1706 * The run time of the last run of the system, as loaded from the
1707 * saved data.
1708 */
Joe Onoratoabded112016-02-08 16:49:39 -08001709 protected long mLastTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001711 /**
1712 * The value of mTotalTime when unplug() was last called. Subtract
1713 * this from mTotalTime to find the time since the last unplug from
1714 * power.
1715 */
Joe Onoratoabded112016-02-08 16:49:39 -08001716 protected long mUnpluggedTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001717
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001718 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07001719 * The total time this timer has been running until the latest mark has been set.
1720 * Subtract this from mTotalTime to get the time spent running since the mark was set.
1721 */
Joe Onoratoabded112016-02-08 16:49:39 -08001722 protected long mTimeBeforeMark;
Adam Lesinskie08af192015-03-25 16:42:59 -07001723
1724 /**
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001725 * Constructs from a parcel.
1726 * @param type
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001727 * @param timeBase
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001728 * @param in
1729 */
Joe Onoratoabded112016-02-08 16:49:39 -08001730 public Timer(Clocks clocks, int type, TimeBase timeBase, Parcel in) {
1731 mClocks = clocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 mType = type;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001733 mTimeBase = timeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 mCount = in.readInt();
1736 mLoadedCount = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001737 mLastCount = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 mUnpluggedCount = in.readInt();
1739 mTotalTime = in.readLong();
1740 mLoadedTime = in.readLong();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001741 mLastTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 mUnpluggedTime = in.readLong();
Adam Lesinskie08af192015-03-25 16:42:59 -07001743 mTimeBeforeMark = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001744 timeBase.add(this);
Dianne Hackborn29325132014-05-21 15:01:03 -07001745 if (DEBUG) Log.i(TAG, "**** READ TIMER #" + mType + ": mTotalTime=" + mTotalTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001746 }
1747
Joe Onoratoabded112016-02-08 16:49:39 -08001748 public Timer(Clocks clocks, int type, TimeBase timeBase) {
1749 mClocks = clocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 mType = type;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001751 mTimeBase = timeBase;
1752 timeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 }
Evan Millarc64edde2009-04-18 12:26:32 -07001754
1755 protected abstract long computeRunTimeLocked(long curBatteryRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001756
Evan Millarc64edde2009-04-18 12:26:32 -07001757 protected abstract int computeCurrentCountLocked();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001758
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001759 /**
1760 * Clear state of this timer. Returns true if the timer is inactive
1761 * so can be completely dropped.
1762 */
Joe Onoratoabded112016-02-08 16:49:39 -08001763 public boolean reset(boolean detachIfReset) {
Adam Lesinskie08af192015-03-25 16:42:59 -07001764 mTotalTime = mLoadedTime = mLastTime = mTimeBeforeMark = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001765 mCount = mLoadedCount = mLastCount = 0;
1766 if (detachIfReset) {
1767 detach();
1768 }
1769 return true;
1770 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001771
Joe Onoratoabded112016-02-08 16:49:39 -08001772 public void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001773 mTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001774 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001775
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001776 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
Dianne Hackborn29325132014-05-21 15:01:03 -07001777 if (DEBUG) Log.i(TAG, "**** WRITING TIMER #" + mType + ": mTotalTime="
1778 + computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)));
Adam Lesinski98f0d462016-04-19 16:46:20 -07001779 out.writeInt(computeCurrentCountLocked());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780 out.writeInt(mLoadedCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001781 out.writeInt(mUnpluggedCount);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001782 out.writeLong(computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783 out.writeLong(mLoadedTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001784 out.writeLong(mUnpluggedTime);
Adam Lesinskie08af192015-03-25 16:42:59 -07001785 out.writeLong(mTimeBeforeMark);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001786 }
1787
Adam Lesinskie08af192015-03-25 16:42:59 -07001788 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001789 public void onTimeStarted(long elapsedRealtime, long timeBaseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 if (DEBUG && mType < 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001791 Log.v(TAG, "unplug #" + mType + ": realtime=" + baseRealtime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792 + " old mUnpluggedTime=" + mUnpluggedTime
1793 + " old mUnpluggedCount=" + mUnpluggedCount);
1794 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001795 mUnpluggedTime = computeRunTimeLocked(baseRealtime);
Adam Lesinski98f0d462016-04-19 16:46:20 -07001796 mUnpluggedCount = computeCurrentCountLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797 if (DEBUG && mType < 0) {
1798 Log.v(TAG, "unplug #" + mType
1799 + ": new mUnpluggedTime=" + mUnpluggedTime
1800 + " new mUnpluggedCount=" + mUnpluggedCount);
1801 }
1802 }
1803
Adam Lesinskie08af192015-03-25 16:42:59 -07001804 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001805 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Evan Millarc64edde2009-04-18 12:26:32 -07001806 if (DEBUG && mType < 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001807 Log.v(TAG, "plug #" + mType + ": realtime=" + baseRealtime
Evan Millarc64edde2009-04-18 12:26:32 -07001808 + " old mTotalTime=" + mTotalTime);
1809 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001810 mTotalTime = computeRunTimeLocked(baseRealtime);
Evan Millarc64edde2009-04-18 12:26:32 -07001811 mCount = computeCurrentCountLocked();
1812 if (DEBUG && mType < 0) {
1813 Log.v(TAG, "plug #" + mType
1814 + ": new mTotalTime=" + mTotalTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 }
1816 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001818 /**
1819 * Writes a possibly null Timer to a Parcel.
1820 *
1821 * @param out the Parcel to be written to.
1822 * @param timer a Timer, or null.
1823 */
Mathew Inwoodc185f082018-08-20 14:28:54 +01001824 @UnsupportedAppUsage
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001825 public static void writeTimerToParcel(Parcel out, Timer timer, long elapsedRealtimeUs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 if (timer == null) {
1827 out.writeInt(0); // indicates null
1828 return;
1829 }
1830 out.writeInt(1); // indicates non-null
1831
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001832 timer.writeToParcel(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833 }
1834
1835 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01001836 @UnsupportedAppUsage
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001837 public long getTotalTimeLocked(long elapsedRealtimeUs, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001838 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1839 if (which == STATS_SINCE_UNPLUGGED) {
1840 val -= mUnpluggedTime;
1841 } else if (which != STATS_SINCE_CHARGED) {
1842 val -= mLoadedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 }
1844
1845 return val;
1846 }
1847
1848 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01001849 @UnsupportedAppUsage
Evan Millarc64edde2009-04-18 12:26:32 -07001850 public int getCountLocked(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001851 int val = computeCurrentCountLocked();
1852 if (which == STATS_SINCE_UNPLUGGED) {
1853 val -= mUnpluggedCount;
1854 } else if (which != STATS_SINCE_CHARGED) {
1855 val -= mLoadedCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 }
1857
1858 return val;
1859 }
1860
Adam Lesinskie08af192015-03-25 16:42:59 -07001861 @Override
1862 public long getTimeSinceMarkLocked(long elapsedRealtimeUs) {
1863 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1864 return val - mTimeBeforeMark;
1865 }
1866
1867 @Override
Dianne Hackborn627bba72009-03-24 22:32:56 -07001868 public void logState(Printer pw, String prefix) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07001869 pw.println(prefix + "mCount=" + mCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001870 + " mLoadedCount=" + mLoadedCount + " mLastCount=" + mLastCount
1871 + " mUnpluggedCount=" + mUnpluggedCount);
Dianne Hackborn627bba72009-03-24 22:32:56 -07001872 pw.println(prefix + "mTotalTime=" + mTotalTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001873 + " mLoadedTime=" + mLoadedTime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07001874 pw.println(prefix + "mLastTime=" + mLastTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 + " mUnpluggedTime=" + mUnpluggedTime);
Evan Millarc64edde2009-04-18 12:26:32 -07001876 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001877
1878
Joe Onoratoabded112016-02-08 16:49:39 -08001879 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001880 long runTime = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1881 out.writeLong(runTime);
Adam Lesinski98f0d462016-04-19 16:46:20 -07001882 out.writeInt(computeCurrentCountLocked());
Evan Millarc64edde2009-04-18 12:26:32 -07001883 }
1884
Joe Onoratoabded112016-02-08 16:49:39 -08001885 public void readSummaryFromParcelLocked(Parcel in) {
Evan Millarc64edde2009-04-18 12:26:32 -07001886 // Multiply by 1000 for backwards compatibility
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001887 mTotalTime = mLoadedTime = in.readLong();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001888 mLastTime = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001889 mUnpluggedTime = mTotalTime;
1890 mCount = mLoadedCount = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001891 mLastCount = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001892 mUnpluggedCount = mCount;
Adam Lesinskie08af192015-03-25 16:42:59 -07001893
1894 // When reading the summary, we set the mark to be the latest information.
1895 mTimeBeforeMark = mTotalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001896 }
1897 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001898
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001899 /**
1900 * A counter meant to accept monotonically increasing values to its {@link #update(long, int)}
1901 * method. The state of the timer according to its {@link TimeBase} will determine how much
1902 * of the value is recorded.
1903 *
1904 * If the value being recorded resets, {@link #endSample()} can be called in order to
1905 * account for the change. If the value passed in to {@link #update(long, int)} decreased
1906 * between calls, the {@link #endSample()} is automatically called and the new value is
1907 * expected to increase monotonically from that point on.
1908 */
Joe Onoratoabded112016-02-08 16:49:39 -08001909 public static class SamplingTimer extends Timer {
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001910
Evan Millarc64edde2009-04-18 12:26:32 -07001911 /**
1912 * The most recent reported count from /proc/wakelocks.
1913 */
1914 int mCurrentReportedCount;
1915
1916 /**
1917 * The reported count from /proc/wakelocks when unplug() was last
1918 * called.
1919 */
1920 int mUnpluggedReportedCount;
1921
1922 /**
1923 * The most recent reported total_time from /proc/wakelocks.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001924 */
Evan Millarc64edde2009-04-18 12:26:32 -07001925 long mCurrentReportedTotalTime;
1926
1927
1928 /**
1929 * The reported total_time from /proc/wakelocks when unplug() was last
1930 * called.
1931 */
1932 long mUnpluggedReportedTotalTime;
1933
1934 /**
1935 * Whether we are currently in a discharge cycle.
1936 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001937 boolean mTimeBaseRunning;
Evan Millarc64edde2009-04-18 12:26:32 -07001938
1939 /**
1940 * Whether we are currently recording reported values.
1941 */
1942 boolean mTrackingReportedValues;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001943
Evan Millarc64edde2009-04-18 12:26:32 -07001944 /*
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001945 * A sequence counter, incremented once for each update of the stats.
Evan Millarc64edde2009-04-18 12:26:32 -07001946 */
1947 int mUpdateVersion;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001948
Adam Lesinski98f0d462016-04-19 16:46:20 -07001949 @VisibleForTesting
1950 public SamplingTimer(Clocks clocks, TimeBase timeBase, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08001951 super(clocks, 0, timeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -07001952 mCurrentReportedCount = in.readInt();
1953 mUnpluggedReportedCount = in.readInt();
1954 mCurrentReportedTotalTime = in.readLong();
1955 mUnpluggedReportedTotalTime = in.readLong();
1956 mTrackingReportedValues = in.readInt() == 1;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001957 mTimeBaseRunning = timeBase.isRunning();
Evan Millarc64edde2009-04-18 12:26:32 -07001958 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001959
Adam Lesinski98f0d462016-04-19 16:46:20 -07001960 @VisibleForTesting
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001961 public SamplingTimer(Clocks clocks, TimeBase timeBase) {
Joe Onoratoabded112016-02-08 16:49:39 -08001962 super(clocks, 0, timeBase);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001963 mTrackingReportedValues = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001964 mTimeBaseRunning = timeBase.isRunning();
Evan Millarc64edde2009-04-18 12:26:32 -07001965 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001966
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001967 /**
1968 * Ends the current sample, allowing subsequent values to {@link #update(long, int)} to
1969 * be less than the values used for a previous invocation.
1970 */
1971 public void endSample() {
1972 mTotalTime = computeRunTimeLocked(0 /* unused by us */);
1973 mCount = computeCurrentCountLocked();
1974 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime = 0;
1975 mUnpluggedReportedCount = mCurrentReportedCount = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001976 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001977
Evan Millarc64edde2009-04-18 12:26:32 -07001978 public void setUpdateVersion(int version) {
1979 mUpdateVersion = version;
1980 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001981
Evan Millarc64edde2009-04-18 12:26:32 -07001982 public int getUpdateVersion() {
1983 return mUpdateVersion;
1984 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001985
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001986 /**
1987 * Updates the current recorded values. These are meant to be monotonically increasing
1988 * and cumulative. If you are dealing with deltas, use {@link #add(long, int)}.
1989 *
1990 * If the values being recorded have been reset, the monotonically increasing requirement
1991 * will be broken. In this case, {@link #endSample()} is automatically called and
1992 * the total value of totalTime and count are recorded, starting a new monotonically
1993 * increasing sample.
1994 *
1995 * @param totalTime total time of sample in microseconds.
1996 * @param count total number of times the event being sampled occurred.
1997 */
1998 public void update(long totalTime, int count) {
1999 if (mTimeBaseRunning && !mTrackingReportedValues) {
Evan Millarc64edde2009-04-18 12:26:32 -07002000 // Updating the reported value for the first time.
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002001 mUnpluggedReportedTotalTime = totalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07002002 mUnpluggedReportedCount = count;
Evan Millarc64edde2009-04-18 12:26:32 -07002003 }
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002004
2005 mTrackingReportedValues = true;
2006
2007 if (totalTime < mCurrentReportedTotalTime || count < mCurrentReportedCount) {
2008 endSample();
2009 }
2010
2011 mCurrentReportedTotalTime = totalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07002012 mCurrentReportedCount = count;
2013 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002014
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002015 /**
2016 * Adds deltaTime and deltaCount to the current sample.
2017 *
2018 * @param deltaTime additional time recorded since the last sampled event, in microseconds.
2019 * @param deltaCount additional number of times the event being sampled occurred.
2020 */
2021 public void add(long deltaTime, int deltaCount) {
2022 update(mCurrentReportedTotalTime + deltaTime, mCurrentReportedCount + deltaCount);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002023 }
2024
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002025 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002026 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
2027 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime);
Evan Millarc64edde2009-04-18 12:26:32 -07002028 if (mTrackingReportedValues) {
2029 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime;
2030 mUnpluggedReportedCount = mCurrentReportedCount;
2031 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002032 mTimeBaseRunning = true;
Evan Millarc64edde2009-04-18 12:26:32 -07002033 }
2034
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002035 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002036 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
2037 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
2038 mTimeBaseRunning = false;
Evan Millarc64edde2009-04-18 12:26:32 -07002039 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002040
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002041 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07002042 public void logState(Printer pw, String prefix) {
2043 super.logState(pw, prefix);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002044 pw.println(prefix + "mCurrentReportedCount=" + mCurrentReportedCount
Evan Millarc64edde2009-04-18 12:26:32 -07002045 + " mUnpluggedReportedCount=" + mUnpluggedReportedCount
2046 + " mCurrentReportedTotalTime=" + mCurrentReportedTotalTime
2047 + " mUnpluggedReportedTotalTime=" + mUnpluggedReportedTotalTime);
2048 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002049
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002050 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07002051 protected long computeRunTimeLocked(long curBatteryRealtime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002052 return mTotalTime + (mTimeBaseRunning && mTrackingReportedValues
Evan Millarc64edde2009-04-18 12:26:32 -07002053 ? mCurrentReportedTotalTime - mUnpluggedReportedTotalTime : 0);
2054 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002055
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002056 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07002057 protected int computeCurrentCountLocked() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002058 return mCount + (mTimeBaseRunning && mTrackingReportedValues
Evan Millarc64edde2009-04-18 12:26:32 -07002059 ? mCurrentReportedCount - mUnpluggedReportedCount : 0);
2060 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002061
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002062 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002063 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2064 super.writeToParcel(out, elapsedRealtimeUs);
Evan Millarc64edde2009-04-18 12:26:32 -07002065 out.writeInt(mCurrentReportedCount);
2066 out.writeInt(mUnpluggedReportedCount);
2067 out.writeLong(mCurrentReportedTotalTime);
2068 out.writeLong(mUnpluggedReportedTotalTime);
2069 out.writeInt(mTrackingReportedValues ? 1 : 0);
2070 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002071
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002072 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002073 public boolean reset(boolean detachIfReset) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002074 super.reset(detachIfReset);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002075 mTrackingReportedValues = false;
2076 mUnpluggedReportedTotalTime = 0;
2077 mUnpluggedReportedCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002078 return true;
2079 }
Evan Millarc64edde2009-04-18 12:26:32 -07002080 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002081
Evan Millarc64edde2009-04-18 12:26:32 -07002082 /**
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002083 * A timer that increments in batches. It does not run for durations, but just jumps
2084 * for a pre-determined amount.
2085 */
Joe Onoratoabded112016-02-08 16:49:39 -08002086 public static class BatchTimer extends Timer {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002087 final Uid mUid;
2088
2089 /**
2090 * The last time at which we updated the timer. This is in elapsed realtime microseconds.
2091 */
2092 long mLastAddedTime;
2093
2094 /**
2095 * The last duration that we added to the timer. This is in microseconds.
2096 */
2097 long mLastAddedDuration;
2098
2099 /**
2100 * Whether we are currently in a discharge cycle.
2101 */
2102 boolean mInDischarge;
2103
Joe Onoratoabded112016-02-08 16:49:39 -08002104 BatchTimer(Clocks clocks, Uid uid, int type, TimeBase timeBase, Parcel in) {
2105 super(clocks, type, timeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002106 mUid = uid;
2107 mLastAddedTime = in.readLong();
2108 mLastAddedDuration = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002109 mInDischarge = timeBase.isRunning();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002110 }
2111
Joe Onoratoabded112016-02-08 16:49:39 -08002112 BatchTimer(Clocks clocks, Uid uid, int type, TimeBase timeBase) {
2113 super(clocks, type, timeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002114 mUid = uid;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002115 mInDischarge = timeBase.isRunning();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002116 }
2117
2118 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002119 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2120 super.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002121 out.writeLong(mLastAddedTime);
2122 out.writeLong(mLastAddedDuration);
2123 }
2124
2125 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002126 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Joe Onoratoabded112016-02-08 16:49:39 -08002127 recomputeLastDuration(mClocks.elapsedRealtime() * 1000, false);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002128 mInDischarge = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002129 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002130 }
2131
2132 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002133 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002134 recomputeLastDuration(elapsedRealtime, false);
2135 mInDischarge = true;
2136 // If we are still within the last added duration, then re-added whatever remains.
2137 if (mLastAddedTime == elapsedRealtime) {
2138 mTotalTime += mLastAddedDuration;
2139 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002140 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002141 }
2142
2143 @Override
2144 public void logState(Printer pw, String prefix) {
2145 super.logState(pw, prefix);
2146 pw.println(prefix + "mLastAddedTime=" + mLastAddedTime
2147 + " mLastAddedDuration=" + mLastAddedDuration);
2148 }
2149
2150 private long computeOverage(long curTime) {
2151 if (mLastAddedTime > 0) {
2152 return mLastTime + mLastAddedDuration - curTime;
2153 }
2154 return 0;
2155 }
2156
2157 private void recomputeLastDuration(long curTime, boolean abort) {
2158 final long overage = computeOverage(curTime);
2159 if (overage > 0) {
2160 // Aborting before the duration ran out -- roll back the remaining
2161 // duration. Only do this if currently discharging; otherwise we didn't
2162 // actually add the time.
2163 if (mInDischarge) {
2164 mTotalTime -= overage;
2165 }
2166 if (abort) {
2167 mLastAddedTime = 0;
2168 } else {
2169 mLastAddedTime = curTime;
2170 mLastAddedDuration -= overage;
2171 }
2172 }
2173 }
2174
2175 public void addDuration(BatteryStatsImpl stats, long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08002176 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002177 recomputeLastDuration(now, true);
2178 mLastAddedTime = now;
2179 mLastAddedDuration = durationMillis * 1000;
2180 if (mInDischarge) {
2181 mTotalTime += mLastAddedDuration;
2182 mCount++;
2183 }
2184 }
2185
2186 public void abortLastDuration(BatteryStatsImpl stats) {
Joe Onoratoabded112016-02-08 16:49:39 -08002187 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002188 recomputeLastDuration(now, true);
2189 }
2190
2191 @Override
2192 protected int computeCurrentCountLocked() {
2193 return mCount;
2194 }
2195
2196 @Override
2197 protected long computeRunTimeLocked(long curBatteryRealtime) {
Joe Onoratoabded112016-02-08 16:49:39 -08002198 final long overage = computeOverage(mClocks.elapsedRealtime() * 1000);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002199 if (overage > 0) {
2200 return mTotalTime = overage;
2201 }
2202 return mTotalTime;
2203 }
2204
2205 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002206 public boolean reset(boolean detachIfReset) {
2207 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002208 recomputeLastDuration(now, true);
2209 boolean stillActive = mLastAddedTime == now;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002210 super.reset(!stillActive && detachIfReset);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002211 return !stillActive;
2212 }
2213 }
2214
Joe Onorato92fd23f2016-07-25 11:18:42 -07002215
2216 /**
2217 * A StopwatchTimer that also tracks the total and max individual
2218 * time spent active according to the given timebase. Whereas
2219 * StopwatchTimer apportions the time amongst all in the pool,
2220 * the total and max durations are not apportioned.
2221 */
2222 public static class DurationTimer extends StopwatchTimer {
2223 /**
2224 * The time (in ms) that the timer was last acquired or the time base
2225 * last (re-)started. Increasing the nesting depth does not reset this time.
2226 *
2227 * -1 if the timer is currently not running or the time base is not running.
2228 *
2229 * If written to a parcel, the start time is reset, as is mNesting in the base class
2230 * StopwatchTimer.
2231 */
2232 long mStartTimeMs = -1;
2233
2234 /**
Bookatz867c0d72017-03-07 18:23:42 -08002235 * The longest time period (in ms) that the timer has been active. Not pooled.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002236 */
2237 long mMaxDurationMs;
2238
2239 /**
Bookatz867c0d72017-03-07 18:23:42 -08002240 * The time (in ms) that that the timer has been active since most recent
2241 * stopRunningLocked() or reset(). Not pooled.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002242 */
2243 long mCurrentDurationMs;
2244
Bookatz867c0d72017-03-07 18:23:42 -08002245 /**
2246 * The total time (in ms) that that the timer has been active since most recent reset()
2247 * prior to the current startRunningLocked. This is the sum of all past currentDurations
2248 * (but not including the present currentDuration) since reset. Not pooled.
2249 */
2250 long mTotalDurationMs;
2251
Joe Onorato92fd23f2016-07-25 11:18:42 -07002252 public DurationTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2253 TimeBase timeBase, Parcel in) {
2254 super(clocks, uid, type, timerPool, timeBase, in);
2255 mMaxDurationMs = in.readLong();
Bookatz867c0d72017-03-07 18:23:42 -08002256 mTotalDurationMs = in.readLong();
jackqdyulei610a0a02017-08-09 14:02:01 -07002257 mCurrentDurationMs = in.readLong();
Joe Onorato92fd23f2016-07-25 11:18:42 -07002258 }
2259
2260 public DurationTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2261 TimeBase timeBase) {
2262 super(clocks, uid, type, timerPool, timeBase);
2263 }
2264
2265 @Override
2266 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2267 super.writeToParcel(out, elapsedRealtimeUs);
Kweku Adams47db5a82016-12-09 19:04:50 -08002268 out.writeLong(getMaxDurationMsLocked(elapsedRealtimeUs / 1000));
jackqdyulei610a0a02017-08-09 14:02:01 -07002269 out.writeLong(mTotalDurationMs);
2270 out.writeLong(getCurrentDurationMsLocked(elapsedRealtimeUs / 1000));
Joe Onorato92fd23f2016-07-25 11:18:42 -07002271 }
2272
2273 /**
2274 * Write the summary to the parcel.
2275 *
2276 * Since the time base is probably meaningless after we come back, reading
2277 * from this will have the effect of stopping the timer. So here all we write
Bookatz867c0d72017-03-07 18:23:42 -08002278 * is the max and total durations.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002279 */
2280 @Override
2281 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
2282 super.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
Kweku Adams47db5a82016-12-09 19:04:50 -08002283 out.writeLong(getMaxDurationMsLocked(elapsedRealtimeUs / 1000));
Bookatz867c0d72017-03-07 18:23:42 -08002284 out.writeLong(getTotalDurationMsLocked(elapsedRealtimeUs / 1000));
Joe Onorato92fd23f2016-07-25 11:18:42 -07002285 }
2286
2287 /**
2288 * Read the summary parcel.
2289 *
2290 * Has the side effect of stopping the timer.
2291 */
2292 @Override
2293 public void readSummaryFromParcelLocked(Parcel in) {
2294 super.readSummaryFromParcelLocked(in);
2295 mMaxDurationMs = in.readLong();
Bookatz867c0d72017-03-07 18:23:42 -08002296 mTotalDurationMs = in.readLong();
Joe Onorato92fd23f2016-07-25 11:18:42 -07002297 mStartTimeMs = -1;
2298 mCurrentDurationMs = 0;
2299 }
2300
2301 /**
2302 * The TimeBase time started (again).
2303 *
2304 * If the timer is also running, store the start time.
2305 */
2306 public void onTimeStarted(long elapsedRealtimeUs, long baseUptime, long baseRealtime) {
2307 super.onTimeStarted(elapsedRealtimeUs, baseUptime, baseRealtime);
2308 if (mNesting > 0) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002309 mStartTimeMs = baseRealtime / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002310 }
2311 }
2312
2313 /**
2314 * The TimeBase stopped running.
2315 *
2316 * If the timer is running, add the duration into mCurrentDurationMs.
2317 */
2318 @Override
Kweku Adams47db5a82016-12-09 19:04:50 -08002319 public void onTimeStopped(long elapsedRealtimeUs, long baseUptime, long baseRealtimeUs) {
2320 super.onTimeStopped(elapsedRealtimeUs, baseUptime, baseRealtimeUs);
Joe Onorato92fd23f2016-07-25 11:18:42 -07002321 if (mNesting > 0) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002322 // baseRealtimeUs has already been converted to the timebase's realtime.
2323 mCurrentDurationMs += (baseRealtimeUs / 1000) - mStartTimeMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002324 }
2325 mStartTimeMs = -1;
2326 }
2327
2328 @Override
2329 public void logState(Printer pw, String prefix) {
2330 super.logState(pw, prefix);
2331 }
2332
2333 @Override
2334 public void startRunningLocked(long elapsedRealtimeMs) {
2335 super.startRunningLocked(elapsedRealtimeMs);
2336 if (mNesting == 1 && mTimeBase.isRunning()) {
2337 // Just started
Kweku Adams47db5a82016-12-09 19:04:50 -08002338 mStartTimeMs = mTimeBase.getRealtime(elapsedRealtimeMs * 1000) / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002339 }
2340 }
2341
2342 /**
2343 * Decrements the mNesting ref-count on this timer.
2344 *
2345 * If it actually stopped (mNesting went to 0), then possibly update
2346 * mMaxDuration if the current duration was the longest ever.
2347 */
2348 @Override
2349 public void stopRunningLocked(long elapsedRealtimeMs) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002350 if (mNesting == 1) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07002351 final long durationMs = getCurrentDurationMsLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002352 mTotalDurationMs += durationMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002353 if (durationMs > mMaxDurationMs) {
2354 mMaxDurationMs = durationMs;
2355 }
2356 mStartTimeMs = -1;
2357 mCurrentDurationMs = 0;
2358 }
Kweku Adams47db5a82016-12-09 19:04:50 -08002359 // super method decrements mNesting, which getCurrentDurationMsLocked relies on,
2360 // so call super.stopRunningLocked after calling getCurrentDurationMsLocked.
2361 super.stopRunningLocked(elapsedRealtimeMs);
Joe Onorato92fd23f2016-07-25 11:18:42 -07002362 }
2363
2364 @Override
2365 public boolean reset(boolean detachIfReset) {
2366 boolean result = super.reset(detachIfReset);
2367 mMaxDurationMs = 0;
Bookatz867c0d72017-03-07 18:23:42 -08002368 mTotalDurationMs = 0;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002369 mCurrentDurationMs = 0;
2370 if (mNesting > 0) {
2371 mStartTimeMs = mTimeBase.getRealtime(mClocks.elapsedRealtime()*1000) / 1000;
2372 } else {
2373 mStartTimeMs = -1;
2374 }
2375 return result;
2376 }
2377
2378 /**
2379 * Returns the max duration that this timer has ever seen.
2380 *
2381 * Note that this time is NOT split between the timers in the timer group that
2382 * this timer is attached to. It is the TOTAL time.
2383 */
2384 @Override
2385 public long getMaxDurationMsLocked(long elapsedRealtimeMs) {
2386 if (mNesting > 0) {
2387 final long durationMs = getCurrentDurationMsLocked(elapsedRealtimeMs);
2388 if (durationMs > mMaxDurationMs) {
2389 return durationMs;
2390 }
2391 }
2392 return mMaxDurationMs;
2393 }
2394
2395 /**
2396 * Returns the time since the timer was started.
Bookatz867c0d72017-03-07 18:23:42 -08002397 * Returns 0 if the timer is not currently running.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002398 *
2399 * Note that this time is NOT split between the timers in the timer group that
2400 * this timer is attached to. It is the TOTAL time.
jackqdyulei610a0a02017-08-09 14:02:01 -07002401 *
2402 * Note that if running timer is parceled and unparceled, this method will return
2403 * current duration value at the time of parceling even though timer may not be
2404 * currently running.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002405 */
2406 @Override
2407 public long getCurrentDurationMsLocked(long elapsedRealtimeMs) {
2408 long durationMs = mCurrentDurationMs;
Kweku Adams47db5a82016-12-09 19:04:50 -08002409 if (mNesting > 0 && mTimeBase.isRunning()) {
2410 durationMs += (mTimeBase.getRealtime(elapsedRealtimeMs*1000)/1000)
2411 - mStartTimeMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002412 }
2413 return durationMs;
2414 }
Bookatz867c0d72017-03-07 18:23:42 -08002415
2416 /**
2417 * Returns the total cumulative duration that this timer has been on since reset().
2418 * If mTimerPool == null, this should be the same
2419 * as getTotalTimeLocked(elapsedRealtimeMs*1000, STATS_SINCE_CHARGED)/1000.
2420 *
2421 * Note that this time is NOT split between the timers in the timer group that
2422 * this timer is attached to. It is the TOTAL time. For this reason, if mTimerPool != null,
2423 * the result will not be equivalent to getTotalTimeLocked.
2424 */
2425 @Override
2426 public long getTotalDurationMsLocked(long elapsedRealtimeMs) {
2427 return mTotalDurationMs + getCurrentDurationMsLocked(elapsedRealtimeMs);
2428 }
Joe Onorato92fd23f2016-07-25 11:18:42 -07002429 }
2430
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002431 /**
Evan Millarc64edde2009-04-18 12:26:32 -07002432 * State for keeping track of timing information.
2433 */
Joe Onoratoabded112016-02-08 16:49:39 -08002434 public static class StopwatchTimer extends Timer {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002435 final Uid mUid;
Evan Millarc64edde2009-04-18 12:26:32 -07002436 final ArrayList<StopwatchTimer> mTimerPool;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002437
Evan Millarc64edde2009-04-18 12:26:32 -07002438 int mNesting;
2439
Evan Millarc64edde2009-04-18 12:26:32 -07002440 /**
2441 * The last time at which we updated the timer. If mNesting is > 0,
2442 * subtract this from the current battery time to find the amount of
2443 * time we have been running since we last computed an update.
2444 */
2445 long mUpdateTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002446
Evan Millarc64edde2009-04-18 12:26:32 -07002447 /**
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002448 * The total time at which the timer was acquired, to determine if it
Bookatzceebafe2017-04-06 11:59:13 -07002449 * was actually held for an interesting duration. If time base was not running when timer
2450 * was acquired, will be -1.
Evan Millarc64edde2009-04-18 12:26:32 -07002451 */
Bookatzceebafe2017-04-06 11:59:13 -07002452 long mAcquireTime = -1;
Evan Millarc64edde2009-04-18 12:26:32 -07002453
Amith Yamasanif37447b2009-10-08 18:28:01 -07002454 long mTimeout;
2455
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002456 /**
2457 * For partial wake locks, keep track of whether we are in the list
2458 * to consume CPU cycles.
2459 */
Sudheer Shanka38383232017-07-25 09:55:03 -07002460 @VisibleForTesting
2461 public boolean mInList;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002462
Joe Onoratoabded112016-02-08 16:49:39 -08002463 public StopwatchTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002464 TimeBase timeBase, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08002465 super(clocks, type, timeBase, in);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002466 mUid = uid;
Evan Millarc64edde2009-04-18 12:26:32 -07002467 mTimerPool = timerPool;
2468 mUpdateTime = in.readLong();
2469 }
2470
Joe Onoratoabded112016-02-08 16:49:39 -08002471 public StopwatchTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002472 TimeBase timeBase) {
Joe Onoratoabded112016-02-08 16:49:39 -08002473 super(clocks, type, timeBase);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002474 mUid = uid;
Evan Millarc64edde2009-04-18 12:26:32 -07002475 mTimerPool = timerPool;
2476 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002477
Joe Onoratoabded112016-02-08 16:49:39 -08002478 public void setTimeout(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07002479 mTimeout = timeout;
2480 }
2481
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002482 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2483 super.writeToParcel(out, elapsedRealtimeUs);
Evan Millarc64edde2009-04-18 12:26:32 -07002484 out.writeLong(mUpdateTime);
2485 }
2486
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002487 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Evan Millarc64edde2009-04-18 12:26:32 -07002488 if (mNesting > 0) {
2489 if (DEBUG && mType < 0) {
2490 Log.v(TAG, "old mUpdateTime=" + mUpdateTime);
2491 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002492 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
2493 mUpdateTime = baseRealtime;
Evan Millarc64edde2009-04-18 12:26:32 -07002494 if (DEBUG && mType < 0) {
2495 Log.v(TAG, "new mUpdateTime=" + mUpdateTime);
2496 }
2497 }
2498 }
2499
2500 public void logState(Printer pw, String prefix) {
2501 super.logState(pw, prefix);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07002502 pw.println(prefix + "mNesting=" + mNesting + " mUpdateTime=" + mUpdateTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002503 + " mAcquireTime=" + mAcquireTime);
2504 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002505
Joe Onoratoabded112016-02-08 16:49:39 -08002506 public void startRunningLocked(long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002507 if (mNesting++ == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002508 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002509 mUpdateTime = batteryRealtime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002510 if (mTimerPool != null) {
2511 // Accumulate time to all currently active timers before adding
2512 // this new one to the pool.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002513 refreshTimersLocked(batteryRealtime, mTimerPool, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514 // Add this timer to the active pool
2515 mTimerPool.add(this);
2516 }
Bookatzceebafe2017-04-06 11:59:13 -07002517 if (mTimeBase.isRunning()) {
2518 // Increment the count
2519 mCount++;
2520 mAcquireTime = mTotalTime;
2521 } else {
2522 mAcquireTime = -1;
2523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002524 if (DEBUG && mType < 0) {
2525 Log.v(TAG, "start #" + mType + ": mUpdateTime=" + mUpdateTime
2526 + " mTotalTime=" + mTotalTime + " mCount=" + mCount
2527 + " mAcquireTime=" + mAcquireTime);
2528 }
2529 }
2530 }
2531
Joe Onoratoabded112016-02-08 16:49:39 -08002532 public boolean isRunningLocked() {
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002533 return mNesting > 0;
2534 }
2535
Joe Onoratoabded112016-02-08 16:49:39 -08002536 public void stopRunningLocked(long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537 // Ignore attempt to stop a timer that isn't running
2538 if (mNesting == 0) {
2539 return;
2540 }
2541 if (--mNesting == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002542 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002543 if (mTimerPool != null) {
2544 // Accumulate time to all active counters, scaled by the total
2545 // active in the pool, before taking this one out of the pool.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002546 refreshTimersLocked(batteryRealtime, mTimerPool, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002547 // Remove this timer from the active pool
2548 mTimerPool.remove(this);
2549 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002550 mNesting = 1;
2551 mTotalTime = computeRunTimeLocked(batteryRealtime);
2552 mNesting = 0;
2553 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002555 if (DEBUG && mType < 0) {
2556 Log.v(TAG, "stop #" + mType + ": mUpdateTime=" + mUpdateTime
2557 + " mTotalTime=" + mTotalTime + " mCount=" + mCount
2558 + " mAcquireTime=" + mAcquireTime);
2559 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002560
Bookatzceebafe2017-04-06 11:59:13 -07002561 if (mAcquireTime >= 0 && mTotalTime == mAcquireTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562 // If there was no change in the time, then discard this
2563 // count. A somewhat cheezy strategy, but hey.
2564 mCount--;
2565 }
2566 }
2567 }
2568
Joe Onoratoabded112016-02-08 16:49:39 -08002569 public void stopAllRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07002570 if (mNesting > 0) {
2571 mNesting = 1;
2572 stopRunningLocked(elapsedRealtimeMs);
2573 }
2574 }
2575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576 // Update the total time for all other running Timers with the same type as this Timer
2577 // due to a change in timer count
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002578 private static long refreshTimersLocked(long batteryRealtime,
2579 final ArrayList<StopwatchTimer> pool, StopwatchTimer self) {
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002580 long selfTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002581 final int N = pool.size();
2582 for (int i=N-1; i>= 0; i--) {
Evan Millarc64edde2009-04-18 12:26:32 -07002583 final StopwatchTimer t = pool.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 long heldTime = batteryRealtime - t.mUpdateTime;
2585 if (heldTime > 0) {
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002586 final long myTime = heldTime / N;
2587 if (t == self) {
2588 selfTime = myTime;
2589 }
2590 t.mTotalTime += myTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 }
2592 t.mUpdateTime = batteryRealtime;
2593 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002594 return selfTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002595 }
2596
Evan Millarc64edde2009-04-18 12:26:32 -07002597 @Override
2598 protected long computeRunTimeLocked(long curBatteryRealtime) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07002599 if (mTimeout > 0 && curBatteryRealtime > mUpdateTime + mTimeout) {
2600 curBatteryRealtime = mUpdateTime + mTimeout;
2601 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002602 return mTotalTime + (mNesting > 0
2603 ? (curBatteryRealtime - mUpdateTime)
2604 / (mTimerPool != null ? mTimerPool.size() : 1)
2605 : 0);
2606 }
2607
Evan Millarc64edde2009-04-18 12:26:32 -07002608 @Override
2609 protected int computeCurrentCountLocked() {
2610 return mCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002611 }
2612
Adam Lesinskie08af192015-03-25 16:42:59 -07002613 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002614 public boolean reset(boolean detachIfReset) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002615 boolean canDetach = mNesting <= 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002616 super.reset(canDetach && detachIfReset);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002617 if (mNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08002618 mUpdateTime = mTimeBase.getRealtime(mClocks.elapsedRealtime() * 1000);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002619 }
Bookatzceebafe2017-04-06 11:59:13 -07002620 mAcquireTime = -1; // to ensure mCount isn't decreased to -1 if timer is stopped later.
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002621 return canDetach;
2622 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002623
Adam Lesinskie08af192015-03-25 16:42:59 -07002624 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01002625 @UnsupportedAppUsage
Joe Onoratoabded112016-02-08 16:49:39 -08002626 public void detach() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002627 super.detach();
2628 if (mTimerPool != null) {
2629 mTimerPool.remove(this);
2630 }
2631 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002632
Adam Lesinskie08af192015-03-25 16:42:59 -07002633 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002634 public void readSummaryFromParcelLocked(Parcel in) {
Evan Millarc64edde2009-04-18 12:26:32 -07002635 super.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002636 mNesting = 0;
2637 }
Adam Lesinskie08af192015-03-25 16:42:59 -07002638
2639 /**
2640 * Set the mark so that we can query later for the total time the timer has
2641 * accumulated since this point. The timer can be running or not.
2642 *
2643 * @param elapsedRealtimeMs the current elapsed realtime in milliseconds.
2644 */
2645 public void setMark(long elapsedRealtimeMs) {
2646 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
2647 if (mNesting > 0) {
2648 // We are running.
2649 if (mTimerPool != null) {
2650 refreshTimersLocked(batteryRealtime, mTimerPool, this);
2651 } else {
2652 mTotalTime += batteryRealtime - mUpdateTime;
2653 mUpdateTime = batteryRealtime;
2654 }
2655 }
2656 mTimeBeforeMark = mTotalTime;
2657 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002658 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002659
Bookatz867c0d72017-03-07 18:23:42 -08002660 /**
2661 * State for keeping track of two DurationTimers with different TimeBases, presumably where one
2662 * TimeBase is effectively a subset of the other.
2663 */
Bookatzaa4594a2017-03-24 12:39:56 -07002664 public static class DualTimer extends DurationTimer {
2665 // This class both is a DurationTimer and also holds a second DurationTimer.
2666 // The main timer (this) typically tracks the total time. It may be pooled (but since it's a
2667 // durationTimer, it also has the unpooled getTotalDurationMsLocked() for
2668 // STATS_SINCE_CHARGED).
Bookatz867c0d72017-03-07 18:23:42 -08002669 // mSubTimer typically tracks only part of the total time, such as background time, as
2670 // determined by a subTimeBase. It is NOT pooled.
2671 private final DurationTimer mSubTimer;
2672
2673 /**
Bookatzaa4594a2017-03-24 12:39:56 -07002674 * Creates a DualTimer to hold a main timer (this) and a mSubTimer.
2675 * The main timer (this) is based on the given timeBase and timerPool.
Bookatz867c0d72017-03-07 18:23:42 -08002676 * The mSubTimer is based on the given subTimeBase. The mSubTimer is not pooled, even if
Bookatzaa4594a2017-03-24 12:39:56 -07002677 * the main timer is.
Bookatz867c0d72017-03-07 18:23:42 -08002678 */
2679 public DualTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2680 TimeBase timeBase, TimeBase subTimeBase, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07002681 super(clocks, uid, type, timerPool, timeBase, in);
Bookatz867c0d72017-03-07 18:23:42 -08002682 mSubTimer = new DurationTimer(clocks, uid, type, null, subTimeBase, in);
2683 }
2684
2685 /**
Bookatzaa4594a2017-03-24 12:39:56 -07002686 * Creates a DualTimer to hold a main timer (this) and a mSubTimer.
2687 * The main timer (this) is based on the given timeBase and timerPool.
Bookatz867c0d72017-03-07 18:23:42 -08002688 * The mSubTimer is based on the given subTimeBase. The mSubTimer is not pooled, even if
Bookatzaa4594a2017-03-24 12:39:56 -07002689 * the main timer is.
Bookatz867c0d72017-03-07 18:23:42 -08002690 */
2691 public DualTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2692 TimeBase timeBase, TimeBase subTimeBase) {
Bookatzaa4594a2017-03-24 12:39:56 -07002693 super(clocks, uid, type, timerPool, timeBase);
Bookatz867c0d72017-03-07 18:23:42 -08002694 mSubTimer = new DurationTimer(clocks, uid, type, null, subTimeBase);
2695 }
2696
Bookatz867c0d72017-03-07 18:23:42 -08002697 /** Get the secondary timer. */
Bookatzaa4594a2017-03-24 12:39:56 -07002698 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002699 public DurationTimer getSubTimer() {
2700 return mSubTimer;
2701 }
2702
Bookatzaa4594a2017-03-24 12:39:56 -07002703 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002704 public void startRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002705 super.startRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002706 mSubTimer.startRunningLocked(elapsedRealtimeMs);
2707 }
2708
Bookatzaa4594a2017-03-24 12:39:56 -07002709 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002710 public void stopRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002711 super.stopRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002712 mSubTimer.stopRunningLocked(elapsedRealtimeMs);
2713 }
2714
Bookatzaa4594a2017-03-24 12:39:56 -07002715 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002716 public void stopAllRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002717 super.stopAllRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002718 mSubTimer.stopAllRunningLocked(elapsedRealtimeMs);
2719 }
2720
Bookatzaa4594a2017-03-24 12:39:56 -07002721 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002722 public boolean reset(boolean detachIfReset) {
2723 boolean active = false;
Bookatz4a3eda92017-04-10 13:10:46 -07002724 // Do not detach the subTimer explicitly since that'll be done by DualTimer.detach().
2725 active |= !mSubTimer.reset(false);
Bookatzaa4594a2017-03-24 12:39:56 -07002726 active |= !super.reset(detachIfReset);
Bookatz867c0d72017-03-07 18:23:42 -08002727 return !active;
2728 }
2729
Bookatzaa4594a2017-03-24 12:39:56 -07002730 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002731 public void detach() {
Bookatz867c0d72017-03-07 18:23:42 -08002732 mSubTimer.detach();
Bookatz4a3eda92017-04-10 13:10:46 -07002733 super.detach();
Bookatz867c0d72017-03-07 18:23:42 -08002734 }
2735
Bookatzaa4594a2017-03-24 12:39:56 -07002736 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002737 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002738 super.writeToParcel(out, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08002739 mSubTimer.writeToParcel(out, elapsedRealtimeUs);
2740 }
2741
Bookatzaa4594a2017-03-24 12:39:56 -07002742 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002743 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002744 super.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08002745 mSubTimer.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
2746 }
2747
Bookatzaa4594a2017-03-24 12:39:56 -07002748 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002749 public void readSummaryFromParcelLocked(Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07002750 super.readSummaryFromParcelLocked(in);
Bookatz867c0d72017-03-07 18:23:42 -08002751 mSubTimer.readSummaryFromParcelLocked(in);
2752 }
2753 }
2754
2755
Dianne Hackbornd953c532014-08-16 18:17:38 -07002756 public abstract class OverflowArrayMap<T> {
2757 private static final String OVERFLOW_NAME = "*overflow*";
2758
Dianne Hackborn657153b2016-07-29 14:54:14 -07002759 final int mUid;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002760 final ArrayMap<String, T> mMap = new ArrayMap<>();
2761 T mCurOverflow;
2762 ArrayMap<String, MutableInt> mActiveOverflow;
Dianne Hackborn657153b2016-07-29 14:54:14 -07002763 long mLastOverflowTime;
2764 long mLastOverflowFinishTime;
2765 long mLastClearTime;
2766 long mLastCleanupTime;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002767
Dianne Hackborn657153b2016-07-29 14:54:14 -07002768 public OverflowArrayMap(int uid) {
2769 mUid = uid;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002770 }
2771
2772 public ArrayMap<String, T> getMap() {
2773 return mMap;
2774 }
2775
2776 public void clear() {
Dianne Hackborn657153b2016-07-29 14:54:14 -07002777 mLastClearTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002778 mMap.clear();
2779 mCurOverflow = null;
2780 mActiveOverflow = null;
2781 }
2782
2783 public void add(String name, T obj) {
Joe Onorato388fc332016-04-12 17:06:47 -07002784 if (name == null) {
2785 name = "";
2786 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002787 mMap.put(name, obj);
2788 if (OVERFLOW_NAME.equals(name)) {
2789 mCurOverflow = obj;
2790 }
2791 }
2792
2793 public void cleanup() {
Dianne Hackborn657153b2016-07-29 14:54:14 -07002794 mLastCleanupTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002795 if (mActiveOverflow != null) {
2796 if (mActiveOverflow.size() == 0) {
2797 mActiveOverflow = null;
2798 }
2799 }
2800 if (mActiveOverflow == null) {
2801 // There is no currently active overflow, so we should no longer have
2802 // an overflow entry.
2803 if (mMap.containsKey(OVERFLOW_NAME)) {
2804 Slog.wtf(TAG, "Cleaning up with no active overflow, but have overflow entry "
2805 + mMap.get(OVERFLOW_NAME));
2806 mMap.remove(OVERFLOW_NAME);
2807 }
2808 mCurOverflow = null;
2809 } else {
2810 // There is currently active overflow, so we should still have an overflow entry.
2811 if (mCurOverflow == null || !mMap.containsKey(OVERFLOW_NAME)) {
2812 Slog.wtf(TAG, "Cleaning up with active overflow, but no overflow entry: cur="
2813 + mCurOverflow + " map=" + mMap.get(OVERFLOW_NAME));
2814 }
2815 }
2816 }
2817
2818 public T startObject(String name) {
Joe Onorato388fc332016-04-12 17:06:47 -07002819 if (name == null) {
2820 name = "";
2821 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002822 T obj = mMap.get(name);
2823 if (obj != null) {
2824 return obj;
2825 }
2826
2827 // No object exists for the given name, but do we currently have it
2828 // running as part of the overflow?
2829 if (mActiveOverflow != null) {
2830 MutableInt over = mActiveOverflow.get(name);
2831 if (over != null) {
2832 // We are already actively counting this name in the overflow object.
2833 obj = mCurOverflow;
2834 if (obj == null) {
2835 // Shouldn't be here, but we'll try to recover.
2836 Slog.wtf(TAG, "Have active overflow " + name + " but null overflow");
2837 obj = mCurOverflow = instantiateObject();
2838 mMap.put(OVERFLOW_NAME, obj);
2839 }
2840 over.value++;
2841 return obj;
2842 }
2843 }
2844
2845 // No object exists for given name nor in the overflow; we need to make
2846 // a new one.
2847 final int N = mMap.size();
2848 if (N >= MAX_WAKELOCKS_PER_UID) {
2849 // Went over the limit on number of objects to track; this one goes
2850 // in to the overflow.
2851 obj = mCurOverflow;
2852 if (obj == null) {
2853 // Need to start overflow now...
2854 obj = mCurOverflow = instantiateObject();
2855 mMap.put(OVERFLOW_NAME, obj);
2856 }
2857 if (mActiveOverflow == null) {
2858 mActiveOverflow = new ArrayMap<>();
2859 }
2860 mActiveOverflow.put(name, new MutableInt(1));
Dianne Hackborn657153b2016-07-29 14:54:14 -07002861 mLastOverflowTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002862 return obj;
2863 }
2864
2865 // Normal case where we just need to make a new object.
2866 obj = instantiateObject();
2867 mMap.put(name, obj);
2868 return obj;
2869 }
2870
2871 public T stopObject(String name) {
Joe Onorato388fc332016-04-12 17:06:47 -07002872 if (name == null) {
2873 name = "";
2874 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002875 T obj = mMap.get(name);
2876 if (obj != null) {
2877 return obj;
2878 }
2879
2880 // No object exists for the given name, but do we currently have it
2881 // running as part of the overflow?
2882 if (mActiveOverflow != null) {
2883 MutableInt over = mActiveOverflow.get(name);
2884 if (over != null) {
2885 // We are already actively counting this name in the overflow object.
2886 obj = mCurOverflow;
2887 if (obj != null) {
2888 over.value--;
2889 if (over.value <= 0) {
2890 mActiveOverflow.remove(name);
Dianne Hackborn657153b2016-07-29 14:54:14 -07002891 mLastOverflowFinishTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002892 }
2893 return obj;
2894 }
2895 }
2896 }
2897
2898 // Huh, they are stopping an active operation but we can't find one!
2899 // That's not good.
Dianne Hackborn657153b2016-07-29 14:54:14 -07002900 StringBuilder sb = new StringBuilder();
2901 sb.append("Unable to find object for ");
2902 sb.append(name);
2903 sb.append(" in uid ");
2904 sb.append(mUid);
2905 sb.append(" mapsize=");
2906 sb.append(mMap.size());
2907 sb.append(" activeoverflow=");
2908 sb.append(mActiveOverflow);
2909 sb.append(" curoverflow=");
2910 sb.append(mCurOverflow);
2911 long now = SystemClock.elapsedRealtime();
2912 if (mLastOverflowTime != 0) {
2913 sb.append(" lastOverflowTime=");
2914 TimeUtils.formatDuration(mLastOverflowTime-now, sb);
2915 }
2916 if (mLastOverflowFinishTime != 0) {
2917 sb.append(" lastOverflowFinishTime=");
2918 TimeUtils.formatDuration(mLastOverflowFinishTime-now, sb);
2919 }
2920 if (mLastClearTime != 0) {
2921 sb.append(" lastClearTime=");
2922 TimeUtils.formatDuration(mLastClearTime-now, sb);
2923 }
2924 if (mLastCleanupTime != 0) {
2925 sb.append(" lastCleanupTime=");
2926 TimeUtils.formatDuration(mLastCleanupTime-now, sb);
2927 }
2928 Slog.wtf(TAG, sb.toString());
Dianne Hackbornd953c532014-08-16 18:17:38 -07002929 return null;
2930 }
2931
2932 public abstract T instantiateObject();
2933 }
2934
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002935 public static class ControllerActivityCounterImpl extends ControllerActivityCounter
2936 implements Parcelable {
2937 private final LongSamplingCounter mIdleTimeMillis;
Siddharth Rayb50a6842017-12-14 15:15:28 -08002938 private final LongSamplingCounter mScanTimeMillis;
Siddharth Rayed754702018-02-15 12:44:37 -08002939 private final LongSamplingCounter mSleepTimeMillis;
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002940 private final LongSamplingCounter mRxTimeMillis;
2941 private final LongSamplingCounter[] mTxTimeMillis;
2942 private final LongSamplingCounter mPowerDrainMaMs;
2943
2944 public ControllerActivityCounterImpl(TimeBase timeBase, int numTxStates) {
2945 mIdleTimeMillis = new LongSamplingCounter(timeBase);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002946 mScanTimeMillis = new LongSamplingCounter(timeBase);
Siddharth Rayed754702018-02-15 12:44:37 -08002947 mSleepTimeMillis = new LongSamplingCounter(timeBase);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002948 mRxTimeMillis = new LongSamplingCounter(timeBase);
2949 mTxTimeMillis = new LongSamplingCounter[numTxStates];
2950 for (int i = 0; i < numTxStates; i++) {
2951 mTxTimeMillis[i] = new LongSamplingCounter(timeBase);
2952 }
2953 mPowerDrainMaMs = new LongSamplingCounter(timeBase);
2954 }
2955
2956 public ControllerActivityCounterImpl(TimeBase timeBase, int numTxStates, Parcel in) {
2957 mIdleTimeMillis = new LongSamplingCounter(timeBase, in);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002958 mScanTimeMillis = new LongSamplingCounter(timeBase, in);
Siddharth Rayed754702018-02-15 12:44:37 -08002959 mSleepTimeMillis = new LongSamplingCounter(timeBase, in);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002960 mRxTimeMillis = new LongSamplingCounter(timeBase, in);
2961 final int recordedTxStates = in.readInt();
2962 if (recordedTxStates != numTxStates) {
2963 throw new ParcelFormatException("inconsistent tx state lengths");
2964 }
2965
2966 mTxTimeMillis = new LongSamplingCounter[numTxStates];
2967 for (int i = 0; i < numTxStates; i++) {
2968 mTxTimeMillis[i] = new LongSamplingCounter(timeBase, in);
2969 }
2970 mPowerDrainMaMs = new LongSamplingCounter(timeBase, in);
2971 }
2972
2973 public void readSummaryFromParcel(Parcel in) {
2974 mIdleTimeMillis.readSummaryFromParcelLocked(in);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002975 mScanTimeMillis.readSummaryFromParcelLocked(in);
Siddharth Rayed754702018-02-15 12:44:37 -08002976 mSleepTimeMillis.readSummaryFromParcelLocked(in);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002977 mRxTimeMillis.readSummaryFromParcelLocked(in);
2978 final int recordedTxStates = in.readInt();
2979 if (recordedTxStates != mTxTimeMillis.length) {
2980 throw new ParcelFormatException("inconsistent tx state lengths");
2981 }
2982 for (LongSamplingCounter counter : mTxTimeMillis) {
2983 counter.readSummaryFromParcelLocked(in);
2984 }
2985 mPowerDrainMaMs.readSummaryFromParcelLocked(in);
2986 }
2987
2988 @Override
2989 public int describeContents() {
2990 return 0;
2991 }
2992
2993 public void writeSummaryToParcel(Parcel dest) {
2994 mIdleTimeMillis.writeSummaryFromParcelLocked(dest);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002995 mScanTimeMillis.writeSummaryFromParcelLocked(dest);
Siddharth Rayed754702018-02-15 12:44:37 -08002996 mSleepTimeMillis.writeSummaryFromParcelLocked(dest);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002997 mRxTimeMillis.writeSummaryFromParcelLocked(dest);
2998 dest.writeInt(mTxTimeMillis.length);
2999 for (LongSamplingCounter counter : mTxTimeMillis) {
3000 counter.writeSummaryFromParcelLocked(dest);
3001 }
3002 mPowerDrainMaMs.writeSummaryFromParcelLocked(dest);
3003 }
3004
3005 @Override
3006 public void writeToParcel(Parcel dest, int flags) {
3007 mIdleTimeMillis.writeToParcel(dest);
Siddharth Rayb50a6842017-12-14 15:15:28 -08003008 mScanTimeMillis.writeToParcel(dest);
Siddharth Rayed754702018-02-15 12:44:37 -08003009 mSleepTimeMillis.writeToParcel(dest);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08003010 mRxTimeMillis.writeToParcel(dest);
3011 dest.writeInt(mTxTimeMillis.length);
3012 for (LongSamplingCounter counter : mTxTimeMillis) {
3013 counter.writeToParcel(dest);
3014 }
3015 mPowerDrainMaMs.writeToParcel(dest);
3016 }
3017
3018 public void reset(boolean detachIfReset) {
3019 mIdleTimeMillis.reset(detachIfReset);
Siddharth Rayb50a6842017-12-14 15:15:28 -08003020 mScanTimeMillis.reset(detachIfReset);
Siddharth Rayed754702018-02-15 12:44:37 -08003021 mSleepTimeMillis.reset(detachIfReset);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08003022 mRxTimeMillis.reset(detachIfReset);
3023 for (LongSamplingCounter counter : mTxTimeMillis) {
3024 counter.reset(detachIfReset);
3025 }
3026 mPowerDrainMaMs.reset(detachIfReset);
3027 }
3028
3029 public void detach() {
3030 mIdleTimeMillis.detach();
Siddharth Rayb50a6842017-12-14 15:15:28 -08003031 mScanTimeMillis.detach();
Siddharth Rayed754702018-02-15 12:44:37 -08003032 mSleepTimeMillis.detach();
Adam Lesinski21f76aa2016-01-25 12:27:06 -08003033 mRxTimeMillis.detach();
3034 for (LongSamplingCounter counter : mTxTimeMillis) {
3035 counter.detach();
3036 }
3037 mPowerDrainMaMs.detach();
3038 }
3039
3040 /**
3041 * @return a LongSamplingCounter, measuring time spent in the idle state in
3042 * milliseconds.
3043 */
3044 @Override
3045 public LongSamplingCounter getIdleTimeCounter() {
Roshan Pius81643302016-03-14 16:45:55 -07003046 return mIdleTimeMillis;
Adam Lesinski21f76aa2016-01-25 12:27:06 -08003047 }
3048
3049 /**
Siddharth Rayb50a6842017-12-14 15:15:28 -08003050 * @return a LongSamplingCounter, measuring time spent in the scan state in
3051 * milliseconds.
3052 */
3053 @Override
3054 public LongSamplingCounter getScanTimeCounter() {
3055 return mScanTimeMillis;
3056 }
3057
3058 /**
Siddharth Rayed754702018-02-15 12:44:37 -08003059 * @return a LongSamplingCounter, measuring time spent in the sleep state in
3060 * milliseconds.
3061 */
3062 @Override
3063 public LongSamplingCounter getSleepTimeCounter() {
3064 return mSleepTimeMillis;
3065 }
3066
3067 /**
Adam Lesinski21f76aa2016-01-25 12:27:06 -08003068 * @return a LongSamplingCounter, measuring time spent in the receive state in
3069 * milliseconds.
3070 */
3071 @Override
3072 public LongSamplingCounter getRxTimeCounter() {
3073 return mRxTimeMillis;
3074 }
3075
3076 /**
3077 * @return a LongSamplingCounter[], measuring time spent in various transmit states in
3078 * milliseconds.
3079 */
3080 @Override
3081 public LongSamplingCounter[] getTxTimeCounters() {
3082 return mTxTimeMillis;
3083 }
3084
3085 /**
3086 * @return a LongSamplingCounter, measuring power use in milli-ampere milliseconds (mAmS).
3087 */
3088 @Override
3089 public LongSamplingCounter getPowerCounter() {
3090 return mPowerDrainMaMs;
3091 }
3092 }
3093
Bookatz50df7112017-08-04 14:53:26 -07003094 /** Get Resource Power Manager stats. Create a new one if it doesn't already exist. */
3095 public SamplingTimer getRpmTimerLocked(String name) {
3096 SamplingTimer rpmt = mRpmStats.get(name);
3097 if (rpmt == null) {
3098 rpmt = new SamplingTimer(mClocks, mOnBatteryTimeBase);
3099 mRpmStats.put(name, rpmt);
3100 }
3101 return rpmt;
3102 }
3103
3104 /** Get Screen-off Resource Power Manager stats. Create new one if it doesn't already exist. */
3105 public SamplingTimer getScreenOffRpmTimerLocked(String name) {
3106 SamplingTimer rpmt = mScreenOffRpmStats.get(name);
3107 if (rpmt == null) {
3108 rpmt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
3109 mScreenOffRpmStats.put(name, rpmt);
3110 }
3111 return rpmt;
3112 }
3113
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003114 /*
3115 * Get the wakeup reason counter, and create a new one if one
3116 * doesn't already exist.
3117 */
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07003118 public SamplingTimer getWakeupReasonTimerLocked(String name) {
3119 SamplingTimer timer = mWakeupReasonStats.get(name);
3120 if (timer == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07003121 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07003122 mWakeupReasonStats.put(name, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003123 }
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07003124 return timer;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003125 }
3126
Evan Millarc64edde2009-04-18 12:26:32 -07003127 /*
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003128 * Get the KernelWakelockTimer associated with name, and create a new one if one
Evan Millarc64edde2009-04-18 12:26:32 -07003129 * doesn't already exist.
3130 */
3131 public SamplingTimer getKernelWakelockTimerLocked(String name) {
3132 SamplingTimer kwlt = mKernelWakelockStats.get(name);
3133 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07003134 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Evan Millarc64edde2009-04-18 12:26:32 -07003135 mKernelWakelockStats.put(name, kwlt);
3136 }
3137 return kwlt;
3138 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07003139
James Carr3a226052016-07-01 14:49:52 -07003140 public SamplingTimer getKernelMemoryTimerLocked(long bucket) {
3141 SamplingTimer kmt = mKernelMemoryStats.get(bucket);
3142 if (kmt == null) {
3143 kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase);
3144 mKernelMemoryStats.put(bucket, kmt);
3145 }
3146 return kmt;
3147 }
3148
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003149 private int writeHistoryTag(HistoryTag tag) {
3150 Integer idxObj = mHistoryTagPool.get(tag);
3151 int idx;
3152 if (idxObj != null) {
3153 idx = idxObj;
3154 } else {
3155 idx = mNextHistoryTagIdx;
3156 HistoryTag key = new HistoryTag();
3157 key.setTo(tag);
3158 tag.poolIdx = idx;
3159 mHistoryTagPool.put(key, idx);
3160 mNextHistoryTagIdx++;
3161 mNumHistoryTagChars += key.string.length() + 1;
3162 }
3163 return idx;
3164 }
3165
3166 private void readHistoryTag(int index, HistoryTag tag) {
3167 tag.string = mReadHistoryStrings[index];
3168 tag.uid = mReadHistoryUids[index];
3169 tag.poolIdx = index;
3170 }
3171
Adam Lesinski926969b2016-04-28 17:31:12 -07003172 /*
3173 The history delta format uses flags to denote further data in subsequent ints in the parcel.
3174
3175 There is always the first token, which may contain the delta time, or an indicator of
3176 the length of the time (int or long) following this token.
3177
3178 First token: always present,
3179 31 23 15 7 0
3180 â–ˆ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â–ˆ
3181
3182 T: the delta time if it is <= 0x7fffd. Otherwise 0x7fffe indicates an int immediately
3183 follows containing the time, and 0x7ffff indicates a long immediately follows with the
3184 delta time.
3185 A: battery level changed and an int follows with battery data.
3186 B: state changed and an int follows with state change data.
3187 C: state2 has changed and an int follows with state2 change data.
3188 D: wakelock/wakereason has changed and an wakelock/wakereason struct follows.
3189 E: event data has changed and an event struct follows.
3190 F: battery charge in coulombs has changed and an int with the charge follows.
3191 G: state flag denoting that the mobile radio was active.
3192 H: state flag denoting that the wifi radio was active.
3193 I: state flag denoting that a wifi scan occurred.
3194 J: state flag denoting that a wifi full lock was held.
3195 K: state flag denoting that the gps was on.
3196 L: state flag denoting that a wakelock was held.
3197 M: state flag denoting that the cpu was running.
3198
3199 Time int/long: if T in the first token is 0x7ffff or 0x7fffe, then an int or long follows
3200 with the time delta.
3201
3202 Battery level int: if A in the first token is set,
3203 31 23 15 7 0
3204 â–ˆ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â–ˆ
3205
3206 D: indicates that extra history details follow.
3207 V: the battery voltage.
3208 T: the battery temperature.
3209 L: the battery level (out of 100).
3210
3211 State change int: if B in the first token is set,
3212 31 23 15 7 0
3213 â–ˆS|S|S|H|H|H|P|Pâ–ˆF|E|D|C|B| | |Aâ–ˆ | | | | | | | â–ˆ | | | | | | | â–ˆ
3214
3215 A: wifi multicast was on.
3216 B: battery was plugged in.
3217 C: screen was on.
3218 D: phone was scanning for signal.
3219 E: audio was on.
3220 F: a sensor was active.
3221
3222 State2 change int: if C in the first token is set,
3223 31 23 15 7 0
3224 â–ˆM|L|K|J|I|H|H|Gâ–ˆF|E|D|C| | | | â–ˆ | | | | | | | â–ˆ |B|B|B|A|A|A|Aâ–ˆ
3225
3226 A: 4 bits indicating the wifi supplicant state: {@link BatteryStats#WIFI_SUPPL_STATE_NAMES}.
3227 B: 3 bits indicating the wifi signal strength: 0, 1, 2, 3, 4.
3228 C: a bluetooth scan was active.
3229 D: the camera was active.
3230 E: bluetooth was on.
3231 F: a phone call was active.
3232 G: the device was charging.
3233 H: 2 bits indicating the device-idle (doze) state: off, light, full
3234 I: the flashlight was on.
3235 J: wifi was on.
3236 K: wifi was running.
3237 L: video was playing.
3238 M: power save mode was on.
3239
3240 Wakelock/wakereason struct: if D in the first token is set,
3241 TODO(adamlesinski): describe wakelock/wakereason struct.
3242
3243 Event struct: if E in the first token is set,
3244 TODO(adamlesinski): describe the event struct.
3245
3246 History step details struct: if D in the battery level int is set,
3247 TODO(adamlesinski): describe the history step details struct.
3248
3249 Battery charge int: if F in the first token is set, an int representing the battery charge
3250 in coulombs follows.
3251 */
3252
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003253 // Part of initial delta int that specifies the time delta.
Dianne Hackborne13c4c02014-02-11 17:18:35 -08003254 static final int DELTA_TIME_MASK = 0x7ffff;
3255 static final int DELTA_TIME_LONG = 0x7ffff; // The delta is a following long
3256 static final int DELTA_TIME_INT = 0x7fffe; // The delta is a following int
3257 static final int DELTA_TIME_ABS = 0x7fffd; // Following is an entire abs update.
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003258 // Flag in delta int: a new battery level int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003259 static final int DELTA_BATTERY_LEVEL_FLAG = 0x00080000;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003260 // Flag in delta int: a new full state and battery status int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003261 static final int DELTA_STATE_FLAG = 0x00100000;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08003262 // Flag in delta int: a new full state2 int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003263 static final int DELTA_STATE2_FLAG = 0x00200000;
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003264 // Flag in delta int: contains a wakelock or wakeReason tag.
Adam Lesinski926969b2016-04-28 17:31:12 -07003265 static final int DELTA_WAKELOCK_FLAG = 0x00400000;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003266 // Flag in delta int: contains an event description.
Adam Lesinski926969b2016-04-28 17:31:12 -07003267 static final int DELTA_EVENT_FLAG = 0x00800000;
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003268 // Flag in delta int: contains the battery charge count in uAh.
3269 static final int DELTA_BATTERY_CHARGE_FLAG = 0x01000000;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003270 // These upper bits are the frequently changing state bits.
Adam Lesinski926969b2016-04-28 17:31:12 -07003271 static final int DELTA_STATE_MASK = 0xfe000000;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003272
3273 // These are the pieces of battery state that are packed in to the upper bits of
3274 // the state int that have been packed in to the first delta int. They must fit
Adam Lesinski926969b2016-04-28 17:31:12 -07003275 // in STATE_BATTERY_MASK.
3276 static final int STATE_BATTERY_MASK = 0xff000000;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003277 static final int STATE_BATTERY_STATUS_MASK = 0x00000007;
3278 static final int STATE_BATTERY_STATUS_SHIFT = 29;
3279 static final int STATE_BATTERY_HEALTH_MASK = 0x00000007;
3280 static final int STATE_BATTERY_HEALTH_SHIFT = 26;
3281 static final int STATE_BATTERY_PLUG_MASK = 0x00000003;
3282 static final int STATE_BATTERY_PLUG_SHIFT = 24;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003283
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003284 // We use the low bit of the battery state int to indicate that we have full details
3285 // from a battery level change.
3286 static final int BATTERY_DELTA_LEVEL_FLAG = 0x00000001;
3287
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003288 public void writeHistoryDelta(Parcel dest, HistoryItem cur, HistoryItem last) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003289 if (last == null || cur.cmd != HistoryItem.CMD_UPDATE) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003290 dest.writeInt(DELTA_TIME_ABS);
3291 cur.writeToParcel(dest, 0);
3292 return;
3293 }
3294
3295 final long deltaTime = cur.time - last.time;
3296 final int lastBatteryLevelInt = buildBatteryLevelInt(last);
3297 final int lastStateInt = buildStateInt(last);
3298
3299 int deltaTimeToken;
3300 if (deltaTime < 0 || deltaTime > Integer.MAX_VALUE) {
3301 deltaTimeToken = DELTA_TIME_LONG;
3302 } else if (deltaTime >= DELTA_TIME_ABS) {
3303 deltaTimeToken = DELTA_TIME_INT;
3304 } else {
3305 deltaTimeToken = (int)deltaTime;
3306 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003307 int firstToken = deltaTimeToken | (cur.states&DELTA_STATE_MASK);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003308 final int includeStepDetails = mLastHistoryStepLevel > cur.batteryLevel
3309 ? BATTERY_DELTA_LEVEL_FLAG : 0;
3310 final boolean computeStepDetails = includeStepDetails != 0
3311 || mLastHistoryStepDetails == null;
3312 final int batteryLevelInt = buildBatteryLevelInt(cur) | includeStepDetails;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003313 final boolean batteryLevelIntChanged = batteryLevelInt != lastBatteryLevelInt;
3314 if (batteryLevelIntChanged) {
3315 firstToken |= DELTA_BATTERY_LEVEL_FLAG;
3316 }
3317 final int stateInt = buildStateInt(cur);
3318 final boolean stateIntChanged = stateInt != lastStateInt;
3319 if (stateIntChanged) {
3320 firstToken |= DELTA_STATE_FLAG;
3321 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003322 final boolean state2IntChanged = cur.states2 != last.states2;
3323 if (state2IntChanged) {
3324 firstToken |= DELTA_STATE2_FLAG;
3325 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003326 if (cur.wakelockTag != null || cur.wakeReasonTag != null) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003327 firstToken |= DELTA_WAKELOCK_FLAG;
3328 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003329 if (cur.eventCode != HistoryItem.EVENT_NONE) {
3330 firstToken |= DELTA_EVENT_FLAG;
3331 }
Adam Lesinski926969b2016-04-28 17:31:12 -07003332
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003333 final boolean batteryChargeChanged = cur.batteryChargeUAh != last.batteryChargeUAh;
3334 if (batteryChargeChanged) {
3335 firstToken |= DELTA_BATTERY_CHARGE_FLAG;
Adam Lesinski926969b2016-04-28 17:31:12 -07003336 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003337 dest.writeInt(firstToken);
3338 if (DEBUG) Slog.i(TAG, "WRITE DELTA: firstToken=0x" + Integer.toHexString(firstToken)
3339 + " deltaTime=" + deltaTime);
3340
3341 if (deltaTimeToken >= DELTA_TIME_INT) {
3342 if (deltaTimeToken == DELTA_TIME_INT) {
3343 if (DEBUG) Slog.i(TAG, "WRITE DELTA: int deltaTime=" + (int)deltaTime);
3344 dest.writeInt((int)deltaTime);
3345 } else {
3346 if (DEBUG) Slog.i(TAG, "WRITE DELTA: long deltaTime=" + deltaTime);
3347 dest.writeLong(deltaTime);
3348 }
3349 }
3350 if (batteryLevelIntChanged) {
3351 dest.writeInt(batteryLevelInt);
3352 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryToken=0x"
3353 + Integer.toHexString(batteryLevelInt)
3354 + " batteryLevel=" + cur.batteryLevel
3355 + " batteryTemp=" + cur.batteryTemperature
3356 + " batteryVolt=" + (int)cur.batteryVoltage);
3357 }
3358 if (stateIntChanged) {
3359 dest.writeInt(stateInt);
3360 if (DEBUG) Slog.i(TAG, "WRITE DELTA: stateToken=0x"
3361 + Integer.toHexString(stateInt)
3362 + " batteryStatus=" + cur.batteryStatus
3363 + " batteryHealth=" + cur.batteryHealth
3364 + " batteryPlugType=" + cur.batteryPlugType
3365 + " states=0x" + Integer.toHexString(cur.states));
3366 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003367 if (state2IntChanged) {
3368 dest.writeInt(cur.states2);
3369 if (DEBUG) Slog.i(TAG, "WRITE DELTA: states2=0x"
3370 + Integer.toHexString(cur.states2));
3371 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003372 if (cur.wakelockTag != null || cur.wakeReasonTag != null) {
3373 int wakeLockIndex;
3374 int wakeReasonIndex;
3375 if (cur.wakelockTag != null) {
3376 wakeLockIndex = writeHistoryTag(cur.wakelockTag);
3377 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx
3378 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string);
3379 } else {
3380 wakeLockIndex = 0xffff;
3381 }
3382 if (cur.wakeReasonTag != null) {
3383 wakeReasonIndex = writeHistoryTag(cur.wakeReasonTag);
3384 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx
3385 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string);
3386 } else {
3387 wakeReasonIndex = 0xffff;
3388 }
3389 dest.writeInt((wakeReasonIndex<<16) | wakeLockIndex);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003390 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003391 if (cur.eventCode != HistoryItem.EVENT_NONE) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003392 int index = writeHistoryTag(cur.eventTag);
3393 int codeAndIndex = (cur.eventCode&0xffff) | (index<<16);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003394 dest.writeInt(codeAndIndex);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003395 if (DEBUG) Slog.i(TAG, "WRITE DELTA: event=" + cur.eventCode + " tag=#"
3396 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":"
3397 + cur.eventTag.string);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003398 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003399 if (computeStepDetails) {
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07003400 if (mPlatformIdleStateCallback != null) {
3401 mCurHistoryStepDetails.statPlatformIdleState =
3402 mPlatformIdleStateCallback.getPlatformLowPowerStats();
3403 if (DEBUG) Slog.i(TAG, "WRITE PlatformIdleState:" +
3404 mCurHistoryStepDetails.statPlatformIdleState);
Ahmed ElArabawyd8b44112017-05-23 21:25:02 +00003405
3406 mCurHistoryStepDetails.statSubsystemPowerState =
3407 mPlatformIdleStateCallback.getSubsystemLowPowerStats();
3408 if (DEBUG) Slog.i(TAG, "WRITE SubsystemPowerState:" +
3409 mCurHistoryStepDetails.statSubsystemPowerState);
3410
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07003411 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003412 computeHistoryStepDetails(mCurHistoryStepDetails, mLastHistoryStepDetails);
3413 if (includeStepDetails != 0) {
3414 mCurHistoryStepDetails.writeToParcel(dest);
3415 }
3416 cur.stepDetails = mCurHistoryStepDetails;
3417 mLastHistoryStepDetails = mCurHistoryStepDetails;
3418 } else {
3419 cur.stepDetails = null;
3420 }
3421 if (mLastHistoryStepLevel < cur.batteryLevel) {
3422 mLastHistoryStepDetails = null;
3423 }
3424 mLastHistoryStepLevel = cur.batteryLevel;
Adam Lesinski926969b2016-04-28 17:31:12 -07003425
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003426 if (batteryChargeChanged) {
3427 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryChargeUAh=" + cur.batteryChargeUAh);
3428 dest.writeInt(cur.batteryChargeUAh);
Adam Lesinski926969b2016-04-28 17:31:12 -07003429 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003430 }
3431
3432 private int buildBatteryLevelInt(HistoryItem h) {
3433 return ((((int)h.batteryLevel)<<25)&0xfe000000)
Adam Lesinski3944c812015-11-13 15:54:59 -08003434 | ((((int)h.batteryTemperature)<<15)&0x01ff8000)
3435 | ((((int)h.batteryVoltage)<<1)&0x00007ffe);
3436 }
3437
3438 private void readBatteryLevelInt(int batteryLevelInt, HistoryItem out) {
3439 out.batteryLevel = (byte)((batteryLevelInt & 0xfe000000) >>> 25);
3440 out.batteryTemperature = (short)((batteryLevelInt & 0x01ff8000) >>> 15);
3441 out.batteryVoltage = (char)((batteryLevelInt & 0x00007ffe) >>> 1);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003442 }
3443
3444 private int buildStateInt(HistoryItem h) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003445 int plugType = 0;
3446 if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_AC) != 0) {
3447 plugType = 1;
3448 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_USB) != 0) {
3449 plugType = 2;
3450 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_WIRELESS) != 0) {
3451 plugType = 3;
3452 }
3453 return ((h.batteryStatus&STATE_BATTERY_STATUS_MASK)<<STATE_BATTERY_STATUS_SHIFT)
3454 | ((h.batteryHealth&STATE_BATTERY_HEALTH_MASK)<<STATE_BATTERY_HEALTH_SHIFT)
3455 | ((plugType&STATE_BATTERY_PLUG_MASK)<<STATE_BATTERY_PLUG_SHIFT)
Adam Lesinski926969b2016-04-28 17:31:12 -07003456 | (h.states&(~STATE_BATTERY_MASK));
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003457 }
3458
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003459 private void computeHistoryStepDetails(final HistoryStepDetails out,
3460 final HistoryStepDetails last) {
3461 final HistoryStepDetails tmp = last != null ? mTmpHistoryStepDetails : out;
3462
3463 // Perform a CPU update right after we do this collection, so we have started
3464 // collecting good data for the next step.
3465 requestImmediateCpuUpdate();
3466
3467 if (last == null) {
3468 // We are not generating a delta, so all we need to do is reset the stats
3469 // we will later be doing a delta from.
3470 final int NU = mUidStats.size();
3471 for (int i=0; i<NU; i++) {
3472 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
3473 uid.mLastStepUserTime = uid.mCurStepUserTime;
3474 uid.mLastStepSystemTime = uid.mCurStepSystemTime;
3475 }
3476 mLastStepCpuUserTime = mCurStepCpuUserTime;
3477 mLastStepCpuSystemTime = mCurStepCpuSystemTime;
3478 mLastStepStatUserTime = mCurStepStatUserTime;
3479 mLastStepStatSystemTime = mCurStepStatSystemTime;
3480 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime;
3481 mLastStepStatIrqTime = mCurStepStatIrqTime;
3482 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime;
3483 mLastStepStatIdleTime = mCurStepStatIdleTime;
3484 tmp.clear();
3485 return;
3486 }
3487 if (DEBUG) {
3488 Slog.d(TAG, "Step stats last: user=" + mLastStepCpuUserTime + " sys="
3489 + mLastStepStatSystemTime + " io=" + mLastStepStatIOWaitTime
3490 + " irq=" + mLastStepStatIrqTime + " sirq="
3491 + mLastStepStatSoftIrqTime + " idle=" + mLastStepStatIdleTime);
3492 Slog.d(TAG, "Step stats cur: user=" + mCurStepCpuUserTime + " sys="
3493 + mCurStepStatSystemTime + " io=" + mCurStepStatIOWaitTime
3494 + " irq=" + mCurStepStatIrqTime + " sirq="
3495 + mCurStepStatSoftIrqTime + " idle=" + mCurStepStatIdleTime);
3496 }
3497 out.userTime = (int)(mCurStepCpuUserTime - mLastStepCpuUserTime);
3498 out.systemTime = (int)(mCurStepCpuSystemTime - mLastStepCpuSystemTime);
3499 out.statUserTime = (int)(mCurStepStatUserTime - mLastStepStatUserTime);
3500 out.statSystemTime = (int)(mCurStepStatSystemTime - mLastStepStatSystemTime);
3501 out.statIOWaitTime = (int)(mCurStepStatIOWaitTime - mLastStepStatIOWaitTime);
3502 out.statIrqTime = (int)(mCurStepStatIrqTime - mLastStepStatIrqTime);
3503 out.statSoftIrqTime = (int)(mCurStepStatSoftIrqTime - mLastStepStatSoftIrqTime);
3504 out.statIdlTime = (int)(mCurStepStatIdleTime - mLastStepStatIdleTime);
3505 out.appCpuUid1 = out.appCpuUid2 = out.appCpuUid3 = -1;
3506 out.appCpuUTime1 = out.appCpuUTime2 = out.appCpuUTime3 = 0;
3507 out.appCpuSTime1 = out.appCpuSTime2 = out.appCpuSTime3 = 0;
3508 final int NU = mUidStats.size();
3509 for (int i=0; i<NU; i++) {
3510 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
3511 final int totalUTime = (int)(uid.mCurStepUserTime - uid.mLastStepUserTime);
3512 final int totalSTime = (int)(uid.mCurStepSystemTime - uid.mLastStepSystemTime);
3513 final int totalTime = totalUTime + totalSTime;
3514 uid.mLastStepUserTime = uid.mCurStepUserTime;
3515 uid.mLastStepSystemTime = uid.mCurStepSystemTime;
3516 if (totalTime <= (out.appCpuUTime3+out.appCpuSTime3)) {
3517 continue;
3518 }
3519 if (totalTime <= (out.appCpuUTime2+out.appCpuSTime2)) {
3520 out.appCpuUid3 = uid.mUid;
3521 out.appCpuUTime3 = totalUTime;
3522 out.appCpuSTime3 = totalSTime;
3523 } else {
3524 out.appCpuUid3 = out.appCpuUid2;
3525 out.appCpuUTime3 = out.appCpuUTime2;
3526 out.appCpuSTime3 = out.appCpuSTime2;
3527 if (totalTime <= (out.appCpuUTime1+out.appCpuSTime1)) {
3528 out.appCpuUid2 = uid.mUid;
3529 out.appCpuUTime2 = totalUTime;
3530 out.appCpuSTime2 = totalSTime;
3531 } else {
3532 out.appCpuUid2 = out.appCpuUid1;
3533 out.appCpuUTime2 = out.appCpuUTime1;
3534 out.appCpuSTime2 = out.appCpuSTime1;
3535 out.appCpuUid1 = uid.mUid;
3536 out.appCpuUTime1 = totalUTime;
3537 out.appCpuSTime1 = totalSTime;
3538 }
3539 }
3540 }
3541 mLastStepCpuUserTime = mCurStepCpuUserTime;
3542 mLastStepCpuSystemTime = mCurStepCpuSystemTime;
3543 mLastStepStatUserTime = mCurStepStatUserTime;
3544 mLastStepStatSystemTime = mCurStepStatSystemTime;
3545 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime;
3546 mLastStepStatIrqTime = mCurStepStatIrqTime;
3547 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime;
3548 mLastStepStatIdleTime = mCurStepStatIdleTime;
3549 }
3550
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003551 public void readHistoryDelta(Parcel src, HistoryItem cur) {
3552 int firstToken = src.readInt();
3553 int deltaTimeToken = firstToken&DELTA_TIME_MASK;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003554 cur.cmd = HistoryItem.CMD_UPDATE;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003555 cur.numReadInts = 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003556 if (DEBUG) Slog.i(TAG, "READ DELTA: firstToken=0x" + Integer.toHexString(firstToken)
3557 + " deltaTimeToken=" + deltaTimeToken);
3558
3559 if (deltaTimeToken < DELTA_TIME_ABS) {
3560 cur.time += deltaTimeToken;
3561 } else if (deltaTimeToken == DELTA_TIME_ABS) {
3562 cur.time = src.readLong();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003563 cur.numReadInts += 2;
3564 if (DEBUG) Slog.i(TAG, "READ DELTA: ABS time=" + cur.time);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003565 cur.readFromParcel(src);
3566 return;
3567 } else if (deltaTimeToken == DELTA_TIME_INT) {
3568 int delta = src.readInt();
3569 cur.time += delta;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003570 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003571 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time);
3572 } else {
3573 long delta = src.readLong();
3574 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time);
3575 cur.time += delta;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003576 cur.numReadInts += 2;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003577 }
3578
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003579 final int batteryLevelInt;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003580 if ((firstToken&DELTA_BATTERY_LEVEL_FLAG) != 0) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003581 batteryLevelInt = src.readInt();
Adam Lesinski3944c812015-11-13 15:54:59 -08003582 readBatteryLevelInt(batteryLevelInt, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003583 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003584 if (DEBUG) Slog.i(TAG, "READ DELTA: batteryToken=0x"
3585 + Integer.toHexString(batteryLevelInt)
3586 + " batteryLevel=" + cur.batteryLevel
3587 + " batteryTemp=" + cur.batteryTemperature
3588 + " batteryVolt=" + (int)cur.batteryVoltage);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003589 } else {
3590 batteryLevelInt = 0;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003591 }
3592
3593 if ((firstToken&DELTA_STATE_FLAG) != 0) {
3594 int stateInt = src.readInt();
Adam Lesinski926969b2016-04-28 17:31:12 -07003595 cur.states = (firstToken&DELTA_STATE_MASK) | (stateInt&(~STATE_BATTERY_MASK));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003596 cur.batteryStatus = (byte)((stateInt>>STATE_BATTERY_STATUS_SHIFT)
3597 & STATE_BATTERY_STATUS_MASK);
3598 cur.batteryHealth = (byte)((stateInt>>STATE_BATTERY_HEALTH_SHIFT)
3599 & STATE_BATTERY_HEALTH_MASK);
3600 cur.batteryPlugType = (byte)((stateInt>>STATE_BATTERY_PLUG_SHIFT)
3601 & STATE_BATTERY_PLUG_MASK);
3602 switch (cur.batteryPlugType) {
3603 case 1:
3604 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_AC;
3605 break;
3606 case 2:
3607 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_USB;
3608 break;
3609 case 3:
3610 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_WIRELESS;
3611 break;
3612 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003613 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003614 if (DEBUG) Slog.i(TAG, "READ DELTA: stateToken=0x"
3615 + Integer.toHexString(stateInt)
3616 + " batteryStatus=" + cur.batteryStatus
3617 + " batteryHealth=" + cur.batteryHealth
3618 + " batteryPlugType=" + cur.batteryPlugType
3619 + " states=0x" + Integer.toHexString(cur.states));
3620 } else {
Adam Lesinski926969b2016-04-28 17:31:12 -07003621 cur.states = (firstToken&DELTA_STATE_MASK) | (cur.states&(~STATE_BATTERY_MASK));
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003622 }
3623
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003624 if ((firstToken&DELTA_STATE2_FLAG) != 0) {
3625 cur.states2 = src.readInt();
3626 if (DEBUG) Slog.i(TAG, "READ DELTA: states2=0x"
3627 + Integer.toHexString(cur.states2));
3628 }
3629
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003630 if ((firstToken&DELTA_WAKELOCK_FLAG) != 0) {
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003631 int indexes = src.readInt();
3632 int wakeLockIndex = indexes&0xffff;
3633 int wakeReasonIndex = (indexes>>16)&0xffff;
3634 if (wakeLockIndex != 0xffff) {
3635 cur.wakelockTag = cur.localWakelockTag;
3636 readHistoryTag(wakeLockIndex, cur.wakelockTag);
3637 if (DEBUG) Slog.i(TAG, "READ DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx
3638 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string);
3639 } else {
3640 cur.wakelockTag = null;
3641 }
3642 if (wakeReasonIndex != 0xffff) {
3643 cur.wakeReasonTag = cur.localWakeReasonTag;
3644 readHistoryTag(wakeReasonIndex, cur.wakeReasonTag);
3645 if (DEBUG) Slog.i(TAG, "READ DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx
3646 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string);
3647 } else {
3648 cur.wakeReasonTag = null;
3649 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003650 cur.numReadInts += 1;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003651 } else {
3652 cur.wakelockTag = null;
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003653 cur.wakeReasonTag = null;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003654 }
3655
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003656 if ((firstToken&DELTA_EVENT_FLAG) != 0) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003657 cur.eventTag = cur.localEventTag;
3658 final int codeAndIndex = src.readInt();
Dianne Hackborn099bc622014-01-22 13:39:16 -08003659 cur.eventCode = (codeAndIndex&0xffff);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003660 final int index = ((codeAndIndex>>16)&0xffff);
3661 readHistoryTag(index, cur.eventTag);
3662 cur.numReadInts += 1;
3663 if (DEBUG) Slog.i(TAG, "READ DELTA: event=" + cur.eventCode + " tag=#"
3664 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":"
3665 + cur.eventTag.string);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003666 } else {
3667 cur.eventCode = HistoryItem.EVENT_NONE;
3668 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003669
3670 if ((batteryLevelInt&BATTERY_DELTA_LEVEL_FLAG) != 0) {
3671 cur.stepDetails = mReadHistoryStepDetails;
3672 cur.stepDetails.readFromParcel(src);
3673 } else {
3674 cur.stepDetails = null;
3675 }
Adam Lesinski926969b2016-04-28 17:31:12 -07003676
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003677 if ((firstToken&DELTA_BATTERY_CHARGE_FLAG) != 0) {
3678 cur.batteryChargeUAh = src.readInt();
Adam Lesinski926969b2016-04-28 17:31:12 -07003679 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003680 }
3681
Dianne Hackbornfc064132014-06-02 12:42:12 -07003682 @Override
3683 public void commitCurrentHistoryBatchLocked() {
3684 mHistoryLastWritten.cmd = HistoryItem.CMD_NULL;
3685 }
3686
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003687 void addHistoryBufferLocked(long elapsedRealtimeMs, HistoryItem cur) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003688 if (!mHaveBatteryLevel || !mRecordingHistory) {
3689 return;
3690 }
3691
Dianne Hackborn40c87252014-03-19 16:55:40 -07003692 final long timeDiff = (mHistoryBaseTime+elapsedRealtimeMs) - mHistoryLastWritten.time;
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003693 final int diffStates = mHistoryLastWritten.states^(cur.states&mActiveHistoryStates);
3694 final int diffStates2 = mHistoryLastWritten.states2^(cur.states2&mActiveHistoryStates2);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003695 final int lastDiffStates = mHistoryLastWritten.states^mHistoryLastLastWritten.states;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003696 final int lastDiffStates2 = mHistoryLastWritten.states2^mHistoryLastLastWritten.states2;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003697 if (DEBUG) Slog.i(TAG, "ADD: tdelta=" + timeDiff + " diff="
3698 + Integer.toHexString(diffStates) + " lastDiff="
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003699 + Integer.toHexString(lastDiffStates) + " diff2="
3700 + Integer.toHexString(diffStates2) + " lastDiff2="
3701 + Integer.toHexString(lastDiffStates2));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003702 if (mHistoryBufferLastPos >= 0 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003703 && timeDiff < 1000 && (diffStates&lastDiffStates) == 0
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003704 && (diffStates2&lastDiffStates2) == 0
3705 && (mHistoryLastWritten.wakelockTag == null || cur.wakelockTag == null)
3706 && (mHistoryLastWritten.wakeReasonTag == null || cur.wakeReasonTag == null)
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003707 && mHistoryLastWritten.stepDetails == null
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003708 && (mHistoryLastWritten.eventCode == HistoryItem.EVENT_NONE
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003709 || cur.eventCode == HistoryItem.EVENT_NONE)
3710 && mHistoryLastWritten.batteryLevel == cur.batteryLevel
3711 && mHistoryLastWritten.batteryStatus == cur.batteryStatus
3712 && mHistoryLastWritten.batteryHealth == cur.batteryHealth
3713 && mHistoryLastWritten.batteryPlugType == cur.batteryPlugType
3714 && mHistoryLastWritten.batteryTemperature == cur.batteryTemperature
3715 && mHistoryLastWritten.batteryVoltage == cur.batteryVoltage) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003716 // We can merge this new change in with the last one. Merging is
Dianne Hackborn40c87252014-03-19 16:55:40 -07003717 // allowed as long as only the states have changed, and within those states
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003718 // as long as no bit has changed both between now and the last entry, as
3719 // well as the last entry and the one before it (so we capture any toggles).
3720 if (DEBUG) Slog.i(TAG, "ADD: rewinding back to " + mHistoryBufferLastPos);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003721 mHistoryBuffer.setDataSize(mHistoryBufferLastPos);
3722 mHistoryBuffer.setDataPosition(mHistoryBufferLastPos);
3723 mHistoryBufferLastPos = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003724 elapsedRealtimeMs = mHistoryLastWritten.time - mHistoryBaseTime;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003725 // If the last written history had a wakelock tag, we need to retain it.
3726 // Note that the condition above made sure that we aren't in a case where
3727 // both it and the current history item have a wakelock tag.
3728 if (mHistoryLastWritten.wakelockTag != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003729 cur.wakelockTag = cur.localWakelockTag;
3730 cur.wakelockTag.setTo(mHistoryLastWritten.wakelockTag);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003731 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003732 // If the last written history had a wake reason tag, we need to retain it.
3733 // Note that the condition above made sure that we aren't in a case where
3734 // both it and the current history item have a wakelock tag.
3735 if (mHistoryLastWritten.wakeReasonTag != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003736 cur.wakeReasonTag = cur.localWakeReasonTag;
3737 cur.wakeReasonTag.setTo(mHistoryLastWritten.wakeReasonTag);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003738 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003739 // If the last written history had an event, we need to retain it.
3740 // Note that the condition above made sure that we aren't in a case where
3741 // both it and the current history item have an event.
3742 if (mHistoryLastWritten.eventCode != HistoryItem.EVENT_NONE) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003743 cur.eventCode = mHistoryLastWritten.eventCode;
3744 cur.eventTag = cur.localEventTag;
3745 cur.eventTag.setTo(mHistoryLastWritten.eventTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003746 }
Dianne Hackborn1fadab52011-04-14 17:57:33 -07003747 mHistoryLastWritten.setTo(mHistoryLastLastWritten);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003748 }
3749
Adam Lesinski45489782016-12-15 23:45:17 -08003750 boolean recordResetDueToOverflow = false;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003751 final int dataSize = mHistoryBuffer.dataSize();
Adam Lesinski45489782016-12-15 23:45:17 -08003752 if (dataSize >= MAX_MAX_HISTORY_BUFFER*3) {
3753 // Clients can't deal with history buffers this large. This only
3754 // really happens when the device is on charger and interacted with
3755 // for long periods of time, like in retail mode. Since the device is
3756 // most likely charged, when unplugged, stats would have reset anyways.
3757 // Reset the stats and mark that we overflowed.
3758 // b/32540341
3759 resetAllStatsLocked();
3760
3761 // Mark that we want to set *OVERFLOW* event and the RESET:START
3762 // events.
3763 recordResetDueToOverflow = true;
3764
3765 } else if (dataSize >= MAX_HISTORY_BUFFER) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003766 if (!mHistoryOverflow) {
3767 mHistoryOverflow = true;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003768 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, cur);
3769 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_OVERFLOW, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003770 return;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003771 }
3772
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003773 // After overflow, we allow various bit-wise states to settle to 0.
3774 boolean writeAnyway = false;
3775 final int curStates = cur.states & HistoryItem.SETTLE_TO_ZERO_STATES
3776 & mActiveHistoryStates;
3777 if (mHistoryLastWritten.states != curStates) {
3778 // mActiveHistoryStates keeps track of which bits in .states are now being
3779 // forced to 0.
3780 int old = mActiveHistoryStates;
3781 mActiveHistoryStates &= curStates | ~HistoryItem.SETTLE_TO_ZERO_STATES;
3782 writeAnyway |= old != mActiveHistoryStates;
3783 }
3784 final int curStates2 = cur.states2 & HistoryItem.SETTLE_TO_ZERO_STATES2
3785 & mActiveHistoryStates2;
3786 if (mHistoryLastWritten.states2 != curStates2) {
3787 // mActiveHistoryStates2 keeps track of which bits in .states2 are now being
3788 // forced to 0.
3789 int old = mActiveHistoryStates2;
3790 mActiveHistoryStates2 &= curStates2 | ~HistoryItem.SETTLE_TO_ZERO_STATES2;
3791 writeAnyway |= old != mActiveHistoryStates2;
3792 }
3793
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003794 // Once we've reached the maximum number of items, we only
3795 // record changes to the battery level and the most interesting states.
3796 // Once we've reached the maximum maximum number of items, we only
3797 // record changes to the battery level.
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003798 if (!writeAnyway && mHistoryLastWritten.batteryLevel == cur.batteryLevel &&
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003799 (dataSize >= MAX_MAX_HISTORY_BUFFER
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003800 || ((mHistoryLastWritten.states^cur.states)
Dianne Hackborn3251b902014-06-20 14:40:53 -07003801 & HistoryItem.MOST_INTERESTING_STATES) == 0
3802 || ((mHistoryLastWritten.states2^cur.states2)
3803 & HistoryItem.MOST_INTERESTING_STATES2) == 0)) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003804 return;
3805 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003806
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003807 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003808 return;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003809 }
3810
Adam Lesinski45489782016-12-15 23:45:17 -08003811 if (dataSize == 0 || recordResetDueToOverflow) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003812 // The history is currently empty; we need it to start with a time stamp.
3813 cur.currentTime = System.currentTimeMillis();
Adam Lesinski45489782016-12-15 23:45:17 -08003814 if (recordResetDueToOverflow) {
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003815 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_OVERFLOW, cur);
Adam Lesinski45489782016-12-15 23:45:17 -08003816 }
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003817 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_RESET, cur);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003818 }
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003819 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003820 }
3821
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003822 private void addHistoryBufferLocked(long elapsedRealtimeMs, byte cmd, HistoryItem cur) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003823 if (mIteratingHistory) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003824 throw new IllegalStateException("Can't do this while iterating history!");
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003825 }
3826 mHistoryBufferLastPos = mHistoryBuffer.dataPosition();
3827 mHistoryLastLastWritten.setTo(mHistoryLastWritten);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003828 mHistoryLastWritten.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003829 mHistoryLastWritten.states &= mActiveHistoryStates;
3830 mHistoryLastWritten.states2 &= mActiveHistoryStates2;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003831 writeHistoryDelta(mHistoryBuffer, mHistoryLastWritten, mHistoryLastLastWritten);
Dianne Hackborn40c87252014-03-19 16:55:40 -07003832 mLastHistoryElapsedRealtime = elapsedRealtimeMs;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003833 cur.wakelockTag = null;
3834 cur.wakeReasonTag = null;
3835 cur.eventCode = HistoryItem.EVENT_NONE;
3836 cur.eventTag = null;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003837 if (DEBUG_HISTORY) Slog.i(TAG, "Writing history buffer: was " + mHistoryBufferLastPos
3838 + " now " + mHistoryBuffer.dataPosition()
3839 + " size is now " + mHistoryBuffer.dataSize());
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003840 }
3841
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003842 int mChangedStates = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003843 int mChangedStates2 = 0;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003844
Dianne Hackborn40c87252014-03-19 16:55:40 -07003845 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003846 if (mTrackRunningHistoryElapsedRealtime != 0) {
3847 final long diffElapsed = elapsedRealtimeMs - mTrackRunningHistoryElapsedRealtime;
3848 final long diffUptime = uptimeMs - mTrackRunningHistoryUptime;
3849 if (diffUptime < (diffElapsed-20)) {
3850 final long wakeElapsedTime = elapsedRealtimeMs - (diffElapsed - diffUptime);
3851 mHistoryAddTmp.setTo(mHistoryLastWritten);
3852 mHistoryAddTmp.wakelockTag = null;
3853 mHistoryAddTmp.wakeReasonTag = null;
3854 mHistoryAddTmp.eventCode = HistoryItem.EVENT_NONE;
3855 mHistoryAddTmp.states &= ~HistoryItem.STATE_CPU_RUNNING_FLAG;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003856 addHistoryRecordInnerLocked(wakeElapsedTime, mHistoryAddTmp);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003857 }
3858 }
3859 mHistoryCur.states |= HistoryItem.STATE_CPU_RUNNING_FLAG;
3860 mTrackRunningHistoryElapsedRealtime = elapsedRealtimeMs;
3861 mTrackRunningHistoryUptime = uptimeMs;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003862 addHistoryRecordInnerLocked(elapsedRealtimeMs, mHistoryCur);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003863 }
3864
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003865 void addHistoryRecordInnerLocked(long elapsedRealtimeMs, HistoryItem cur) {
3866 addHistoryBufferLocked(elapsedRealtimeMs, cur);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003867
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003868 if (!USE_OLD_HISTORY) {
3869 return;
3870 }
3871
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003872 if (!mHaveBatteryLevel || !mRecordingHistory) {
3873 return;
3874 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003875
3876 // If the current time is basically the same as the last time,
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003877 // and no states have since the last recorded entry changed and
3878 // are now resetting back to their original value, then just collapse
3879 // into one record.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003880 if (mHistoryEnd != null && mHistoryEnd.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn40c87252014-03-19 16:55:40 -07003881 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+1000)
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003882 && ((mHistoryEnd.states^cur.states)&mChangedStates&mActiveHistoryStates) == 0
3883 && ((mHistoryEnd.states2^cur.states2)&mChangedStates2&mActiveHistoryStates2) == 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003884 // If the current is the same as the one before, then we no
3885 // longer need the entry.
3886 if (mHistoryLastEnd != null && mHistoryLastEnd.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn40c87252014-03-19 16:55:40 -07003887 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+500)
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003888 && mHistoryLastEnd.sameNonEvent(cur)) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003889 mHistoryLastEnd.next = null;
3890 mHistoryEnd.next = mHistoryCache;
3891 mHistoryCache = mHistoryEnd;
3892 mHistoryEnd = mHistoryLastEnd;
3893 mHistoryLastEnd = null;
3894 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003895 mChangedStates |= mHistoryEnd.states^(cur.states&mActiveHistoryStates);
3896 mChangedStates2 |= mHistoryEnd.states^(cur.states2&mActiveHistoryStates2);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003897 mHistoryEnd.setTo(mHistoryEnd.time, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003898 }
3899 return;
3900 }
3901
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003902 mChangedStates = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003903 mChangedStates2 = 0;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003904
3905 if (mNumHistoryItems == MAX_HISTORY_ITEMS
3906 || mNumHistoryItems == MAX_MAX_HISTORY_ITEMS) {
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003907 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_OVERFLOW, cur);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07003908 }
3909
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003910 if (mNumHistoryItems >= MAX_HISTORY_ITEMS) {
3911 // Once we've reached the maximum number of items, we only
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003912 // record changes to the battery level and the most interesting states.
3913 // Once we've reached the maximum maximum number of items, we only
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003914 // record changes to the battery level.
3915 if (mHistoryEnd != null && mHistoryEnd.batteryLevel
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003916 == cur.batteryLevel &&
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003917 (mNumHistoryItems >= MAX_MAX_HISTORY_ITEMS
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003918 || ((mHistoryEnd.states^(cur.states&mActiveHistoryStates))
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003919 & HistoryItem.MOST_INTERESTING_STATES) == 0)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003920 return;
3921 }
3922 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003923
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003924 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003925 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003926
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003927 public void addHistoryEventLocked(long elapsedRealtimeMs, long uptimeMs, int code,
Dianne Hackborn40c87252014-03-19 16:55:40 -07003928 String name, int uid) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003929 mHistoryCur.eventCode = code;
3930 mHistoryCur.eventTag = mHistoryCur.localEventTag;
3931 mHistoryCur.eventTag.string = name;
3932 mHistoryCur.eventTag.uid = uid;
Dianne Hackborn4590e522014-03-24 13:36:46 -07003933 addHistoryRecordLocked(elapsedRealtimeMs, uptimeMs);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003934 }
3935
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003936 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs, byte cmd, HistoryItem cur) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003937 HistoryItem rec = mHistoryCache;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003938 if (rec != null) {
3939 mHistoryCache = rec.next;
3940 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003941 rec = new HistoryItem();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003942 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003943 rec.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003944
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003945 addHistoryRecordLocked(rec);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003946 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003947
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003948 void addHistoryRecordLocked(HistoryItem rec) {
3949 mNumHistoryItems++;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003950 rec.next = null;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003951 mHistoryLastEnd = mHistoryEnd;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003952 if (mHistoryEnd != null) {
3953 mHistoryEnd.next = rec;
3954 mHistoryEnd = rec;
3955 } else {
3956 mHistory = mHistoryEnd = rec;
3957 }
3958 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003959
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003960 void clearHistoryLocked() {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003961 if (DEBUG_HISTORY) Slog.i(TAG, "********** CLEARING HISTORY!");
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003962 if (USE_OLD_HISTORY) {
3963 if (mHistory != null) {
3964 mHistoryEnd.next = mHistoryCache;
3965 mHistoryCache = mHistory;
3966 mHistory = mHistoryLastEnd = mHistoryEnd = null;
3967 }
3968 mNumHistoryItems = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003969 }
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003970
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003971 mHistoryBaseTime = 0;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003972 mLastHistoryElapsedRealtime = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003973 mTrackRunningHistoryElapsedRealtime = 0;
3974 mTrackRunningHistoryUptime = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003975
3976 mHistoryBuffer.setDataSize(0);
3977 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003978 mHistoryBuffer.setDataCapacity(MAX_HISTORY_BUFFER / 2);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003979 mHistoryLastLastWritten.clear();
3980 mHistoryLastWritten.clear();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003981 mHistoryTagPool.clear();
3982 mNextHistoryTagIdx = 0;
3983 mNumHistoryTagChars = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003984 mHistoryBufferLastPos = -1;
3985 mHistoryOverflow = false;
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003986 mActiveHistoryStates = 0xffffffff;
3987 mActiveHistoryStates2 = 0xffffffff;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003988 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003989
Andreas Gampe3f24e692018-02-05 13:24:28 -08003990 @GuardedBy("this")
Mike Mac2f518a2017-09-19 16:06:03 -07003991 public void updateTimeBasesLocked(boolean unplugged, int screenState, long uptime,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003992 long realtime) {
Mike Maa7724752017-10-10 15:29:25 -07003993 final boolean screenOff = !isScreenOn(screenState);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003994 final boolean updateOnBatteryTimeBase = unplugged != mOnBatteryTimeBase.isRunning();
3995 final boolean updateOnBatteryScreenOffTimeBase =
3996 (unplugged && screenOff) != mOnBatteryScreenOffTimeBase.isRunning();
Bookatz867c0d72017-03-07 18:23:42 -08003997
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003998 if (updateOnBatteryScreenOffTimeBase || updateOnBatteryTimeBase) {
3999 if (updateOnBatteryScreenOffTimeBase) {
4000 updateKernelWakelocksLocked();
4001 updateBatteryPropertiesLocked();
Bookatz867c0d72017-03-07 18:23:42 -08004002 }
Bookatz82b341172017-09-07 19:06:08 -07004003 // This if{} is only necessary due to SCREEN_OFF_RPM_STATS_ENABLED, which exists because
4004 // updateRpmStatsLocked is too slow to run each screen change. When the speed is
4005 // improved, remove the surrounding if{}.
4006 if (SCREEN_OFF_RPM_STATS_ENABLED || updateOnBatteryTimeBase) {
4007 updateRpmStatsLocked(); // if either OnBattery or OnBatteryScreenOff timebase changes.
4008 }
Adam Lesinski72478f02015-06-17 15:39:43 -07004009 if (DEBUG_ENERGY_CPU) {
Mike Mac2f518a2017-09-19 16:06:03 -07004010 Slog.d(TAG, "Updating cpu time because screen is now "
4011 + Display.stateToString(screenState)
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07004012 + " and battery is " + (unplugged ? "on" : "off"));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004013 }
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07004014
4015 mOnBatteryTimeBase.setRunning(unplugged, uptime, realtime);
Mike Mac2f518a2017-09-19 16:06:03 -07004016 if (updateOnBatteryTimeBase) {
4017 for (int i = mUidStats.size() - 1; i >= 0; --i) {
4018 mUidStats.valueAt(i).updateOnBatteryBgTimeBase(uptime, realtime);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07004019 }
Mike Mac2f518a2017-09-19 16:06:03 -07004020 }
4021 if (updateOnBatteryScreenOffTimeBase) {
4022 mOnBatteryScreenOffTimeBase.setRunning(unplugged && screenOff, uptime, realtime);
4023 for (int i = mUidStats.size() - 1; i >= 0; --i) {
4024 mUidStats.valueAt(i).updateOnBatteryScreenOffBgTimeBase(uptime, realtime);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07004025 }
Bookatzc8c44962017-05-11 12:12:54 -07004026 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004027 }
4028 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07004029
Adam Lesinskie1f480d2017-02-15 18:51:23 -08004030 private void updateBatteryPropertiesLocked() {
4031 try {
4032 IBatteryPropertiesRegistrar registrar = IBatteryPropertiesRegistrar.Stub.asInterface(
4033 ServiceManager.getService("batteryproperties"));
4034 registrar.scheduleUpdate();
4035 } catch (RemoteException e) {
4036 // Ignore.
4037 }
4038 }
4039
Dianne Hackborn099bc622014-01-22 13:39:16 -08004040 public void addIsolatedUidLocked(int isolatedUid, int appUid) {
4041 mIsolatedUids.put(isolatedUid, appUid);
Bookatz90867622018-01-31 15:05:57 -08004042 StatsLog.write(StatsLog.ISOLATED_UID_CHANGED, appUid, isolatedUid,
4043 StatsLog.ISOLATED_UID_CHANGED__EVENT__CREATED);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08004044 final Uid u = getUidStatsLocked(appUid);
4045 u.addIsolatedUid(isolatedUid);
Dianne Hackborn099bc622014-01-22 13:39:16 -08004046 }
4047
Adam Lesinski61db88f2015-07-01 15:05:07 -07004048 /**
4049 * Schedules a read of the latest cpu times before removing the isolated UID.
4050 * @see #removeIsolatedUidLocked(int)
4051 */
4052 public void scheduleRemoveIsolatedUidLocked(int isolatedUid, int appUid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004053 int curUid = mIsolatedUids.get(isolatedUid, -1);
4054 if (curUid == appUid) {
Adam Lesinski61db88f2015-07-01 15:05:07 -07004055 if (mExternalSync != null) {
4056 mExternalSync.scheduleCpuSyncDueToRemovedUid(isolatedUid);
4057 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08004058 }
4059 }
4060
Adam Lesinski61db88f2015-07-01 15:05:07 -07004061 /**
4062 * This should only be called after the cpu times have been read.
4063 * @see #scheduleRemoveIsolatedUidLocked(int, int)
4064 */
Andreas Gampe3f24e692018-02-05 13:24:28 -08004065 @GuardedBy("this")
Adam Lesinski61db88f2015-07-01 15:05:07 -07004066 public void removeIsolatedUidLocked(int isolatedUid) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08004067 StatsLog.write(
Bookatz90867622018-01-31 15:05:57 -08004068 StatsLog.ISOLATED_UID_CHANGED, mIsolatedUids.get(isolatedUid, -1),
4069 isolatedUid, StatsLog.ISOLATED_UID_CHANGED__EVENT__REMOVED);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08004070 final int idx = mIsolatedUids.indexOfKey(isolatedUid);
4071 if (idx >= 0) {
4072 final int ownerUid = mIsolatedUids.valueAt(idx);
4073 final Uid u = getUidStatsLocked(ownerUid);
4074 u.removeIsolatedUid(isolatedUid);
4075 mIsolatedUids.removeAt(idx);
4076 }
Mike Ma234d1822018-03-13 18:53:21 -07004077 mPendingRemovedUids.add(new UidToRemove(isolatedUid, mClocks.elapsedRealtime()));
Adam Lesinski61db88f2015-07-01 15:05:07 -07004078 }
4079
Dianne Hackborn099bc622014-01-22 13:39:16 -08004080 public int mapUid(int uid) {
4081 int isolated = mIsolatedUids.get(uid, -1);
4082 return isolated > 0 ? isolated : uid;
4083 }
4084
4085 public void noteEventLocked(int code, String name, int uid) {
4086 uid = mapUid(uid);
Dianne Hackborn37de0982014-05-09 09:32:18 -07004087 if (!mActiveEvents.updateState(code, name, uid, 0)) {
4088 return;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08004089 }
Joe Onoratoabded112016-02-08 16:49:39 -08004090 final long elapsedRealtime = mClocks.elapsedRealtime();
4091 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -07004092 addHistoryEventLocked(elapsedRealtime, uptime, code, name, uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -08004093 }
4094
Dianne Hackbornd48954f2015-07-22 17:20:33 -07004095 boolean ensureStartClockTime(final long currentTime) {
4096 final long ABOUT_ONE_YEAR = 365*24*60*60*1000L;
Makoto Onuki62b3c922018-04-25 14:51:56 -07004097 if ((currentTime > ABOUT_ONE_YEAR && mStartClockTime < (currentTime-ABOUT_ONE_YEAR))
4098 || (mStartClockTime > currentTime)) {
Dianne Hackbornd48954f2015-07-22 17:20:33 -07004099 // If the start clock time has changed by more than a year, then presumably
4100 // the previous time was completely bogus. So we are going to figure out a
4101 // new time based on how much time has elapsed since we started counting.
Joe Onoratoabded112016-02-08 16:49:39 -08004102 mStartClockTime = currentTime - (mClocks.elapsedRealtime()-(mRealtimeStart/1000));
Dianne Hackbornd48954f2015-07-22 17:20:33 -07004103 return true;
4104 }
4105 return false;
4106 }
4107
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07004108 public void noteCurrentTimeChangedLocked() {
4109 final long currentTime = System.currentTimeMillis();
Joe Onoratoabded112016-02-08 16:49:39 -08004110 final long elapsedRealtime = mClocks.elapsedRealtime();
4111 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07004112 recordCurrentTimeChangeLocked(currentTime, elapsedRealtime, uptime);
Dianne Hackbornd48954f2015-07-22 17:20:33 -07004113 ensureStartClockTime(currentTime);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07004114 }
4115
Dianne Hackborn61659e52014-07-09 16:13:01 -07004116 public void noteProcessStartLocked(String name, int uid) {
4117 uid = mapUid(uid);
4118 if (isOnBattery()) {
4119 Uid u = getUidStatsLocked(uid);
4120 u.getProcessStatsLocked(name).incStartsLocked();
4121 }
4122 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_START, name, uid, 0)) {
4123 return;
4124 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004125 if (!mRecordAllHistory) {
4126 return;
4127 }
Joe Onoratoabded112016-02-08 16:49:39 -08004128 final long elapsedRealtime = mClocks.elapsedRealtime();
4129 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn61659e52014-07-09 16:13:01 -07004130 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_START, name, uid);
4131 }
4132
Dianne Hackborn1e01d162014-12-04 17:46:42 -08004133 public void noteProcessCrashLocked(String name, int uid) {
4134 uid = mapUid(uid);
4135 if (isOnBattery()) {
4136 Uid u = getUidStatsLocked(uid);
4137 u.getProcessStatsLocked(name).incNumCrashesLocked();
4138 }
4139 }
4140
4141 public void noteProcessAnrLocked(String name, int uid) {
4142 uid = mapUid(uid);
4143 if (isOnBattery()) {
4144 Uid u = getUidStatsLocked(uid);
4145 u.getProcessStatsLocked(name).incNumAnrsLocked();
4146 }
4147 }
4148
Dianne Hackborna8d10942015-11-19 17:55:19 -08004149 public void noteUidProcessStateLocked(int uid, int state) {
Amith Yamasanifd3caf62017-07-26 11:48:35 -07004150 int parentUid = mapUid(uid);
4151 if (uid != parentUid) {
4152 // Isolated UIDs process state is already rolled up into parent, so no need to track
4153 // Otherwise the parent's process state will get downgraded incorrectly
4154 return;
4155 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08004156 getUidStatsLocked(uid).updateUidProcessStateLocked(state);
Dianne Hackborn61659e52014-07-09 16:13:01 -07004157 }
4158
4159 public void noteProcessFinishLocked(String name, int uid) {
4160 uid = mapUid(uid);
4161 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_FINISH, name, uid, 0)) {
4162 return;
4163 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004164 if (!mRecordAllHistory) {
4165 return;
4166 }
Joe Onoratoabded112016-02-08 16:49:39 -08004167 final long elapsedRealtime = mClocks.elapsedRealtime();
4168 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004169 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_FINISH, name, uid);
Dianne Hackborn61659e52014-07-09 16:13:01 -07004170 }
4171
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004172 public void noteSyncStartLocked(String name, int uid) {
4173 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004174 final long elapsedRealtime = mClocks.elapsedRealtime();
4175 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004176 getUidStatsLocked(uid).noteStartSyncLocked(name, elapsedRealtime);
4177 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_START, name, uid, 0)) {
4178 return;
4179 }
4180 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_START, name, uid);
4181 }
4182
4183 public void noteSyncFinishLocked(String name, int uid) {
4184 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004185 final long elapsedRealtime = mClocks.elapsedRealtime();
4186 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004187 getUidStatsLocked(uid).noteStopSyncLocked(name, elapsedRealtime);
4188 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_FINISH, name, uid, 0)) {
4189 return;
4190 }
4191 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_FINISH, name, uid);
4192 }
4193
4194 public void noteJobStartLocked(String name, int uid) {
4195 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004196 final long elapsedRealtime = mClocks.elapsedRealtime();
4197 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004198 getUidStatsLocked(uid).noteStartJobLocked(name, elapsedRealtime);
4199 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_START, name, uid, 0)) {
4200 return;
4201 }
4202 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_START, name, uid);
4203 }
4204
Dianne Hackborn94326cb2017-06-28 16:17:20 -07004205 public void noteJobFinishLocked(String name, int uid, int stopReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004206 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004207 final long elapsedRealtime = mClocks.elapsedRealtime();
4208 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07004209 getUidStatsLocked(uid).noteStopJobLocked(name, elapsedRealtime, stopReason);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004210 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_FINISH, name, uid, 0)) {
4211 return;
4212 }
4213 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_FINISH, name, uid);
4214 }
4215
Amith Yamasani977e11f2018-02-16 11:29:54 -08004216 public void noteJobsDeferredLocked(int uid, int numDeferred, long sinceLast) {
4217 uid = mapUid(uid);
4218 getUidStatsLocked(uid).noteJobsDeferredLocked(numDeferred, sinceLast);
4219 }
4220
Narayan Kamath695cf722017-12-21 18:32:47 +00004221 public void noteAlarmStartLocked(String name, WorkSource workSource, int uid) {
4222 noteAlarmStartOrFinishLocked(HistoryItem.EVENT_ALARM_START, name, workSource, uid);
Dianne Hackborn1e383822015-04-10 14:02:33 -07004223 }
4224
Narayan Kamath695cf722017-12-21 18:32:47 +00004225 public void noteAlarmFinishLocked(String name, WorkSource workSource, int uid) {
4226 noteAlarmStartOrFinishLocked(HistoryItem.EVENT_ALARM_FINISH, name, workSource, uid);
4227 }
4228
4229 private void noteAlarmStartOrFinishLocked(int historyItem, String name, WorkSource workSource,
4230 int uid) {
Dianne Hackborn1e383822015-04-10 14:02:33 -07004231 if (!mRecordAllHistory) {
4232 return;
4233 }
Narayan Kamath695cf722017-12-21 18:32:47 +00004234
Joe Onoratoabded112016-02-08 16:49:39 -08004235 final long elapsedRealtime = mClocks.elapsedRealtime();
4236 final long uptime = mClocks.uptimeMillis();
Narayan Kamath695cf722017-12-21 18:32:47 +00004237
4238 if (workSource != null) {
4239 for (int i = 0; i < workSource.size(); ++i) {
4240 uid = mapUid(workSource.get(i));
4241 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4242 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4243 }
4244 }
4245
4246 List<WorkChain> workChains = workSource.getWorkChains();
4247 if (workChains != null) {
4248 for (int i = 0; i < workChains.size(); ++i) {
4249 uid = mapUid(workChains.get(i).getAttributionUid());
4250 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4251 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4252 }
4253 }
4254 }
4255 } else {
4256 uid = mapUid(uid);
4257
4258 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4259 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4260 }
4261 }
4262 }
4263
4264 public void noteWakupAlarmLocked(String packageName, int uid, WorkSource workSource,
4265 String tag) {
Narayan Kamath695cf722017-12-21 18:32:47 +00004266 if (workSource != null) {
4267 for (int i = 0; i < workSource.size(); ++i) {
4268 uid = workSource.get(i);
4269 final String workSourceName = workSource.getName(i);
4270
Tej Singh6f724c42018-01-03 20:02:03 -08004271 if (isOnBattery()) {
4272 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid,
4273 workSourceName != null ? workSourceName : packageName);
4274 pkg.noteWakeupAlarmLocked(tag);
4275 }
Yangster-mac2f5daec2018-01-16 10:23:15 -08004276 StatsLog.write_non_chained(StatsLog.WAKEUP_ALARM_OCCURRED, workSource.get(i),
4277 workSource.getName(i), tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004278 }
4279
4280 ArrayList<WorkChain> workChains = workSource.getWorkChains();
4281 if (workChains != null) {
4282 for (int i = 0; i < workChains.size(); ++i) {
4283 final WorkChain wc = workChains.get(i);
4284 uid = wc.getAttributionUid();
4285
Tej Singh6f724c42018-01-03 20:02:03 -08004286 if (isOnBattery()) {
4287 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid, packageName);
4288 pkg.noteWakeupAlarmLocked(tag);
4289 }
Yangster-macafad8c62018-01-05 22:30:49 -08004290 StatsLog.write(StatsLog.WAKEUP_ALARM_OCCURRED, wc.getUids(), wc.getTags(), tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004291 }
4292 }
4293 } else {
Tej Singh6f724c42018-01-03 20:02:03 -08004294 if (isOnBattery()) {
4295 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid, packageName);
4296 pkg.noteWakeupAlarmLocked(tag);
4297 }
Yangster-mac2f5daec2018-01-16 10:23:15 -08004298 StatsLog.write_non_chained(StatsLog.WAKEUP_ALARM_OCCURRED, uid, null, tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004299 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07004300 }
4301
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004302 private void requestWakelockCpuUpdate() {
Sudheer Shankac57729a2018-02-09 15:44:42 -08004303 mExternalSync.scheduleCpuSyncDueToWakelockChange(DELAY_UPDATE_WAKELOCKS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004304 }
4305
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004306 private void requestImmediateCpuUpdate() {
Sudheer Shankac57729a2018-02-09 15:44:42 -08004307 mExternalSync.scheduleCpuSyncDueToWakelockChange(0 /* delayMillis */);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004308 }
4309
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004310 public void setRecordAllHistoryLocked(boolean enabled) {
4311 mRecordAllHistory = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004312 if (!enabled) {
4313 // Clear out any existing state.
4314 mActiveEvents.removeEvents(HistoryItem.EVENT_WAKE_LOCK);
Dianne Hackborn1e383822015-04-10 14:02:33 -07004315 mActiveEvents.removeEvents(HistoryItem.EVENT_ALARM);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004316 // Record the currently running processes as stopping, now that we are no
4317 // longer tracking them.
4318 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
4319 HistoryItem.EVENT_PROC);
4320 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08004321 long mSecRealtime = mClocks.elapsedRealtime();
4322 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004323 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
4324 SparseIntArray uids = ent.getValue();
4325 for (int j=0; j<uids.size(); j++) {
4326 addHistoryEventLocked(mSecRealtime, mSecUptime,
4327 HistoryItem.EVENT_PROC_FINISH, ent.getKey(), uids.keyAt(j));
4328 }
4329 }
4330 }
4331 } else {
4332 // Record the currently running processes as starting, now that we are tracking them.
4333 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
4334 HistoryItem.EVENT_PROC);
4335 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08004336 long mSecRealtime = mClocks.elapsedRealtime();
4337 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004338 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
4339 SparseIntArray uids = ent.getValue();
4340 for (int j=0; j<uids.size(); j++) {
4341 addHistoryEventLocked(mSecRealtime, mSecUptime,
4342 HistoryItem.EVENT_PROC_START, ent.getKey(), uids.keyAt(j));
4343 }
4344 }
4345 }
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004346 }
4347 }
4348
Dianne Hackborn9a755432014-05-15 17:05:22 -07004349 public void setNoAutoReset(boolean enabled) {
4350 mNoAutoReset = enabled;
4351 }
4352
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004353 public void setPretendScreenOff(boolean pretendScreenOff) {
Mike Mac2f518a2017-09-19 16:06:03 -07004354 if (mPretendScreenOff != pretendScreenOff) {
4355 mPretendScreenOff = pretendScreenOff;
4356 noteScreenStateLocked(pretendScreenOff ? Display.STATE_OFF : Display.STATE_ON);
4357 }
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004358 }
4359
Dianne Hackborn9a755432014-05-15 17:05:22 -07004360 private String mInitialAcquireWakeName;
4361 private int mInitialAcquireWakeUid = -1;
4362
Narayan Kamath81822022017-12-08 11:56:01 +00004363 public void noteStartWakeLocked(int uid, int pid, WorkChain wc, String name, String historyName,
4364 int type, boolean unimportantForLogging, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004365 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004366 if (type == WAKE_TYPE_PARTIAL) {
4367 // Only care about partial wake locks, since full wake locks
4368 // will be canceled when the user puts the screen to sleep.
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004369 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07004370 if (historyName == null) {
4371 historyName = name;
4372 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004373 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07004374 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_START, historyName,
4375 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07004376 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07004377 HistoryItem.EVENT_WAKE_LOCK_START, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07004378 }
4379 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004380 if (mWakeLockNesting == 0) {
4381 mHistoryCur.states |= HistoryItem.STATE_WAKE_LOCK_FLAG;
4382 if (DEBUG_HISTORY) Slog.v(TAG, "Start wake lock to: "
4383 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08004384 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004385 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07004386 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004387 mWakeLockImportant = !unimportantForLogging;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004388 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07004389 } else if (!mWakeLockImportant && !unimportantForLogging
4390 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004391 if (mHistoryLastWritten.wakelockTag != null) {
4392 // We'll try to update the last tag.
4393 mHistoryLastWritten.wakelockTag = null;
4394 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004395 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07004396 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004397 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004398 }
4399 mWakeLockImportant = true;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004400 }
4401 mWakeLockNesting++;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004402 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004403 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07004404 if (mOnBatteryScreenOffTimeBase.isRunning()) {
4405 // We only update the cpu time when a wake lock is acquired if the screen is off.
4406 // If the screen is on, we don't distribute the power amongst partial wakelocks.
4407 if (DEBUG_ENERGY_CPU) {
4408 Slog.d(TAG, "Updating cpu time because of +wake_lock");
4409 }
4410 requestWakelockCpuUpdate();
4411 }
Narayan Kamath81822022017-12-08 11:56:01 +00004412
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004413 getUidStatsLocked(uid).noteStartWakeLocked(pid, name, type, elapsedRealtime);
Narayan Kamath81822022017-12-08 11:56:01 +00004414
Yangster-mac20877162017-12-22 17:19:39 -08004415 if (wc != null) {
Bookatz1a1b0462018-01-12 11:47:03 -08004416 StatsLog.write(StatsLog.WAKELOCK_STATE_CHANGED, wc.getUids(), wc.getTags(),
Bookatz90867622018-01-31 15:05:57 -08004417 getPowerManagerWakeLockLevel(type), name,
4418 StatsLog.WAKELOCK_STATE_CHANGED__STATE__ACQUIRE);
Yangster-macafad8c62018-01-05 22:30:49 -08004419 } else {
Bookatz1a1b0462018-01-12 11:47:03 -08004420 StatsLog.write_non_chained(StatsLog.WAKELOCK_STATE_CHANGED, uid, null,
Bookatz90867622018-01-31 15:05:57 -08004421 getPowerManagerWakeLockLevel(type), name,
4422 StatsLog.WAKELOCK_STATE_CHANGED__STATE__ACQUIRE);
Narayan Kamath81822022017-12-08 11:56:01 +00004423 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004424 }
4425 }
4426
Narayan Kamath81822022017-12-08 11:56:01 +00004427 public void noteStopWakeLocked(int uid, int pid, WorkChain wc, String name, String historyName,
4428 int type, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004429 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004430 if (type == WAKE_TYPE_PARTIAL) {
4431 mWakeLockNesting--;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004432 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07004433 if (historyName == null) {
4434 historyName = name;
4435 }
4436 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName,
4437 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07004438 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07004439 HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07004440 }
4441 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004442 if (mWakeLockNesting == 0) {
4443 mHistoryCur.states &= ~HistoryItem.STATE_WAKE_LOCK_FLAG;
4444 if (DEBUG_HISTORY) Slog.v(TAG, "Stop wake lock to: "
4445 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn37de0982014-05-09 09:32:18 -07004446 mInitialAcquireWakeName = null;
4447 mInitialAcquireWakeUid = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004448 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004449 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004450 }
4451 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07004452 if (mOnBatteryScreenOffTimeBase.isRunning()) {
4453 if (DEBUG_ENERGY_CPU) {
4454 Slog.d(TAG, "Updating cpu time because of -wake_lock");
4455 }
4456 requestWakelockCpuUpdate();
4457 }
Narayan Kamath81822022017-12-08 11:56:01 +00004458
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004459 getUidStatsLocked(uid).noteStopWakeLocked(pid, name, type, elapsedRealtime);
Yangster-mac20877162017-12-22 17:19:39 -08004460 if (wc != null) {
Bookatz1a1b0462018-01-12 11:47:03 -08004461 StatsLog.write(StatsLog.WAKELOCK_STATE_CHANGED, wc.getUids(), wc.getTags(),
Bookatz90867622018-01-31 15:05:57 -08004462 getPowerManagerWakeLockLevel(type), name,
4463 StatsLog.WAKELOCK_STATE_CHANGED__STATE__RELEASE);
Yangster-macafad8c62018-01-05 22:30:49 -08004464 } else {
Bookatz1a1b0462018-01-12 11:47:03 -08004465 StatsLog.write_non_chained(StatsLog.WAKELOCK_STATE_CHANGED, uid, null,
Bookatz90867622018-01-31 15:05:57 -08004466 getPowerManagerWakeLockLevel(type), name,
4467 StatsLog.WAKELOCK_STATE_CHANGED__STATE__RELEASE);
Narayan Kamath81822022017-12-08 11:56:01 +00004468 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004469 }
4470 }
4471
Bookatz1a1b0462018-01-12 11:47:03 -08004472 /**
4473 * Converts BatteryStats wakelock types back into PowerManager wakelock levels.
4474 * This is the inverse map of Notifier.getBatteryStatsWakeLockMonitorType().
4475 * These are estimations, since batterystats loses some of the original data.
4476 * TODO: Delete this. Instead, StatsLog.write should be called from PowerManager's Notifier.
4477 */
4478 private int getPowerManagerWakeLockLevel(int battertStatsWakelockType) {
4479 switch (battertStatsWakelockType) {
4480 // PowerManager.PARTIAL_WAKE_LOCK or PROXIMITY_SCREEN_OFF_WAKE_LOCK
4481 case BatteryStats.WAKE_TYPE_PARTIAL:
4482 return PowerManager.PARTIAL_WAKE_LOCK;
4483
4484 // PowerManager.SCREEN_DIM_WAKE_LOCK or SCREEN_BRIGHT_WAKE_LOCK
4485 case BatteryStats.WAKE_TYPE_FULL:
4486 return PowerManager.FULL_WAKE_LOCK;
4487
4488 case BatteryStats.WAKE_TYPE_DRAW:
4489 return PowerManager.DRAW_WAKE_LOCK;
4490
4491 // It appears that nothing can ever make a Window and PowerManager lacks an equivalent.
4492 case BatteryStats.WAKE_TYPE_WINDOW:
4493 Slog.e(TAG, "Illegal window wakelock type observed in batterystats.");
4494 return -1;
4495
4496 default:
4497 Slog.e(TAG, "Illegal wakelock type in batterystats: " + battertStatsWakelockType);
4498 return -1;
4499 }
4500 }
4501
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004502 public void noteStartWakeFromSourceLocked(WorkSource ws, int pid, String name,
4503 String historyName, int type, boolean unimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08004504 final long elapsedRealtime = mClocks.elapsedRealtime();
4505 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004506 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004507 for (int i=0; i<N; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004508 noteStartWakeLocked(ws.get(i), pid, null, name, historyName, type,
4509 unimportantForLogging, elapsedRealtime, uptime);
4510 }
4511
4512 List<WorkChain> wcs = ws.getWorkChains();
4513 if (wcs != null) {
4514 for (int i = 0; i < wcs.size(); ++i) {
4515 final WorkChain wc = wcs.get(i);
4516 noteStartWakeLocked(wc.getAttributionUid(), pid, wc, name, historyName, type,
4517 unimportantForLogging, elapsedRealtime, uptime);
4518 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004519 }
4520 }
4521
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004522 public void noteChangeWakelockFromSourceLocked(WorkSource ws, int pid, String name,
4523 String historyName, int type, WorkSource newWs, int newPid, String newName,
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004524 String newHistoryName, int newType, boolean newUnimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08004525 final long elapsedRealtime = mClocks.elapsedRealtime();
4526 final long uptime = mClocks.uptimeMillis();
Narayan Kamath81822022017-12-08 11:56:01 +00004527
4528 List<WorkChain>[] wcs = WorkSource.diffChains(ws, newWs);
4529
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004530 // For correct semantics, we start the need worksources first, so that we won't
4531 // make inappropriate history items as if all wake locks went away and new ones
4532 // appeared. This is okay because tracking of wake locks allows nesting.
Narayan Kamath81822022017-12-08 11:56:01 +00004533 //
4534 // First the starts :
Dianne Hackborn40c87252014-03-19 16:55:40 -07004535 final int NN = newWs.size();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004536 for (int i=0; i<NN; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004537 noteStartWakeLocked(newWs.get(i), newPid, null, newName, newHistoryName, newType,
Dianne Hackborn40c87252014-03-19 16:55:40 -07004538 newUnimportantForLogging, elapsedRealtime, uptime);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004539 }
Narayan Kamath81822022017-12-08 11:56:01 +00004540 if (wcs != null) {
4541 List<WorkChain> newChains = wcs[0];
4542 if (newChains != null) {
4543 for (int i = 0; i < newChains.size(); ++i) {
4544 final WorkChain newChain = newChains.get(i);
4545 noteStartWakeLocked(newChain.getAttributionUid(), newPid, newChain, newName,
4546 newHistoryName, newType, newUnimportantForLogging, elapsedRealtime,
4547 uptime);
4548 }
4549 }
4550 }
4551
4552 // Then the stops :
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004553 final int NO = ws.size();
4554 for (int i=0; i<NO; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004555 noteStopWakeLocked(ws.get(i), pid, null, name, historyName, type, elapsedRealtime,
4556 uptime);
4557 }
4558 if (wcs != null) {
4559 List<WorkChain> goneChains = wcs[1];
4560 if (goneChains != null) {
4561 for (int i = 0; i < goneChains.size(); ++i) {
4562 final WorkChain goneChain = goneChains.get(i);
4563 noteStopWakeLocked(goneChain.getAttributionUid(), pid, goneChain, name,
4564 historyName, type, elapsedRealtime, uptime);
4565 }
4566 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004567 }
4568 }
4569
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004570 public void noteStopWakeFromSourceLocked(WorkSource ws, int pid, String name,
4571 String historyName, int type) {
Joe Onoratoabded112016-02-08 16:49:39 -08004572 final long elapsedRealtime = mClocks.elapsedRealtime();
4573 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004574 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004575 for (int i=0; i<N; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004576 noteStopWakeLocked(ws.get(i), pid, null, name, historyName, type, elapsedRealtime,
4577 uptime);
4578 }
4579
4580 List<WorkChain> wcs = ws.getWorkChains();
4581 if (wcs != null) {
4582 for (int i = 0; i < wcs.size(); ++i) {
4583 final WorkChain wc = wcs.get(i);
4584 noteStopWakeLocked(wc.getAttributionUid(), pid, wc, name, historyName, type,
4585 elapsedRealtime, uptime);
4586 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004587 }
4588 }
4589
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004590 public void noteLongPartialWakelockStart(String name, String historyName, int uid) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08004591 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004592 uid, null, name, historyName,
4593 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
Yangster-macafad8c62018-01-05 22:30:49 -08004594
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004595 uid = mapUid(uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004596 noteLongPartialWakeLockStartInternal(name, historyName, uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004597 }
4598
4599 public void noteLongPartialWakelockStartFromSource(String name, String historyName,
4600 WorkSource workSource) {
4601 final int N = workSource.size();
4602 for (int i = 0; i < N; ++i) {
4603 final int uid = mapUid(workSource.get(i));
4604 noteLongPartialWakeLockStartInternal(name, historyName, uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08004605 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004606 workSource.get(i), workSource.getName(i), name, historyName,
4607 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath96a92562018-01-02 18:57:17 +00004608 }
4609
4610 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
4611 if (workChains != null) {
4612 for (int i = 0; i < workChains.size(); ++i) {
4613 final WorkChain workChain = workChains.get(i);
4614 final int uid = workChain.getAttributionUid();
4615 noteLongPartialWakeLockStartInternal(name, historyName, uid);
4616
Yangster-macafad8c62018-01-05 22:30:49 -08004617 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004618 workChain.getUids(), workChain.getTags(), name, historyName,
4619 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath96a92562018-01-02 18:57:17 +00004620 }
4621 }
4622 }
4623
4624 private void noteLongPartialWakeLockStartInternal(String name, String historyName, int uid) {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004625 final long elapsedRealtime = mClocks.elapsedRealtime();
4626 final long uptime = mClocks.uptimeMillis();
4627 if (historyName == null) {
4628 historyName = name;
4629 }
4630 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_START, historyName, uid,
4631 0)) {
4632 return;
4633 }
4634 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_START,
4635 historyName, uid);
4636 }
4637
4638 public void noteLongPartialWakelockFinish(String name, String historyName, int uid) {
Bookatz90867622018-01-31 15:05:57 -08004639 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED, uid, null,
4640 name, historyName, StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
Yangster-macafad8c62018-01-05 22:30:49 -08004641
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004642 uid = mapUid(uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004643 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004644 }
4645
4646 public void noteLongPartialWakelockFinishFromSource(String name, String historyName,
4647 WorkSource workSource) {
4648 final int N = workSource.size();
4649 for (int i = 0; i < N; ++i) {
4650 final int uid = mapUid(workSource.get(i));
4651 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08004652 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004653 workSource.get(i), workSource.getName(i), name, historyName,
4654 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath96a92562018-01-02 18:57:17 +00004655 }
4656
4657 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
4658 if (workChains != null) {
4659 for (int i = 0; i < workChains.size(); ++i) {
4660 final WorkChain workChain = workChains.get(i);
4661 final int uid = workChain.getAttributionUid();
Narayan Kamath96a92562018-01-02 18:57:17 +00004662 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Yangster-macafad8c62018-01-05 22:30:49 -08004663 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004664 workChain.getUids(), workChain.getTags(), name, historyName,
4665 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath96a92562018-01-02 18:57:17 +00004666 }
4667 }
4668 }
4669
4670 private void noteLongPartialWakeLockFinishInternal(String name, String historyName, int uid) {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004671 final long elapsedRealtime = mClocks.elapsedRealtime();
4672 final long uptime = mClocks.uptimeMillis();
4673 if (historyName == null) {
4674 historyName = name;
4675 }
4676 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH, historyName, uid,
4677 0)) {
4678 return;
4679 }
4680 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH,
4681 historyName, uid);
4682 }
4683
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004684 void aggregateLastWakeupUptimeLocked(long uptimeMs) {
4685 if (mLastWakeupReason != null) {
4686 long deltaUptime = uptimeMs - mLastWakeupUptimeMs;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004687 SamplingTimer timer = getWakeupReasonTimerLocked(mLastWakeupReason);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07004688 timer.add(deltaUptime * 1000, 1); // time in in microseconds
Bookatz90867622018-01-31 15:05:57 -08004689 StatsLog.write(StatsLog.KERNEL_WAKEUP_REPORTED, mLastWakeupReason,
4690 /* duration_usec */ deltaUptime * 1000);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004691 mLastWakeupReason = null;
4692 }
4693 }
4694
4695 public void noteWakeupReasonLocked(String reason) {
Joe Onoratoabded112016-02-08 16:49:39 -08004696 final long elapsedRealtime = mClocks.elapsedRealtime();
4697 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004698 if (DEBUG_HISTORY) Slog.v(TAG, "Wakeup reason \"" + reason +"\": "
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004699 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004700 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004701 mHistoryCur.wakeReasonTag = mHistoryCur.localWakeReasonTag;
4702 mHistoryCur.wakeReasonTag.string = reason;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004703 mHistoryCur.wakeReasonTag.uid = 0;
4704 mLastWakeupReason = reason;
4705 mLastWakeupUptimeMs = uptime;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004706 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004707 }
4708
Adam Lesinski72478f02015-06-17 15:39:43 -07004709 public boolean startAddingCpuLocked() {
Sudheer Shankac57729a2018-02-09 15:44:42 -08004710 mExternalSync.cancelCpuSyncDueToWakelockChange();
Adam Lesinski72478f02015-06-17 15:39:43 -07004711 return mOnBatteryInternal;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004712 }
4713
Adam Lesinski72478f02015-06-17 15:39:43 -07004714 public void finishAddingCpuLocked(int totalUTime, int totalSTime, int statUserTime,
4715 int statSystemTime, int statIOWaitTime, int statIrqTime,
4716 int statSoftIrqTime, int statIdleTime) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004717 if (DEBUG) Slog.d(TAG, "Adding cpu: tuser=" + totalUTime + " tsys=" + totalSTime
4718 + " user=" + statUserTime + " sys=" + statSystemTime
4719 + " io=" + statIOWaitTime + " irq=" + statIrqTime
4720 + " sirq=" + statSoftIrqTime + " idle=" + statIdleTime);
4721 mCurStepCpuUserTime += totalUTime;
4722 mCurStepCpuSystemTime += totalSTime;
4723 mCurStepStatUserTime += statUserTime;
4724 mCurStepStatSystemTime += statSystemTime;
4725 mCurStepStatIOWaitTime += statIOWaitTime;
4726 mCurStepStatIrqTime += statIrqTime;
4727 mCurStepStatSoftIrqTime += statSoftIrqTime;
4728 mCurStepStatIdleTime += statIdleTime;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004729 }
4730
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004731 public void noteProcessDiedLocked(int uid, int pid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004732 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004733 Uid u = mUidStats.get(uid);
4734 if (u != null) {
4735 u.mPids.remove(pid);
4736 }
4737 }
4738
4739 public long getProcessWakeTime(int uid, int pid, long realtime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004740 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004741 Uid u = mUidStats.get(uid);
4742 if (u != null) {
4743 Uid.Pid p = u.mPids.get(pid);
4744 if (p != null) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004745 return p.mWakeSumMs + (p.mWakeNesting > 0 ? (realtime - p.mWakeStartMs) : 0);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004746 }
4747 }
4748 return 0;
4749 }
4750
Dianne Hackborn287952c2010-09-22 22:34:31 -07004751 public void reportExcessiveCpuLocked(int uid, String proc, long overTime, long usedTime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004752 uid = mapUid(uid);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004753 Uid u = mUidStats.get(uid);
4754 if (u != null) {
4755 u.reportExcessiveCpuLocked(proc, overTime, usedTime);
4756 }
4757 }
4758
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004759 int mSensorNesting;
4760
4761 public void noteStartSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004762 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004763 final long elapsedRealtime = mClocks.elapsedRealtime();
4764 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004765 if (mSensorNesting == 0) {
4766 mHistoryCur.states |= HistoryItem.STATE_SENSOR_ON_FLAG;
4767 if (DEBUG_HISTORY) Slog.v(TAG, "Start sensor to: "
4768 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004769 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004770 }
4771 mSensorNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004772 getUidStatsLocked(uid).noteStartSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004773 }
4774
4775 public void noteStopSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004776 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004777 final long elapsedRealtime = mClocks.elapsedRealtime();
4778 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004779 mSensorNesting--;
4780 if (mSensorNesting == 0) {
4781 mHistoryCur.states &= ~HistoryItem.STATE_SENSOR_ON_FLAG;
4782 if (DEBUG_HISTORY) Slog.v(TAG, "Stop sensor to: "
4783 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004784 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004785 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004786 getUidStatsLocked(uid).noteStopSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004787 }
4788
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004789 int mGpsNesting;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004790
Narayan Kamath32684dd2018-01-08 17:32:51 +00004791 public void noteGpsChangedLocked(WorkSource oldWs, WorkSource newWs) {
4792 for (int i = 0; i < newWs.size(); ++i) {
4793 noteStartGpsLocked(newWs.get(i), null);
4794 }
4795
4796 for (int i = 0; i < oldWs.size(); ++i) {
4797 noteStopGpsLocked((oldWs.get(i)), null);
4798 }
4799
4800 List<WorkChain>[] wcs = WorkSource.diffChains(oldWs, newWs);
4801 if (wcs != null) {
4802 if (wcs[0] != null) {
4803 final List<WorkChain> newChains = wcs[0];
4804 for (int i = 0; i < newChains.size(); ++i) {
4805 noteStartGpsLocked(-1, newChains.get(i));
4806 }
4807 }
4808
4809 if (wcs[1] != null) {
4810 final List<WorkChain> goneChains = wcs[1];
4811 for (int i = 0; i < goneChains.size(); ++i) {
4812 noteStopGpsLocked(-1, goneChains.get(i));
4813 }
4814 }
4815 }
4816 }
4817
4818 private void noteStartGpsLocked(int uid, WorkChain workChain) {
4819 uid = getAttributionUid(uid, workChain);
Joe Onoratoabded112016-02-08 16:49:39 -08004820 final long elapsedRealtime = mClocks.elapsedRealtime();
4821 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004822 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004823 mHistoryCur.states |= HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004824 if (DEBUG_HISTORY) Slog.v(TAG, "Start GPS to: "
4825 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004826 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004827 }
4828 mGpsNesting++;
Narayan Kamath32684dd2018-01-08 17:32:51 +00004829
4830 if (workChain == null) {
Bookatz90867622018-01-31 15:05:57 -08004831 StatsLog.write_non_chained(StatsLog.GPS_SCAN_STATE_CHANGED, uid, null,
4832 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004833 } else {
4834 StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004835 workChain.getUids(), workChain.getTags(),
4836 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004837 }
4838
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004839 getUidStatsLocked(uid).noteStartGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004840 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004841
Narayan Kamath32684dd2018-01-08 17:32:51 +00004842 private void noteStopGpsLocked(int uid, WorkChain workChain) {
4843 uid = getAttributionUid(uid, workChain);
Joe Onoratoabded112016-02-08 16:49:39 -08004844 final long elapsedRealtime = mClocks.elapsedRealtime();
4845 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004846 mGpsNesting--;
4847 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004848 mHistoryCur.states &= ~HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004849 if (DEBUG_HISTORY) Slog.v(TAG, "Stop GPS to: "
4850 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004851 addHistoryRecordLocked(elapsedRealtime, uptime);
Siddharth Ray78ccaf52017-12-23 16:16:21 -08004852 stopAllGpsSignalQualityTimersLocked(-1);
4853 mGpsSignalQualityBin = -1;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004854 }
Narayan Kamath32684dd2018-01-08 17:32:51 +00004855
4856 if (workChain == null) {
Bookatz90867622018-01-31 15:05:57 -08004857 StatsLog.write_non_chained(StatsLog.GPS_SCAN_STATE_CHANGED, uid, null,
4858 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004859 } else {
4860 StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED, workChain.getUids(),
Bookatz90867622018-01-31 15:05:57 -08004861 workChain.getTags(), StatsLog.GPS_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004862 }
4863
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004864 getUidStatsLocked(uid).noteStopGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004865 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07004866
Siddharth Ray78ccaf52017-12-23 16:16:21 -08004867 public void noteGpsSignalQualityLocked(int signalLevel) {
4868 if (mGpsNesting == 0) {
4869 return;
4870 }
4871 if (signalLevel < 0 || signalLevel >= GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS) {
4872 stopAllGpsSignalQualityTimersLocked(-1);
4873 return;
4874 }
4875 final long elapsedRealtime = mClocks.elapsedRealtime();
4876 final long uptime = mClocks.uptimeMillis();
4877 if (mGpsSignalQualityBin != signalLevel) {
4878 if (mGpsSignalQualityBin >= 0) {
4879 mGpsSignalQualityTimer[mGpsSignalQualityBin].stopRunningLocked(elapsedRealtime);
4880 }
4881 if(!mGpsSignalQualityTimer[signalLevel].isRunningLocked()) {
4882 mGpsSignalQualityTimer[signalLevel].startRunningLocked(elapsedRealtime);
4883 }
4884 mHistoryCur.states2 = (mHistoryCur.states2&~HistoryItem.STATE2_GPS_SIGNAL_QUALITY_MASK)
4885 | (signalLevel << HistoryItem.STATE2_GPS_SIGNAL_QUALITY_SHIFT);
4886 addHistoryRecordLocked(elapsedRealtime, uptime);
4887 mGpsSignalQualityBin = signalLevel;
4888 }
4889 return;
4890 }
4891
Andreas Gampe3f24e692018-02-05 13:24:28 -08004892 @GuardedBy("this")
Jeff Browne95c3cd2014-05-02 16:59:26 -07004893 public void noteScreenStateLocked(int state) {
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004894 state = mPretendScreenOff ? Display.STATE_OFF : state;
Santos Cordone94f0502017-02-24 12:31:20 -08004895
4896 // Battery stats relies on there being 4 states. To accommodate this, new states beyond the
4897 // original 4 are mapped to one of the originals.
4898 if (state > MAX_TRACKED_SCREEN_STATE) {
4899 switch (state) {
4900 case Display.STATE_VR:
4901 state = Display.STATE_ON;
4902 break;
4903 default:
4904 Slog.wtf(TAG, "Unknown screen state (not mapped): " + state);
4905 break;
4906 }
4907 }
4908
Jeff Browne95c3cd2014-05-02 16:59:26 -07004909 if (mScreenState != state) {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08004910 recordDailyStatsIfNeededLocked(true);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004911 final int oldState = mScreenState;
4912 mScreenState = state;
4913 if (DEBUG) Slog.v(TAG, "Screen state: oldState=" + Display.stateToString(oldState)
4914 + ", newState=" + Display.stateToString(state));
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004915
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004916 if (state != Display.STATE_UNKNOWN) {
4917 int stepState = state-1;
Santos Cordone94f0502017-02-24 12:31:20 -08004918 if ((stepState & STEP_LEVEL_MODE_SCREEN_STATE) == stepState) {
4919 mModStepMode |= (mCurStepMode & STEP_LEVEL_MODE_SCREEN_STATE) ^ stepState;
4920 mCurStepMode = (mCurStepMode & ~STEP_LEVEL_MODE_SCREEN_STATE) | stepState;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004921 } else {
4922 Slog.wtf(TAG, "Unexpected screen state: " + state);
4923 }
4924 }
4925
Mike Mac2f518a2017-09-19 16:06:03 -07004926 final long elapsedRealtime = mClocks.elapsedRealtime();
4927 final long uptime = mClocks.uptimeMillis();
4928
4929 boolean updateHistory = false;
4930 if (isScreenDoze(state)) {
4931 mHistoryCur.states |= HistoryItem.STATE_SCREEN_DOZE_FLAG;
4932 mScreenDozeTimer.startRunningLocked(elapsedRealtime);
4933 updateHistory = true;
4934 } else if (isScreenDoze(oldState)) {
4935 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_DOZE_FLAG;
4936 mScreenDozeTimer.stopRunningLocked(elapsedRealtime);
4937 updateHistory = true;
4938 }
4939 if (isScreenOn(state)) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07004940 mHistoryCur.states |= HistoryItem.STATE_SCREEN_ON_FLAG;
4941 if (DEBUG_HISTORY) Slog.v(TAG, "Screen on to: "
4942 + Integer.toHexString(mHistoryCur.states));
Jeff Browne95c3cd2014-05-02 16:59:26 -07004943 mScreenOnTimer.startRunningLocked(elapsedRealtime);
4944 if (mScreenBrightnessBin >= 0) {
4945 mScreenBrightnessTimer[mScreenBrightnessBin].startRunningLocked(elapsedRealtime);
4946 }
Mike Mac2f518a2017-09-19 16:06:03 -07004947 updateHistory = true;
4948 } else if (isScreenOn(oldState)) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07004949 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_ON_FLAG;
4950 if (DEBUG_HISTORY) Slog.v(TAG, "Screen off to: "
4951 + Integer.toHexString(mHistoryCur.states));
Jeff Browne95c3cd2014-05-02 16:59:26 -07004952 mScreenOnTimer.stopRunningLocked(elapsedRealtime);
4953 if (mScreenBrightnessBin >= 0) {
4954 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
4955 }
Mike Mac2f518a2017-09-19 16:06:03 -07004956 updateHistory = true;
4957 }
4958 if (updateHistory) {
4959 if (DEBUG_HISTORY) Slog.v(TAG, "Screen state to: "
4960 + Display.stateToString(state));
4961 addHistoryRecordLocked(elapsedRealtime, uptime);
4962 }
Sudheer Shankac57729a2018-02-09 15:44:42 -08004963 mExternalSync.scheduleCpuSyncDueToScreenStateChange(
4964 mOnBatteryTimeBase.isRunning(), mOnBatteryScreenOffTimeBase.isRunning());
Mike Mac2f518a2017-09-19 16:06:03 -07004965 if (isScreenOn(state)) {
4966 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), state,
4967 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
4968 // Fake a wake lock, so we consider the device waked as long as the screen is on.
Narayan Kamath81822022017-12-08 11:56:01 +00004969 noteStartWakeLocked(-1, -1, null, "screen", null, WAKE_TYPE_PARTIAL, false,
Mike Mac2f518a2017-09-19 16:06:03 -07004970 elapsedRealtime, uptime);
4971 } else if (isScreenOn(oldState)) {
Narayan Kamath81822022017-12-08 11:56:01 +00004972 noteStopWakeLocked(-1, -1, null, "screen", "screen", WAKE_TYPE_PARTIAL,
Jeff Browne95c3cd2014-05-02 16:59:26 -07004973 elapsedRealtime, uptime);
Mike Mac2f518a2017-09-19 16:06:03 -07004974 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), state,
Joe Onoratoabded112016-02-08 16:49:39 -08004975 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
Mike Mac2f518a2017-09-19 16:06:03 -07004976 }
4977 // Update discharge amounts.
4978 if (mOnBatteryInternal) {
4979 updateDischargeScreenLevelsLocked(oldState, state);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08004980 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07004981 }
4982 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004983
Mathew Inwoodc185f082018-08-20 14:28:54 +01004984 @UnsupportedAppUsage
Dianne Hackborn617f8772009-03-31 15:04:46 -07004985 public void noteScreenBrightnessLocked(int brightness) {
4986 // Bin the brightness.
4987 int bin = brightness / (256/NUM_SCREEN_BRIGHTNESS_BINS);
4988 if (bin < 0) bin = 0;
4989 else if (bin >= NUM_SCREEN_BRIGHTNESS_BINS) bin = NUM_SCREEN_BRIGHTNESS_BINS-1;
4990 if (mScreenBrightnessBin != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08004991 final long elapsedRealtime = mClocks.elapsedRealtime();
4992 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004993 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_BRIGHTNESS_MASK)
4994 | (bin << HistoryItem.STATE_BRIGHTNESS_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004995 if (DEBUG_HISTORY) Slog.v(TAG, "Screen brightness " + bin + " to: "
4996 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004997 addHistoryRecordLocked(elapsedRealtime, uptime);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004998 if (mScreenState == Display.STATE_ON) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07004999 if (mScreenBrightnessBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005000 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07005001 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005002 mScreenBrightnessTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07005003 }
5004 mScreenBrightnessBin = bin;
5005 }
5006 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005007
Mathew Inwoodc185f082018-08-20 14:28:54 +01005008 @UnsupportedAppUsage
Dianne Hackborn617f8772009-03-31 15:04:46 -07005009 public void noteUserActivityLocked(int uid, int event) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08005010 if (mOnBatteryInternal) {
5011 uid = mapUid(uid);
5012 getUidStatsLocked(uid).noteUserActivityLocked(event);
5013 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005014 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005015
Dianne Hackborn280a64e2015-07-13 14:48:08 -07005016 public void noteWakeUpLocked(String reason, int reasonUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005017 final long elapsedRealtime = mClocks.elapsedRealtime();
5018 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn280a64e2015-07-13 14:48:08 -07005019 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SCREEN_WAKE_UP,
5020 reason, reasonUid);
5021 }
5022
Jeff Browne95c3cd2014-05-02 16:59:26 -07005023 public void noteInteractiveLocked(boolean interactive) {
5024 if (mInteractive != interactive) {
Joe Onoratoabded112016-02-08 16:49:39 -08005025 final long elapsedRealtime = mClocks.elapsedRealtime();
Jeff Browne95c3cd2014-05-02 16:59:26 -07005026 mInteractive = interactive;
5027 if (DEBUG) Slog.v(TAG, "Interactive: " + interactive);
5028 if (interactive) {
5029 mInteractiveTimer.startRunningLocked(elapsedRealtime);
5030 } else {
5031 mInteractiveTimer.stopRunningLocked(elapsedRealtime);
5032 }
5033 }
5034 }
5035
Dianne Hackborn1e01d162014-12-04 17:46:42 -08005036 public void noteConnectivityChangedLocked(int type, String extra) {
Joe Onoratoabded112016-02-08 16:49:39 -08005037 final long elapsedRealtime = mClocks.elapsedRealtime();
5038 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08005039 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_CONNECTIVITY_CHANGED,
5040 extra, type);
5041 mNumConnectivityChange++;
5042 }
5043
Adam Lesinski5f056f62016-07-14 16:56:08 -07005044 private void noteMobileRadioApWakeupLocked(final long elapsedRealtimeMillis,
5045 final long uptimeMillis, int uid) {
5046 uid = mapUid(uid);
5047 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
5048 uid);
5049 getUidStatsLocked(uid).noteMobileRadioApWakeupLocked();
5050 }
5051
Adam Lesinski14ae39a2017-05-26 11:50:40 -07005052 /**
5053 * Updates the radio power state and returns true if an external stats collection should occur.
5054 */
5055 public boolean noteMobileRadioPowerStateLocked(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005056 final long elapsedRealtime = mClocks.elapsedRealtime();
5057 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005058 if (mMobileRadioPowerState != powerState) {
5059 long realElapsedRealtimeMs;
5060 final boolean active =
5061 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
5062 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
5063 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07005064 if (uid > 0) {
5065 noteMobileRadioApWakeupLocked(elapsedRealtime, uptime, uid);
5066 }
5067
Adam Lesinski9acfd812016-04-19 18:29:50 -07005068 mMobileRadioActiveStartTime = realElapsedRealtimeMs = timestampNs / (1000 * 1000);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005069 mHistoryCur.states |= HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
5070 } else {
5071 realElapsedRealtimeMs = timestampNs / (1000*1000);
Dianne Hackbornf7097a52014-05-13 09:56:14 -07005072 long lastUpdateTimeMs = mMobileRadioActiveStartTime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005073 if (realElapsedRealtimeMs < lastUpdateTimeMs) {
5074 Slog.wtf(TAG, "Data connection inactive timestamp " + realElapsedRealtimeMs
5075 + " is before start time " + lastUpdateTimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005076 realElapsedRealtimeMs = elapsedRealtime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005077 } else if (realElapsedRealtimeMs < elapsedRealtime) {
5078 mMobileRadioActiveAdjustedTime.addCountLocked(elapsedRealtime
5079 - realElapsedRealtimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005080 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005081 mHistoryCur.states &= ~HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
5082 }
5083 if (DEBUG_HISTORY) Slog.v(TAG, "Mobile network active " + active + " to: "
5084 + Integer.toHexString(mHistoryCur.states));
5085 addHistoryRecordLocked(elapsedRealtime, uptime);
5086 mMobileRadioPowerState = powerState;
Yangster-mac4c7255f2018-05-07 13:41:47 -07005087 StatsLog.write_non_chained(StatsLog.MOBILE_RADIO_POWER_STATE_CHANGED, uid, null,
5088 powerState);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005089 if (active) {
5090 mMobileRadioActiveTimer.startRunningLocked(elapsedRealtime);
5091 mMobileRadioActivePerAppTimer.startRunningLocked(elapsedRealtime);
5092 } else {
5093 mMobileRadioActiveTimer.stopRunningLocked(realElapsedRealtimeMs);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005094 mMobileRadioActivePerAppTimer.stopRunningLocked(realElapsedRealtimeMs);
Adam Lesinski14ae39a2017-05-26 11:50:40 -07005095 // Tell the caller to collect radio network/power stats.
5096 return true;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08005097 }
Dianne Hackborne13c4c02014-02-11 17:18:35 -08005098 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -07005099 return false;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08005100 }
5101
Adam Lesinski14ae39a2017-05-26 11:50:40 -07005102 public void notePowerSaveModeLocked(boolean enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005103 if (mPowerSaveModeEnabled != enabled) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07005104 int stepState = enabled ? STEP_LEVEL_MODE_POWER_SAVE : 0;
5105 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_POWER_SAVE) ^ stepState;
5106 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_POWER_SAVE) | stepState;
Joe Onoratoabded112016-02-08 16:49:39 -08005107 final long elapsedRealtime = mClocks.elapsedRealtime();
5108 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005109 mPowerSaveModeEnabled = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005110 if (enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005111 mHistoryCur.states2 |= HistoryItem.STATE2_POWER_SAVE_FLAG;
5112 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode enabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005113 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005114 mPowerSaveModeEnabledTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005115 } else {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005116 mHistoryCur.states2 &= ~HistoryItem.STATE2_POWER_SAVE_FLAG;
5117 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode disabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005118 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005119 mPowerSaveModeEnabledTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005120 }
5121 addHistoryRecordLocked(elapsedRealtime, uptime);
Bookatz90867622018-01-31 15:05:57 -08005122 StatsLog.write(StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED, enabled ?
5123 StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED__STATE__ON :
5124 StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED__STATE__OFF);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005125 }
5126 }
5127
Bookatzddccf0a2017-11-28 16:48:14 -08005128 public void noteDeviceIdleModeLocked(final int mode, String activeReason, int activeUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005129 final long elapsedRealtime = mClocks.elapsedRealtime();
5130 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005131 boolean nowIdling = mode == DEVICE_IDLE_MODE_DEEP;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005132 if (mDeviceIdling && !nowIdling && activeReason == null) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005133 // We don't go out of general idling mode until explicitly taken out of
5134 // device idle through going active or significant motion.
5135 nowIdling = true;
5136 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005137 boolean nowLightIdling = mode == DEVICE_IDLE_MODE_LIGHT;
5138 if (mDeviceLightIdling && !nowLightIdling && !nowIdling && activeReason == null) {
5139 // We don't go out of general light idling mode until explicitly taken out of
5140 // device idle through going active or significant motion.
5141 nowLightIdling = true;
5142 }
5143 if (activeReason != null && (mDeviceIdling || mDeviceLightIdling)) {
5144 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_ACTIVE,
5145 activeReason, activeUid);
5146 }
Bookatzddccf0a2017-11-28 16:48:14 -08005147 if (mDeviceIdling != nowIdling || mDeviceLightIdling != nowLightIdling) {
5148 int statsmode;
5149 if (nowIdling) statsmode = DEVICE_IDLE_MODE_DEEP;
5150 else if (nowLightIdling) statsmode = DEVICE_IDLE_MODE_LIGHT;
5151 else statsmode = DEVICE_IDLE_MODE_OFF;
5152 StatsLog.write(StatsLog.DEVICE_IDLING_MODE_STATE_CHANGED, statsmode);
5153 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005154 if (mDeviceIdling != nowIdling) {
5155 mDeviceIdling = nowIdling;
5156 int stepState = nowIdling ? STEP_LEVEL_MODE_DEVICE_IDLE : 0;
5157 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_DEVICE_IDLE) ^ stepState;
5158 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_DEVICE_IDLE) | stepState;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005159 if (nowIdling) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005160 mDeviceIdlingTimer.startRunningLocked(elapsedRealtime);
5161 } else {
5162 mDeviceIdlingTimer.stopRunningLocked(elapsedRealtime);
5163 }
5164 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005165 if (mDeviceLightIdling != nowLightIdling) {
5166 mDeviceLightIdling = nowLightIdling;
5167 if (nowLightIdling) {
5168 mDeviceLightIdlingTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005169 } else {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005170 mDeviceLightIdlingTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005171 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005172 }
5173 if (mDeviceIdleMode != mode) {
5174 mHistoryCur.states2 = (mHistoryCur.states2 & ~HistoryItem.STATE2_DEVICE_IDLE_MASK)
5175 | (mode << HistoryItem.STATE2_DEVICE_IDLE_SHIFT);
5176 if (DEBUG_HISTORY) Slog.v(TAG, "Device idle mode changed to: "
5177 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005178 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005179 long lastDuration = elapsedRealtime - mLastIdleTimeStart;
5180 mLastIdleTimeStart = elapsedRealtime;
5181 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
5182 if (lastDuration > mLongestLightIdleTime) {
5183 mLongestLightIdleTime = lastDuration;
5184 }
5185 mDeviceIdleModeLightTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005186 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005187 if (lastDuration > mLongestFullIdleTime) {
5188 mLongestFullIdleTime = lastDuration;
5189 }
5190 mDeviceIdleModeFullTimer.stopRunningLocked(elapsedRealtime);
5191 }
5192 if (mode == DEVICE_IDLE_MODE_LIGHT) {
5193 mDeviceIdleModeLightTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005194 } else if (mode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005195 mDeviceIdleModeFullTimer.startRunningLocked(elapsedRealtime);
5196 }
5197 mDeviceIdleMode = mode;
Bookatzddccf0a2017-11-28 16:48:14 -08005198 StatsLog.write(StatsLog.DEVICE_IDLE_MODE_STATE_CHANGED, mode);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005199 }
5200 }
5201
Dianne Hackborn3accca02013-09-20 09:32:11 -07005202 public void notePackageInstalledLocked(String pkgName, long versionCode) {
Joe Onoratoabded112016-02-08 16:49:39 -08005203 final long elapsedRealtime = mClocks.elapsedRealtime();
5204 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3accca02013-09-20 09:32:11 -07005205 // XXX need to figure out what to do with long version codes.
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005206 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_INSTALLED,
Dianne Hackborn3accca02013-09-20 09:32:11 -07005207 pkgName, (int)versionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005208 PackageChange pc = new PackageChange();
5209 pc.mPackageName = pkgName;
5210 pc.mUpdate = true;
5211 pc.mVersionCode = versionCode;
5212 addPackageChange(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005213 }
5214
5215 public void notePackageUninstalledLocked(String pkgName) {
Joe Onoratoabded112016-02-08 16:49:39 -08005216 final long elapsedRealtime = mClocks.elapsedRealtime();
5217 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005218 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_UNINSTALLED,
5219 pkgName, 0);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005220 PackageChange pc = new PackageChange();
5221 pc.mPackageName = pkgName;
5222 pc.mUpdate = true;
5223 addPackageChange(pc);
5224 }
5225
5226 private void addPackageChange(PackageChange pc) {
5227 if (mDailyPackageChanges == null) {
5228 mDailyPackageChanges = new ArrayList<>();
5229 }
5230 mDailyPackageChanges.add(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005231 }
5232
Siddharth Ray78ccaf52017-12-23 16:16:21 -08005233 void stopAllGpsSignalQualityTimersLocked(int except) {
5234 final long elapsedRealtime = mClocks.elapsedRealtime();
5235 for (int i = 0; i < GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
5236 if (i == except) {
5237 continue;
5238 }
5239 while (mGpsSignalQualityTimer[i].isRunningLocked()) {
5240 mGpsSignalQualityTimer[i].stopRunningLocked(elapsedRealtime);
5241 }
5242 }
5243 }
5244
Mathew Inwoodc185f082018-08-20 14:28:54 +01005245 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005246 public void notePhoneOnLocked() {
5247 if (!mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005248 final long elapsedRealtime = mClocks.elapsedRealtime();
5249 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005250 mHistoryCur.states2 |= HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005251 if (DEBUG_HISTORY) Slog.v(TAG, "Phone on to: "
5252 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005253 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005254 mPhoneOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005255 mPhoneOnTimer.startRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005256 }
5257 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005258
Mathew Inwoodc185f082018-08-20 14:28:54 +01005259 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005260 public void notePhoneOffLocked() {
5261 if (mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005262 final long elapsedRealtime = mClocks.elapsedRealtime();
5263 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005264 mHistoryCur.states2 &= ~HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005265 if (DEBUG_HISTORY) Slog.v(TAG, "Phone off to: "
5266 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005267 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005268 mPhoneOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005269 mPhoneOnTimer.stopRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005270 }
5271 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07005272
Mike Mafbc01fc2018-04-02 10:28:28 -07005273 private void registerUsbStateReceiver(Context context) {
5274 final IntentFilter usbStateFilter = new IntentFilter();
5275 usbStateFilter.addAction(UsbManager.ACTION_USB_STATE);
5276 context.registerReceiver(new BroadcastReceiver() {
5277 @Override
5278 public void onReceive(Context context, Intent intent) {
5279 final boolean state = intent.getBooleanExtra(UsbManager.USB_CONNECTED, false);
5280 synchronized (BatteryStatsImpl.this) {
5281 noteUsbConnectionStateLocked(state);
5282 }
5283 }
5284 }, usbStateFilter);
5285 synchronized (this) {
5286 if (mUsbDataState == USB_DATA_UNKNOWN) {
5287 final Intent usbState = context.registerReceiver(null, usbStateFilter);
5288 final boolean initState = usbState != null && usbState.getBooleanExtra(
5289 UsbManager.USB_CONNECTED, false);
5290 noteUsbConnectionStateLocked(initState);
5291 }
5292 }
5293 }
5294
5295 private void noteUsbConnectionStateLocked(boolean connected) {
5296 int newState = connected ? USB_DATA_CONNECTED : USB_DATA_DISCONNECTED;
Mike Ma926a97c2018-03-25 02:32:35 -07005297 if (mUsbDataState != newState) {
5298 mUsbDataState = newState;
5299 if (connected) {
5300 mHistoryCur.states2 |= HistoryItem.STATE2_USB_DATA_LINK_FLAG;
5301 } else {
5302 mHistoryCur.states2 &= ~HistoryItem.STATE2_USB_DATA_LINK_FLAG;
5303 }
5304 addHistoryRecordLocked(mClocks.elapsedRealtime(), mClocks.uptimeMillis());
5305 }
5306 }
5307
Dianne Hackborn3251b902014-06-20 14:40:53 -07005308 void stopAllPhoneSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005309 final long elapsedRealtime = mClocks.elapsedRealtime();
Wink Saville52840902011-02-18 12:40:47 -08005310 for (int i = 0; i < SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005311 if (i == except) {
5312 continue;
5313 }
5314 while (mPhoneSignalStrengthsTimer[i].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005315 mPhoneSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005316 }
5317 }
5318 }
5319
Dianne Hackborne4a59512010-12-07 11:08:07 -08005320 private int fixPhoneServiceState(int state, int signalBin) {
5321 if (mPhoneSimStateRaw == TelephonyManager.SIM_STATE_ABSENT) {
5322 // In this case we will always be STATE_OUT_OF_SERVICE, so need
5323 // to infer that we are scanning from other data.
5324 if (state == ServiceState.STATE_OUT_OF_SERVICE
Wink Saville52840902011-02-18 12:40:47 -08005325 && signalBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005326 state = ServiceState.STATE_IN_SERVICE;
5327 }
5328 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005329
Dianne Hackborne4a59512010-12-07 11:08:07 -08005330 return state;
5331 }
5332
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005333 private void updateAllPhoneStateLocked(int state, int simState, int strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005334 boolean scanning = false;
5335 boolean newHistory = false;
5336
5337 mPhoneServiceStateRaw = state;
5338 mPhoneSimStateRaw = simState;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005339 mPhoneSignalStrengthBinRaw = strengthBin;
5340
Joe Onoratoabded112016-02-08 16:49:39 -08005341 final long elapsedRealtime = mClocks.elapsedRealtime();
5342 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne4a59512010-12-07 11:08:07 -08005343
5344 if (simState == TelephonyManager.SIM_STATE_ABSENT) {
5345 // In this case we will always be STATE_OUT_OF_SERVICE, so need
5346 // to infer that we are scanning from other data.
5347 if (state == ServiceState.STATE_OUT_OF_SERVICE
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005348 && strengthBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005349 state = ServiceState.STATE_IN_SERVICE;
5350 }
5351 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005352
5353 // If the phone is powered off, stop all timers.
5354 if (state == ServiceState.STATE_POWER_OFF) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005355 strengthBin = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -07005356
Dianne Hackborne4a59512010-12-07 11:08:07 -08005357 // If we are in service, make sure the correct signal string timer is running.
5358 } else if (state == ServiceState.STATE_IN_SERVICE) {
5359 // Bin will be changed below.
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005360
5361 // If we're out of service, we are in the lowest signal strength
5362 // bin and have the scanning bit set.
Amith Yamasanif37447b2009-10-08 18:28:01 -07005363 } else if (state == ServiceState.STATE_OUT_OF_SERVICE) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005364 scanning = true;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005365 strengthBin = SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN;
Amith Yamasanif37447b2009-10-08 18:28:01 -07005366 if (!mPhoneSignalScanningTimer.isRunningLocked()) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005367 mHistoryCur.states |= HistoryItem.STATE_PHONE_SCANNING_FLAG;
Dianne Hackborne4a59512010-12-07 11:08:07 -08005368 newHistory = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005369 if (DEBUG_HISTORY) Slog.v(TAG, "Phone started scanning to: "
5370 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005371 mPhoneSignalScanningTimer.startRunningLocked(elapsedRealtime);
Amith Yamasanif37447b2009-10-08 18:28:01 -07005372 }
5373 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005374
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005375 if (!scanning) {
5376 // If we are no longer scanning, then stop the scanning timer.
5377 if (mPhoneSignalScanningTimer.isRunningLocked()) {
5378 mHistoryCur.states &= ~HistoryItem.STATE_PHONE_SCANNING_FLAG;
5379 if (DEBUG_HISTORY) Slog.v(TAG, "Phone stopped scanning to: "
5380 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08005381 newHistory = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005382 mPhoneSignalScanningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005383 }
5384 }
5385
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005386 if (mPhoneServiceState != state) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005387 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_STATE_MASK)
5388 | (state << HistoryItem.STATE_PHONE_STATE_SHIFT);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005389 if (DEBUG_HISTORY) Slog.v(TAG, "Phone state " + state + " to: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005390 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08005391 newHistory = true;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005392 mPhoneServiceState = state;
5393 }
Dianne Hackborne4a59512010-12-07 11:08:07 -08005394
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005395 if (mPhoneSignalStrengthBin != strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005396 if (mPhoneSignalStrengthBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005397 mPhoneSignalStrengthsTimer[mPhoneSignalStrengthBin].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005398 elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005399 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005400 if (strengthBin >= 0) {
5401 if (!mPhoneSignalStrengthsTimer[strengthBin].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005402 mPhoneSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005403 }
Dianne Hackborn3251b902014-06-20 14:40:53 -07005404 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_MASK)
5405 | (strengthBin << HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_SHIFT);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005406 if (DEBUG_HISTORY) Slog.v(TAG, "Signal strength " + strengthBin + " to: "
Dianne Hackborne4a59512010-12-07 11:08:07 -08005407 + Integer.toHexString(mHistoryCur.states));
5408 newHistory = true;
Bookatze5885242017-10-24 20:10:31 -07005409 StatsLog.write(StatsLog.PHONE_SIGNAL_STRENGTH_CHANGED, strengthBin);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005410 } else {
Dianne Hackborn3251b902014-06-20 14:40:53 -07005411 stopAllPhoneSignalStrengthTimersLocked(-1);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005412 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005413 mPhoneSignalStrengthBin = strengthBin;
Dianne Hackborne4a59512010-12-07 11:08:07 -08005414 }
5415
5416 if (newHistory) {
Dianne Hackborn40c87252014-03-19 16:55:40 -07005417 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005418 }
5419 }
5420
5421 /**
5422 * Telephony stack updates the phone state.
5423 * @param state phone state from ServiceState.getState()
5424 */
5425 public void notePhoneStateLocked(int state, int simState) {
5426 updateAllPhoneStateLocked(state, simState, mPhoneSignalStrengthBinRaw);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07005427 }
5428
Mathew Inwoodc185f082018-08-20 14:28:54 +01005429 @UnsupportedAppUsage
Wink Savillee9b06d72009-05-18 21:47:50 -07005430 public void notePhoneSignalStrengthLocked(SignalStrength signalStrength) {
Dianne Hackborn627bba72009-03-24 22:32:56 -07005431 // Bin the strength.
Wink Saville52840902011-02-18 12:40:47 -08005432 int bin = signalStrength.getLevel();
Dianne Hackborne4a59512010-12-07 11:08:07 -08005433 updateAllPhoneStateLocked(mPhoneServiceStateRaw, mPhoneSimStateRaw, bin);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005434 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005435
Mathew Inwoodc185f082018-08-20 14:28:54 +01005436 @UnsupportedAppUsage
Dianne Hackborn627bba72009-03-24 22:32:56 -07005437 public void notePhoneDataConnectionStateLocked(int dataType, boolean hasData) {
Tej Singheee317b2018-03-07 19:28:05 -08005438 // BatteryStats uses 0 to represent no network type.
5439 // Telephony does not have a concept of no network type, and uses 0 to represent unknown.
5440 // Unknown is included in DATA_CONNECTION_OTHER.
Dianne Hackborn627bba72009-03-24 22:32:56 -07005441 int bin = DATA_CONNECTION_NONE;
5442 if (hasData) {
Tej Singheee317b2018-03-07 19:28:05 -08005443 if (dataType > 0 && dataType <= TelephonyManager.MAX_NETWORK_TYPE) {
5444 bin = dataType;
5445 } else {
5446 bin = DATA_CONNECTION_OTHER;
Dianne Hackborn627bba72009-03-24 22:32:56 -07005447 }
5448 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07005449 if (DEBUG) Log.i(TAG, "Phone Data Connection -> " + dataType + " = " + hasData);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005450 if (mPhoneDataConnectionType != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005451 final long elapsedRealtime = mClocks.elapsedRealtime();
5452 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005453 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_DATA_CONNECTION_MASK)
5454 | (bin << HistoryItem.STATE_DATA_CONNECTION_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005455 if (DEBUG_HISTORY) Slog.v(TAG, "Data connection " + bin + " to: "
5456 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005457 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005458 if (mPhoneDataConnectionType >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005459 mPhoneDataConnectionsTimer[mPhoneDataConnectionType].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005460 elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005461 }
5462 mPhoneDataConnectionType = bin;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005463 mPhoneDataConnectionsTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005464 }
5465 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005466
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005467 public void noteWifiOnLocked() {
The Android Open Source Project10592532009-03-18 17:39:46 -07005468 if (!mWifiOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005469 final long elapsedRealtime = mClocks.elapsedRealtime();
5470 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005471 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005472 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI on to: "
5473 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005474 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005475 mWifiOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005476 mWifiOnTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005477 scheduleSyncExternalStatsLocked("wifi-off", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07005478 }
5479 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005480
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005481 public void noteWifiOffLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08005482 final long elapsedRealtime = mClocks.elapsedRealtime();
5483 final long uptime = mClocks.uptimeMillis();
The Android Open Source Project10592532009-03-18 17:39:46 -07005484 if (mWifiOn) {
Dianne Hackborn3251b902014-06-20 14:40:53 -07005485 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005486 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI off to: "
5487 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005488 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005489 mWifiOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005490 mWifiOnTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005491 scheduleSyncExternalStatsLocked("wifi-on", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07005492 }
5493 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005494
Mathew Inwoodc185f082018-08-20 14:28:54 +01005495 @UnsupportedAppUsage
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005496 public void noteAudioOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005497 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005498 final long elapsedRealtime = mClocks.elapsedRealtime();
5499 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005500 if (mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005501 mHistoryCur.states |= HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005502 if (DEBUG_HISTORY) Slog.v(TAG, "Audio on to: "
5503 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005504 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005505 mAudioOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005506 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005507 mAudioOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005508 getUidStatsLocked(uid).noteAudioTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005509 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005510
Mathew Inwoodc185f082018-08-20 14:28:54 +01005511 @UnsupportedAppUsage
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005512 public void noteAudioOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005513 if (mAudioOnNesting == 0) {
5514 return;
5515 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08005516 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005517 final long elapsedRealtime = mClocks.elapsedRealtime();
5518 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005519 if (--mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005520 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005521 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
5522 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005523 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005524 mAudioOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005525 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005526 getUidStatsLocked(uid).noteAudioTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005527 }
5528
Mathew Inwoodc185f082018-08-20 14:28:54 +01005529 @UnsupportedAppUsage
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005530 public void noteVideoOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005531 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005532 final long elapsedRealtime = mClocks.elapsedRealtime();
5533 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005534 if (mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005535 mHistoryCur.states2 |= HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005536 if (DEBUG_HISTORY) Slog.v(TAG, "Video on to: "
5537 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005538 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005539 mVideoOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005540 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005541 mVideoOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005542 getUidStatsLocked(uid).noteVideoTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005543 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005544
Mathew Inwoodc185f082018-08-20 14:28:54 +01005545 @UnsupportedAppUsage
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005546 public void noteVideoOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005547 if (mVideoOnNesting == 0) {
5548 return;
5549 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08005550 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005551 final long elapsedRealtime = mClocks.elapsedRealtime();
5552 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005553 if (--mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005554 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005555 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
5556 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005557 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005558 mVideoOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005559 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005560 getUidStatsLocked(uid).noteVideoTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005561 }
5562
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005563 public void noteResetAudioLocked() {
5564 if (mAudioOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005565 final long elapsedRealtime = mClocks.elapsedRealtime();
5566 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005567 mAudioOnNesting = 0;
5568 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
5569 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
5570 + Integer.toHexString(mHistoryCur.states));
5571 addHistoryRecordLocked(elapsedRealtime, uptime);
5572 mAudioOnTimer.stopAllRunningLocked(elapsedRealtime);
5573 for (int i=0; i<mUidStats.size(); i++) {
5574 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5575 uid.noteResetAudioLocked(elapsedRealtime);
5576 }
5577 }
5578 }
5579
5580 public void noteResetVideoLocked() {
5581 if (mVideoOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005582 final long elapsedRealtime = mClocks.elapsedRealtime();
5583 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005584 mAudioOnNesting = 0;
5585 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
5586 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
5587 + Integer.toHexString(mHistoryCur.states));
5588 addHistoryRecordLocked(elapsedRealtime, uptime);
5589 mVideoOnTimer.stopAllRunningLocked(elapsedRealtime);
5590 for (int i=0; i<mUidStats.size(); i++) {
5591 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5592 uid.noteResetVideoLocked(elapsedRealtime);
5593 }
5594 }
5595 }
5596
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005597 public void noteActivityResumedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005598 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005599 getUidStatsLocked(uid).noteActivityResumedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005600 }
5601
5602 public void noteActivityPausedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005603 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005604 getUidStatsLocked(uid).noteActivityPausedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005605 }
5606
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005607 public void noteVibratorOnLocked(int uid, long durationMillis) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005608 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005609 getUidStatsLocked(uid).noteVibratorOnLocked(durationMillis);
5610 }
5611
5612 public void noteVibratorOffLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005613 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005614 getUidStatsLocked(uid).noteVibratorOffLocked();
5615 }
5616
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005617 public void noteFlashlightOnLocked(int uid) {
5618 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005619 final long elapsedRealtime = mClocks.elapsedRealtime();
5620 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005621 if (mFlashlightOnNesting++ == 0) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005622 mHistoryCur.states2 |= HistoryItem.STATE2_FLASHLIGHT_FLAG;
5623 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight on to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005624 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005625 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005626 mFlashlightOnTimer.startRunningLocked(elapsedRealtime);
5627 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005628 getUidStatsLocked(uid).noteFlashlightTurnedOnLocked(elapsedRealtime);
5629 }
5630
5631 public void noteFlashlightOffLocked(int uid) {
5632 if (mFlashlightOnNesting == 0) {
5633 return;
5634 }
5635 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005636 final long elapsedRealtime = mClocks.elapsedRealtime();
5637 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005638 if (--mFlashlightOnNesting == 0) {
5639 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
5640 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
5641 + Integer.toHexString(mHistoryCur.states2));
5642 addHistoryRecordLocked(elapsedRealtime, uptime);
5643 mFlashlightOnTimer.stopRunningLocked(elapsedRealtime);
5644 }
5645 getUidStatsLocked(uid).noteFlashlightTurnedOffLocked(elapsedRealtime);
5646 }
5647
5648 public void noteCameraOnLocked(int uid) {
5649 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005650 final long elapsedRealtime = mClocks.elapsedRealtime();
5651 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005652 if (mCameraOnNesting++ == 0) {
5653 mHistoryCur.states2 |= HistoryItem.STATE2_CAMERA_FLAG;
5654 if (DEBUG_HISTORY) Slog.v(TAG, "Camera on to: "
5655 + Integer.toHexString(mHistoryCur.states2));
5656 addHistoryRecordLocked(elapsedRealtime, uptime);
5657 mCameraOnTimer.startRunningLocked(elapsedRealtime);
5658 }
5659 getUidStatsLocked(uid).noteCameraTurnedOnLocked(elapsedRealtime);
5660 }
5661
5662 public void noteCameraOffLocked(int uid) {
5663 if (mCameraOnNesting == 0) {
5664 return;
5665 }
5666 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005667 final long elapsedRealtime = mClocks.elapsedRealtime();
5668 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005669 if (--mCameraOnNesting == 0) {
5670 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
5671 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
5672 + Integer.toHexString(mHistoryCur.states2));
5673 addHistoryRecordLocked(elapsedRealtime, uptime);
5674 mCameraOnTimer.stopRunningLocked(elapsedRealtime);
5675 }
5676 getUidStatsLocked(uid).noteCameraTurnedOffLocked(elapsedRealtime);
5677 }
5678
5679 public void noteResetCameraLocked() {
5680 if (mCameraOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005681 final long elapsedRealtime = mClocks.elapsedRealtime();
5682 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005683 mCameraOnNesting = 0;
5684 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
5685 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
5686 + Integer.toHexString(mHistoryCur.states2));
5687 addHistoryRecordLocked(elapsedRealtime, uptime);
5688 mCameraOnTimer.stopAllRunningLocked(elapsedRealtime);
5689 for (int i=0; i<mUidStats.size(); i++) {
5690 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5691 uid.noteResetCameraLocked(elapsedRealtime);
5692 }
5693 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005694 }
5695
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005696 public void noteResetFlashlightLocked() {
5697 if (mFlashlightOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005698 final long elapsedRealtime = mClocks.elapsedRealtime();
5699 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005700 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005701 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
5702 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005703 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005704 addHistoryRecordLocked(elapsedRealtime, uptime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005705 mFlashlightOnTimer.stopAllRunningLocked(elapsedRealtime);
5706 for (int i=0; i<mUidStats.size(); i++) {
5707 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5708 uid.noteResetFlashlightLocked(elapsedRealtime);
5709 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005710 }
5711 }
5712
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005713 private void noteBluetoothScanStartedLocked(WorkChain workChain, int uid,
5714 boolean isUnoptimized) {
5715 uid = getAttributionUid(uid, workChain);
Bookatz867c0d72017-03-07 18:23:42 -08005716 final long elapsedRealtime = mClocks.elapsedRealtime();
5717 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005718 if (mBluetoothScanNesting == 0) {
5719 mHistoryCur.states2 |= HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5720 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan started for: "
5721 + Integer.toHexString(mHistoryCur.states2));
5722 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005723 mBluetoothScanTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005724 }
5725 mBluetoothScanNesting++;
Bookatzb1f04f32017-05-19 13:57:32 -07005726 getUidStatsLocked(uid).noteBluetoothScanStartedLocked(elapsedRealtime, isUnoptimized);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005727 }
5728
Bookatzb1f04f32017-05-19 13:57:32 -07005729 public void noteBluetoothScanStartedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005730 final int N = ws.size();
5731 for (int i = 0; i < N; i++) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005732 noteBluetoothScanStartedLocked(null, ws.get(i), isUnoptimized);
5733 }
5734
5735 final List<WorkChain> workChains = ws.getWorkChains();
5736 if (workChains != null) {
5737 for (int i = 0; i < workChains.size(); ++i) {
5738 noteBluetoothScanStartedLocked(workChains.get(i), -1, isUnoptimized);
5739 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005740 }
5741 }
5742
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005743 private void noteBluetoothScanStoppedLocked(WorkChain workChain, int uid,
5744 boolean isUnoptimized) {
5745 uid = getAttributionUid(uid, workChain);
Bookatz867c0d72017-03-07 18:23:42 -08005746 final long elapsedRealtime = mClocks.elapsedRealtime();
5747 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005748 mBluetoothScanNesting--;
5749 if (mBluetoothScanNesting == 0) {
5750 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5751 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan stopped for: "
5752 + Integer.toHexString(mHistoryCur.states2));
5753 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005754 mBluetoothScanTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005755 }
Bookatz94c5a312017-07-11 16:49:17 -07005756 getUidStatsLocked(uid).noteBluetoothScanStoppedLocked(elapsedRealtime, isUnoptimized);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005757 }
5758
5759 private int getAttributionUid(int uid, WorkChain workChain) {
5760 if (workChain != null) {
5761 return mapUid(workChain.getAttributionUid());
5762 }
5763
5764 return mapUid(uid);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005765 }
5766
Bookatz94c5a312017-07-11 16:49:17 -07005767 public void noteBluetoothScanStoppedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005768 final int N = ws.size();
5769 for (int i = 0; i < N; i++) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005770 noteBluetoothScanStoppedLocked(null, ws.get(i), isUnoptimized);
5771 }
5772
5773 final List<WorkChain> workChains = ws.getWorkChains();
5774 if (workChains != null) {
5775 for (int i = 0; i < workChains.size(); ++i) {
5776 noteBluetoothScanStoppedLocked(workChains.get(i), -1, isUnoptimized);
5777 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005778 }
5779 }
5780
5781 public void noteResetBluetoothScanLocked() {
5782 if (mBluetoothScanNesting > 0) {
Bookatz867c0d72017-03-07 18:23:42 -08005783 final long elapsedRealtime = mClocks.elapsedRealtime();
5784 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005785 mBluetoothScanNesting = 0;
5786 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5787 if (DEBUG_HISTORY) Slog.v(TAG, "BLE can stopped for: "
5788 + Integer.toHexString(mHistoryCur.states2));
5789 addHistoryRecordLocked(elapsedRealtime, uptime);
5790 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtime);
5791 for (int i=0; i<mUidStats.size(); i++) {
5792 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5793 uid.noteResetBluetoothScanLocked(elapsedRealtime);
5794 }
5795 }
5796 }
5797
Bookatz4ebc0642017-05-11 12:21:19 -07005798 public void noteBluetoothScanResultsFromSourceLocked(WorkSource ws, int numNewResults) {
Bookatz956f36bf2017-04-28 09:48:17 -07005799 final int N = ws.size();
5800 for (int i = 0; i < N; i++) {
5801 int uid = mapUid(ws.get(i));
Bookatz4ebc0642017-05-11 12:21:19 -07005802 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005803 }
5804
5805 final List<WorkChain> workChains = ws.getWorkChains();
5806 if (workChains != null) {
5807 for (int i = 0; i < workChains.size(); ++i) {
5808 final WorkChain wc = workChains.get(i);
5809 int uid = mapUid(wc.getAttributionUid());
5810 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005811 }
Bookatz956f36bf2017-04-28 09:48:17 -07005812 }
5813 }
5814
Adam Lesinski5f056f62016-07-14 16:56:08 -07005815 private void noteWifiRadioApWakeupLocked(final long elapsedRealtimeMillis,
5816 final long uptimeMillis, int uid) {
5817 uid = mapUid(uid);
5818 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
5819 uid);
5820 getUidStatsLocked(uid).noteWifiRadioApWakeupLocked();
5821 }
5822
5823 public void noteWifiRadioPowerState(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005824 final long elapsedRealtime = mClocks.elapsedRealtime();
5825 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005826 if (mWifiRadioPowerState != powerState) {
5827 final boolean active =
5828 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
5829 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
5830 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07005831 if (uid > 0) {
5832 noteWifiRadioApWakeupLocked(elapsedRealtime, uptime, uid);
5833 }
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005834 mHistoryCur.states |= HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
Siddharth Rayb50a6842017-12-14 15:15:28 -08005835 mWifiActiveTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005836 } else {
5837 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
Siddharth Rayb50a6842017-12-14 15:15:28 -08005838 mWifiActiveTimer.stopRunningLocked(
5839 timestampNs / (1000 * 1000));
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005840 }
5841 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi network active " + active + " to: "
5842 + Integer.toHexString(mHistoryCur.states));
5843 addHistoryRecordLocked(elapsedRealtime, uptime);
5844 mWifiRadioPowerState = powerState;
Yangster-mac4c7255f2018-05-07 13:41:47 -07005845 StatsLog.write_non_chained(StatsLog.WIFI_RADIO_POWER_STATE_CHANGED, uid, null,
5846 powerState);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005847 }
5848 }
5849
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005850 public void noteWifiRunningLocked(WorkSource ws) {
5851 if (!mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005852 final long elapsedRealtime = mClocks.elapsedRealtime();
5853 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005854 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005855 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI running to: "
5856 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005857 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005858 mGlobalWifiRunning = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005859 mGlobalWifiRunningTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005860 int N = ws.size();
5861 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005862 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005863 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005864 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005865
5866 List<WorkChain> workChains = ws.getWorkChains();
5867 if (workChains != null) {
5868 for (int i = 0; i < workChains.size(); ++i) {
5869 int uid = mapUid(workChains.get(i).getAttributionUid());
5870 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
5871 }
5872 }
5873
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005874 scheduleSyncExternalStatsLocked("wifi-running", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005875 } else {
5876 Log.w(TAG, "noteWifiRunningLocked -- called while WIFI running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005877 }
5878 }
5879
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005880 public void noteWifiRunningChangedLocked(WorkSource oldWs, WorkSource newWs) {
5881 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005882 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005883 int N = oldWs.size();
5884 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005885 int uid = mapUid(oldWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005886 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005887 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005888
5889 List<WorkChain> workChains = oldWs.getWorkChains();
5890 if (workChains != null) {
5891 for (int i = 0; i < workChains.size(); ++i) {
5892 int uid = mapUid(workChains.get(i).getAttributionUid());
5893 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
5894 }
5895 }
5896
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005897 N = newWs.size();
5898 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005899 int uid = mapUid(newWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005900 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005901 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005902
5903 workChains = newWs.getWorkChains();
5904 if (workChains != null) {
5905 for (int i = 0; i < workChains.size(); ++i) {
5906 int uid = mapUid(workChains.get(i).getAttributionUid());
5907 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
5908 }
5909 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005910 } else {
5911 Log.w(TAG, "noteWifiRunningChangedLocked -- called while WIFI not running");
5912 }
5913 }
5914
5915 public void noteWifiStoppedLocked(WorkSource ws) {
5916 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005917 final long elapsedRealtime = mClocks.elapsedRealtime();
5918 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005919 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005920 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI stopped to: "
5921 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005922 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005923 mGlobalWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005924 mGlobalWifiRunningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005925 int N = ws.size();
5926 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005927 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005928 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005929 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005930
5931 List<WorkChain> workChains = ws.getWorkChains();
5932 if (workChains != null) {
5933 for (int i = 0; i < workChains.size(); ++i) {
5934 int uid = mapUid(workChains.get(i).getAttributionUid());
5935 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
5936 }
5937 }
5938
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005939 scheduleSyncExternalStatsLocked("wifi-stopped", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005940 } else {
5941 Log.w(TAG, "noteWifiStoppedLocked -- called while WIFI not running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005942 }
5943 }
5944
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005945 public void noteWifiStateLocked(int wifiState, String accessPoint) {
5946 if (DEBUG) Log.i(TAG, "WiFi state -> " + wifiState);
5947 if (mWifiState != wifiState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005948 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005949 if (mWifiState >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005950 mWifiStateTimer[mWifiState].stopRunningLocked(elapsedRealtime);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005951 }
5952 mWifiState = wifiState;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005953 mWifiStateTimer[wifiState].startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005954 scheduleSyncExternalStatsLocked("wifi-state", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005955 }
5956 }
5957
Dianne Hackborn3251b902014-06-20 14:40:53 -07005958 public void noteWifiSupplicantStateChangedLocked(int supplState, boolean failedAuth) {
5959 if (DEBUG) Log.i(TAG, "WiFi suppl state -> " + supplState);
5960 if (mWifiSupplState != supplState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005961 final long elapsedRealtime = mClocks.elapsedRealtime();
5962 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005963 if (mWifiSupplState >= 0) {
5964 mWifiSupplStateTimer[mWifiSupplState].stopRunningLocked(elapsedRealtime);
5965 }
5966 mWifiSupplState = supplState;
5967 mWifiSupplStateTimer[supplState].startRunningLocked(elapsedRealtime);
5968 mHistoryCur.states2 =
5969 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SUPPL_STATE_MASK)
5970 | (supplState << HistoryItem.STATE2_WIFI_SUPPL_STATE_SHIFT);
5971 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi suppl state " + supplState + " to: "
5972 + Integer.toHexString(mHistoryCur.states2));
5973 addHistoryRecordLocked(elapsedRealtime, uptime);
5974 }
5975 }
5976
5977 void stopAllWifiSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005978 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005979 for (int i = 0; i < NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
5980 if (i == except) {
5981 continue;
5982 }
5983 while (mWifiSignalStrengthsTimer[i].isRunningLocked()) {
5984 mWifiSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
5985 }
5986 }
5987 }
5988
5989 public void noteWifiRssiChangedLocked(int newRssi) {
5990 int strengthBin = WifiManager.calculateSignalLevel(newRssi, NUM_WIFI_SIGNAL_STRENGTH_BINS);
5991 if (DEBUG) Log.i(TAG, "WiFi rssi -> " + newRssi + " bin=" + strengthBin);
5992 if (mWifiSignalStrengthBin != strengthBin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005993 final long elapsedRealtime = mClocks.elapsedRealtime();
5994 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005995 if (mWifiSignalStrengthBin >= 0) {
5996 mWifiSignalStrengthsTimer[mWifiSignalStrengthBin].stopRunningLocked(
5997 elapsedRealtime);
5998 }
5999 if (strengthBin >= 0) {
6000 if (!mWifiSignalStrengthsTimer[strengthBin].isRunningLocked()) {
6001 mWifiSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
6002 }
6003 mHistoryCur.states2 =
6004 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_MASK)
6005 | (strengthBin << HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_SHIFT);
6006 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi signal strength " + strengthBin + " to: "
6007 + Integer.toHexString(mHistoryCur.states2));
6008 addHistoryRecordLocked(elapsedRealtime, uptime);
6009 } else {
6010 stopAllWifiSignalStrengthTimersLocked(-1);
6011 }
Bookatz235343d2018-03-26 13:03:50 -07006012 StatsLog.write(StatsLog.WIFI_SIGNAL_STRENGTH_CHANGED, strengthBin);
Dianne Hackborn3251b902014-06-20 14:40:53 -07006013 mWifiSignalStrengthBin = strengthBin;
6014 }
6015 }
6016
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006017 int mWifiFullLockNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006018
Mathew Inwoodc185f082018-08-20 14:28:54 +01006019 @UnsupportedAppUsage
The Android Open Source Project10592532009-03-18 17:39:46 -07006020 public void noteFullWifiLockAcquiredLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006021 final long elapsedRealtime = mClocks.elapsedRealtime();
6022 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006023 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006024 mHistoryCur.states |= HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006025 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock on to: "
6026 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006027 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006028 }
6029 mWifiFullLockNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006030 getUidStatsLocked(uid).noteFullWifiLockAcquiredLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006031 }
6032
Mathew Inwoodc185f082018-08-20 14:28:54 +01006033 @UnsupportedAppUsage
The Android Open Source Project10592532009-03-18 17:39:46 -07006034 public void noteFullWifiLockReleasedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006035 final long elapsedRealtime = mClocks.elapsedRealtime();
6036 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006037 mWifiFullLockNesting--;
6038 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006039 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006040 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock off to: "
6041 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006042 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006043 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006044 getUidStatsLocked(uid).noteFullWifiLockReleasedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006045 }
6046
Nick Pelly6ccaa542012-06-15 15:22:47 -07006047 int mWifiScanNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006048
Nick Pelly6ccaa542012-06-15 15:22:47 -07006049 public void noteWifiScanStartedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006050 final long elapsedRealtime = mClocks.elapsedRealtime();
6051 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07006052 if (mWifiScanNesting == 0) {
6053 mHistoryCur.states |= HistoryItem.STATE_WIFI_SCAN_FLAG;
6054 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan started for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006055 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006056 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006057 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07006058 mWifiScanNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006059 getUidStatsLocked(uid).noteWifiScanStartedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006060 }
6061
Nick Pelly6ccaa542012-06-15 15:22:47 -07006062 public void noteWifiScanStoppedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006063 final long elapsedRealtime = mClocks.elapsedRealtime();
6064 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07006065 mWifiScanNesting--;
6066 if (mWifiScanNesting == 0) {
6067 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_SCAN_FLAG;
6068 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan stopped for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006069 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006070 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006071 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006072 getUidStatsLocked(uid).noteWifiScanStoppedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006073 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006074
Robert Greenwalta029ea12013-09-25 16:38:12 -07006075 public void noteWifiBatchedScanStartedLocked(int uid, int csph) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006076 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006077 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006078 getUidStatsLocked(uid).noteWifiBatchedScanStartedLocked(csph, elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006079 }
6080
6081 public void noteWifiBatchedScanStoppedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006082 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006083 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006084 getUidStatsLocked(uid).noteWifiBatchedScanStoppedLocked(elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006085 }
6086
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006087 int mWifiMulticastNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006088
Mathew Inwoodc185f082018-08-20 14:28:54 +01006089 @UnsupportedAppUsage
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006090 public void noteWifiMulticastEnabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006091 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006092 final long elapsedRealtime = mClocks.elapsedRealtime();
6093 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006094 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006095 mHistoryCur.states |= HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006096 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast on to: "
6097 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006098 addHistoryRecordLocked(elapsedRealtime, uptime);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006099
6100 // Start Wifi Multicast overall timer
6101 if (!mWifiMulticastWakelockTimer.isRunningLocked()) {
6102 if (DEBUG_HISTORY) Slog.v(TAG, "WiFi Multicast Overall Timer Started");
6103 mWifiMulticastWakelockTimer.startRunningLocked(elapsedRealtime);
6104 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006105 }
6106 mWifiMulticastNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006107 getUidStatsLocked(uid).noteWifiMulticastEnabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006108 }
6109
Mathew Inwoodc185f082018-08-20 14:28:54 +01006110 @UnsupportedAppUsage
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006111 public void noteWifiMulticastDisabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006112 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006113 final long elapsedRealtime = mClocks.elapsedRealtime();
6114 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006115 mWifiMulticastNesting--;
6116 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006117 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006118 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast off to: "
6119 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006120 addHistoryRecordLocked(elapsedRealtime, uptime);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006121
6122 // Stop Wifi Multicast overall timer
6123 if (mWifiMulticastWakelockTimer.isRunningLocked()) {
6124 if (DEBUG_HISTORY) Slog.v(TAG, "Multicast Overall Timer Stopped");
6125 mWifiMulticastWakelockTimer.stopRunningLocked(elapsedRealtime);
6126 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006127 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006128 getUidStatsLocked(uid).noteWifiMulticastDisabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006129 }
6130
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006131 public void noteFullWifiLockAcquiredFromSourceLocked(WorkSource ws) {
6132 int N = ws.size();
6133 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006134 final int uid = mapUid(ws.get(i));
6135 noteFullWifiLockAcquiredLocked(uid);
Bookatz90867622018-01-31 15:05:57 -08006136 StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, ws.get(i), ws.getName(i),
6137 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006138 }
6139
6140 final List<WorkChain> workChains = ws.getWorkChains();
6141 if (workChains != null) {
6142 for (int i = 0; i < workChains.size(); ++i) {
6143 final WorkChain workChain = workChains.get(i);
6144 final int uid = mapUid(workChain.getAttributionUid());
6145 noteFullWifiLockAcquiredLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006146 StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006147 workChain.getUids(), workChain.getTags(),
6148 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006149 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006150 }
6151 }
6152
6153 public void noteFullWifiLockReleasedFromSourceLocked(WorkSource ws) {
6154 int N = ws.size();
6155 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006156 final int uid = mapUid(ws.get(i));
6157 noteFullWifiLockReleasedLocked(uid);
Bookatz90867622018-01-31 15:05:57 -08006158 StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, ws.get(i), ws.getName(i),
6159 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006160 }
6161
6162 final List<WorkChain> workChains = ws.getWorkChains();
6163 if (workChains != null) {
6164 for (int i = 0; i < workChains.size(); ++i) {
6165 final WorkChain workChain = workChains.get(i);
6166 final int uid = mapUid(workChain.getAttributionUid());
6167 noteFullWifiLockReleasedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006168 StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006169 workChain.getUids(), workChain.getTags(),
6170 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006171 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006172 }
6173 }
6174
Nick Pelly6ccaa542012-06-15 15:22:47 -07006175 public void noteWifiScanStartedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006176 int N = ws.size();
6177 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006178 final int uid = mapUid(ws.get(i));
6179 noteWifiScanStartedLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08006180 StatsLog.write_non_chained(StatsLog.WIFI_SCAN_STATE_CHANGED, ws.get(i), ws.getName(i),
Bookatz90867622018-01-31 15:05:57 -08006181 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006182 }
6183
6184 final List<WorkChain> workChains = ws.getWorkChains();
6185 if (workChains != null) {
6186 for (int i = 0; i < workChains.size(); ++i) {
6187 final WorkChain workChain = workChains.get(i);
6188 final int uid = mapUid(workChain.getAttributionUid());
6189 noteWifiScanStartedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006190 StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED, workChain.getUids(),
Bookatz90867622018-01-31 15:05:57 -08006191 workChain.getTags(), StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006192 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006193 }
6194 }
6195
Nick Pelly6ccaa542012-06-15 15:22:47 -07006196 public void noteWifiScanStoppedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006197 int N = ws.size();
6198 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006199 final int uid = mapUid(ws.get(i));
6200 noteWifiScanStoppedLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08006201 StatsLog.write_non_chained(StatsLog.WIFI_SCAN_STATE_CHANGED, ws.get(i), ws.getName(i),
Bookatz90867622018-01-31 15:05:57 -08006202 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006203 }
6204
6205 final List<WorkChain> workChains = ws.getWorkChains();
6206 if (workChains != null) {
6207 for (int i = 0; i < workChains.size(); ++i) {
6208 final WorkChain workChain = workChains.get(i);
6209 final int uid = mapUid(workChain.getAttributionUid());
6210 noteWifiScanStoppedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006211 StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006212 workChain.getUids(), workChain.getTags(),
6213 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006214 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006215 }
6216 }
6217
Robert Greenwalta029ea12013-09-25 16:38:12 -07006218 public void noteWifiBatchedScanStartedFromSourceLocked(WorkSource ws, int csph) {
6219 int N = ws.size();
6220 for (int i=0; i<N; i++) {
6221 noteWifiBatchedScanStartedLocked(ws.get(i), csph);
6222 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00006223
6224 final List<WorkChain> workChains = ws.getWorkChains();
6225 if (workChains != null) {
6226 for (int i = 0; i < workChains.size(); ++i) {
6227 noteWifiBatchedScanStartedLocked(workChains.get(i).getAttributionUid(), csph);
6228 }
6229 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006230 }
6231
6232 public void noteWifiBatchedScanStoppedFromSourceLocked(WorkSource ws) {
6233 int N = ws.size();
6234 for (int i=0; i<N; i++) {
6235 noteWifiBatchedScanStoppedLocked(ws.get(i));
6236 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00006237
6238 final List<WorkChain> workChains = ws.getWorkChains();
6239 if (workChains != null) {
6240 for (int i = 0; i < workChains.size(); ++i) {
6241 noteWifiBatchedScanStoppedLocked(workChains.get(i).getAttributionUid());
6242 }
6243 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006244 }
6245
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08006246 private static String[] includeInStringArray(String[] array, String str) {
6247 if (ArrayUtils.indexOf(array, str) >= 0) {
6248 return array;
6249 }
6250 String[] newArray = new String[array.length+1];
6251 System.arraycopy(array, 0, newArray, 0, array.length);
6252 newArray[array.length] = str;
6253 return newArray;
6254 }
6255
6256 private static String[] excludeFromStringArray(String[] array, String str) {
6257 int index = ArrayUtils.indexOf(array, str);
6258 if (index >= 0) {
6259 String[] newArray = new String[array.length-1];
6260 if (index > 0) {
6261 System.arraycopy(array, 0, newArray, 0, index);
6262 }
6263 if (index < array.length-1) {
6264 System.arraycopy(array, index+1, newArray, index, array.length-index-1);
6265 }
6266 return newArray;
6267 }
6268 return array;
6269 }
6270
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07006271 public void noteNetworkInterfaceTypeLocked(String iface, int networkType) {
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07006272 if (TextUtils.isEmpty(iface)) return;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006273
Adam Lesinski14ae39a2017-05-26 11:50:40 -07006274 synchronized (mModemNetworkLock) {
6275 if (ConnectivityManager.isNetworkTypeMobile(networkType)) {
6276 mModemIfaces = includeInStringArray(mModemIfaces, iface);
6277 if (DEBUG) Slog.d(TAG, "Note mobile iface " + iface + ": " + mModemIfaces);
6278 } else {
6279 mModemIfaces = excludeFromStringArray(mModemIfaces, iface);
6280 if (DEBUG) Slog.d(TAG, "Note non-mobile iface " + iface + ": " + mModemIfaces);
6281 }
6282 }
6283
6284 synchronized (mWifiNetworkLock) {
6285 if (ConnectivityManager.isNetworkTypeWifi(networkType)) {
6286 mWifiIfaces = includeInStringArray(mWifiIfaces, iface);
6287 if (DEBUG) Slog.d(TAG, "Note wifi iface " + iface + ": " + mWifiIfaces);
6288 } else {
6289 mWifiIfaces = excludeFromStringArray(mWifiIfaces, iface);
6290 if (DEBUG) Slog.d(TAG, "Note non-wifi iface " + iface + ": " + mWifiIfaces);
6291 }
6292 }
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07006293 }
6294
David Chenc8a43242017-10-17 16:23:28 -07006295 public String[] getWifiIfaces() {
6296 synchronized (mWifiNetworkLock) {
6297 return mWifiIfaces;
6298 }
6299 }
6300
6301 public String[] getMobileIfaces() {
6302 synchronized (mModemNetworkLock) {
6303 return mModemIfaces;
6304 }
6305 }
6306
Mathew Inwoodc185f082018-08-20 14:28:54 +01006307 @UnsupportedAppUsage
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006308 @Override public long getScreenOnTime(long elapsedRealtimeUs, int which) {
6309 return mScreenOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006310 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006311
Dianne Hackborn77b987f2014-02-26 16:20:52 -08006312 @Override public int getScreenOnCount(int which) {
6313 return mScreenOnTimer.getCountLocked(which);
6314 }
6315
Mike Mac2f518a2017-09-19 16:06:03 -07006316 @Override public long getScreenDozeTime(long elapsedRealtimeUs, int which) {
6317 return mScreenDozeTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6318 }
6319
6320 @Override public int getScreenDozeCount(int which) {
6321 return mScreenDozeTimer.getCountLocked(which);
6322 }
6323
Mathew Inwoodc185f082018-08-20 14:28:54 +01006324 @UnsupportedAppUsage
Dianne Hackborn617f8772009-03-31 15:04:46 -07006325 @Override public long getScreenBrightnessTime(int brightnessBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006326 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006327 return mScreenBrightnessTimer[brightnessBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006328 elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006329 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006330
Kweku Adams87b19ec2017-10-09 12:40:03 -07006331 @Override public Timer getScreenBrightnessTimer(int brightnessBin) {
6332 return mScreenBrightnessTimer[brightnessBin];
6333 }
6334
Jeff Browne95c3cd2014-05-02 16:59:26 -07006335 @Override public long getInteractiveTime(long elapsedRealtimeUs, int which) {
6336 return mInteractiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006337 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006338
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006339 @Override public long getPowerSaveModeEnabledTime(long elapsedRealtimeUs, int which) {
6340 return mPowerSaveModeEnabledTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07006341 }
6342
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006343 @Override public int getPowerSaveModeEnabledCount(int which) {
6344 return mPowerSaveModeEnabledTimer.getCountLocked(which);
6345 }
6346
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006347 @Override public long getDeviceIdleModeTime(int mode, long elapsedRealtimeUs,
6348 int which) {
6349 switch (mode) {
6350 case DEVICE_IDLE_MODE_LIGHT:
6351 return mDeviceIdleModeLightTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006352 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006353 return mDeviceIdleModeFullTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6354 }
6355 return 0;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006356 }
6357
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006358 @Override public int getDeviceIdleModeCount(int mode, int which) {
6359 switch (mode) {
6360 case DEVICE_IDLE_MODE_LIGHT:
6361 return mDeviceIdleModeLightTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006362 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006363 return mDeviceIdleModeFullTimer.getCountLocked(which);
6364 }
6365 return 0;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07006366 }
6367
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006368 @Override public long getLongestDeviceIdleModeTime(int mode) {
6369 switch (mode) {
6370 case DEVICE_IDLE_MODE_LIGHT:
6371 return mLongestLightIdleTime;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006372 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006373 return mLongestFullIdleTime;
6374 }
6375 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07006376 }
6377
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006378 @Override public long getDeviceIdlingTime(int mode, long elapsedRealtimeUs, int which) {
6379 switch (mode) {
6380 case DEVICE_IDLE_MODE_LIGHT:
6381 return mDeviceLightIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006382 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006383 return mDeviceIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6384 }
6385 return 0;
6386 }
6387
6388 @Override public int getDeviceIdlingCount(int mode, int which) {
6389 switch (mode) {
6390 case DEVICE_IDLE_MODE_LIGHT:
6391 return mDeviceLightIdlingTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006392 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006393 return mDeviceIdlingTimer.getCountLocked(which);
6394 }
6395 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07006396 }
6397
Dianne Hackborn1e01d162014-12-04 17:46:42 -08006398 @Override public int getNumConnectivityChange(int which) {
6399 int val = mNumConnectivityChange;
6400 if (which == STATS_CURRENT) {
6401 val -= mLoadedNumConnectivityChange;
6402 } else if (which == STATS_SINCE_UNPLUGGED) {
6403 val -= mUnpluggedNumConnectivityChange;
6404 }
6405 return val;
6406 }
6407
Siddharth Ray78ccaf52017-12-23 16:16:21 -08006408 @Override public long getGpsSignalQualityTime(int strengthBin,
6409 long elapsedRealtimeUs, int which) {
6410 if (strengthBin < 0 || strengthBin >= GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS) {
6411 return 0;
6412 }
6413 return mGpsSignalQualityTimer[strengthBin].getTotalTimeLocked(
6414 elapsedRealtimeUs, which);
6415 }
6416
6417 @Override public long getGpsBatteryDrainMaMs() {
Siddharth Ray0ed2e952018-01-22 11:32:14 -08006418 final double opVolt = mPowerProfile.getAveragePower(
6419 PowerProfile.POWER_GPS_OPERATING_VOLTAGE) / 1000.0;
6420 if (opVolt == 0) {
6421 return 0;
6422 }
6423 double energyUsedMaMs = 0.0;
6424 final int which = STATS_SINCE_CHARGED;
6425 final long rawRealtime = SystemClock.elapsedRealtime() * 1000;
6426 for(int i=0; i < GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
6427 energyUsedMaMs
6428 += mPowerProfile.getAveragePower(PowerProfile.POWER_GPS_SIGNAL_QUALITY_BASED, i)
6429 * (getGpsSignalQualityTime(i, rawRealtime, which) / 1000);
6430 }
6431 return (long) energyUsedMaMs;
Siddharth Ray78ccaf52017-12-23 16:16:21 -08006432 }
6433
Mathew Inwoodc185f082018-08-20 14:28:54 +01006434 @UnsupportedAppUsage
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006435 @Override public long getPhoneOnTime(long elapsedRealtimeUs, int which) {
6436 return mPhoneOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006437 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006438
Dianne Hackborn77b987f2014-02-26 16:20:52 -08006439 @Override public int getPhoneOnCount(int which) {
6440 return mPhoneOnTimer.getCountLocked(which);
6441 }
6442
Mathew Inwoodc185f082018-08-20 14:28:54 +01006443 @UnsupportedAppUsage
Dianne Hackborn627bba72009-03-24 22:32:56 -07006444 @Override public long getPhoneSignalStrengthTime(int strengthBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006445 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006446 return mPhoneSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006447 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07006448 }
Amith Yamasanif37447b2009-10-08 18:28:01 -07006449
Mathew Inwoodc185f082018-08-20 14:28:54 +01006450 @UnsupportedAppUsage
Amith Yamasanif37447b2009-10-08 18:28:01 -07006451 @Override public long getPhoneSignalScanningTime(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006452 long elapsedRealtimeUs, int which) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07006453 return mPhoneSignalScanningTimer.getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006454 elapsedRealtimeUs, which);
Amith Yamasanif37447b2009-10-08 18:28:01 -07006455 }
6456
Kweku Adams87b19ec2017-10-09 12:40:03 -07006457 @Override public Timer getPhoneSignalScanningTimer() {
6458 return mPhoneSignalScanningTimer;
6459 }
6460
Mathew Inwoodc185f082018-08-20 14:28:54 +01006461 @UnsupportedAppUsage
Catherine Liufb900812012-07-17 14:12:56 -05006462 @Override public int getPhoneSignalStrengthCount(int strengthBin, int which) {
6463 return mPhoneSignalStrengthsTimer[strengthBin].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006464 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006465
Kweku Adams87b19ec2017-10-09 12:40:03 -07006466 @Override public Timer getPhoneSignalStrengthTimer(int strengthBin) {
6467 return mPhoneSignalStrengthsTimer[strengthBin];
6468 }
6469
Mathew Inwoodc185f082018-08-20 14:28:54 +01006470 @UnsupportedAppUsage
Dianne Hackborn627bba72009-03-24 22:32:56 -07006471 @Override public long getPhoneDataConnectionTime(int dataType,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006472 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006473 return mPhoneDataConnectionsTimer[dataType].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006474 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07006475 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006476
Mathew Inwoodc185f082018-08-20 14:28:54 +01006477 @UnsupportedAppUsage
Dianne Hackborn617f8772009-03-31 15:04:46 -07006478 @Override public int getPhoneDataConnectionCount(int dataType, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006479 return mPhoneDataConnectionsTimer[dataType].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006480 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006481
Kweku Adams87b19ec2017-10-09 12:40:03 -07006482 @Override public Timer getPhoneDataConnectionTimer(int dataType) {
6483 return mPhoneDataConnectionsTimer[dataType];
6484 }
6485
Mathew Inwoodc185f082018-08-20 14:28:54 +01006486 @UnsupportedAppUsage
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006487 @Override public long getMobileRadioActiveTime(long elapsedRealtimeUs, int which) {
6488 return mMobileRadioActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborne13c4c02014-02-11 17:18:35 -08006489 }
6490
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006491 @Override public int getMobileRadioActiveCount(int which) {
6492 return mMobileRadioActiveTimer.getCountLocked(which);
6493 }
6494
Dianne Hackborna1bd7922014-03-21 11:07:11 -07006495 @Override public long getMobileRadioActiveAdjustedTime(int which) {
6496 return mMobileRadioActiveAdjustedTime.getCountLocked(which);
6497 }
6498
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006499 @Override public long getMobileRadioActiveUnknownTime(int which) {
6500 return mMobileRadioActiveUnknownTime.getCountLocked(which);
6501 }
6502
6503 @Override public int getMobileRadioActiveUnknownCount(int which) {
6504 return (int)mMobileRadioActiveUnknownCount.getCountLocked(which);
6505 }
6506
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006507 @Override public long getWifiMulticastWakelockTime(
6508 long elapsedRealtimeUs, int which) {
6509 return mWifiMulticastWakelockTimer.getTotalTimeLocked(
6510 elapsedRealtimeUs, which);
6511 }
6512
6513 @Override public int getWifiMulticastWakelockCount(int which) {
6514 return mWifiMulticastWakelockTimer.getCountLocked(which);
6515 }
6516
Mathew Inwoodc185f082018-08-20 14:28:54 +01006517 @UnsupportedAppUsage
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006518 @Override public long getWifiOnTime(long elapsedRealtimeUs, int which) {
6519 return mWifiOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07006520 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006521
Siddharth Rayb50a6842017-12-14 15:15:28 -08006522 @Override public long getWifiActiveTime(long elapsedRealtimeUs, int which) {
6523 return mWifiActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6524 }
6525
Mathew Inwoodc185f082018-08-20 14:28:54 +01006526 @UnsupportedAppUsage
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006527 @Override public long getGlobalWifiRunningTime(long elapsedRealtimeUs, int which) {
6528 return mGlobalWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07006529 }
6530
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006531 @Override public long getWifiStateTime(int wifiState,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006532 long elapsedRealtimeUs, int which) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006533 return mWifiStateTimer[wifiState].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006534 elapsedRealtimeUs, which);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006535 }
6536
6537 @Override public int getWifiStateCount(int wifiState, int which) {
6538 return mWifiStateTimer[wifiState].getCountLocked(which);
6539 }
6540
Kweku Adams87b19ec2017-10-09 12:40:03 -07006541 @Override public Timer getWifiStateTimer(int wifiState) {
6542 return mWifiStateTimer[wifiState];
6543 }
6544
Dianne Hackborn3251b902014-06-20 14:40:53 -07006545 @Override public long getWifiSupplStateTime(int state,
6546 long elapsedRealtimeUs, int which) {
6547 return mWifiSupplStateTimer[state].getTotalTimeLocked(
6548 elapsedRealtimeUs, which);
6549 }
6550
6551 @Override public int getWifiSupplStateCount(int state, int which) {
6552 return mWifiSupplStateTimer[state].getCountLocked(which);
6553 }
6554
Kweku Adams87b19ec2017-10-09 12:40:03 -07006555 @Override public Timer getWifiSupplStateTimer(int state) {
6556 return mWifiSupplStateTimer[state];
6557 }
6558
Dianne Hackborn3251b902014-06-20 14:40:53 -07006559 @Override public long getWifiSignalStrengthTime(int strengthBin,
6560 long elapsedRealtimeUs, int which) {
6561 return mWifiSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
6562 elapsedRealtimeUs, which);
6563 }
6564
6565 @Override public int getWifiSignalStrengthCount(int strengthBin, int which) {
6566 return mWifiSignalStrengthsTimer[strengthBin].getCountLocked(which);
6567 }
6568
Kweku Adams87b19ec2017-10-09 12:40:03 -07006569 @Override public Timer getWifiSignalStrengthTimer(int strengthBin) {
6570 return mWifiSignalStrengthsTimer[strengthBin];
6571 }
6572
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006573 @Override
6574 public ControllerActivityCounter getBluetoothControllerActivity() {
6575 return mBluetoothActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07006576 }
6577
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006578 @Override
6579 public ControllerActivityCounter getWifiControllerActivity() {
6580 return mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -07006581 }
6582
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006583 @Override
6584 public ControllerActivityCounter getModemControllerActivity() {
6585 return mModemActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07006586 }
6587
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006588 @Override
6589 public boolean hasBluetoothActivityReporting() {
6590 return mHasBluetoothReporting;
6591 }
6592
6593 @Override
6594 public boolean hasWifiActivityReporting() {
6595 return mHasWifiReporting;
6596 }
6597
6598 @Override
6599 public boolean hasModemActivityReporting() {
6600 return mHasModemReporting;
Adam Lesinski33dac552015-03-09 15:24:48 -07006601 }
6602
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006603 @Override
6604 public long getFlashlightOnTime(long elapsedRealtimeUs, int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07006605 return mFlashlightOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6606 }
6607
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006608 @Override
6609 public long getFlashlightOnCount(int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07006610 return mFlashlightOnTimer.getCountLocked(which);
6611 }
6612
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006613 @Override
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006614 public long getCameraOnTime(long elapsedRealtimeUs, int which) {
6615 return mCameraOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6616 }
6617
6618 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006619 public long getBluetoothScanTime(long elapsedRealtimeUs, int which) {
6620 return mBluetoothScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6621 }
6622
6623 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01006624 @UnsupportedAppUsage
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006625 public long getNetworkActivityBytes(int type, int which) {
6626 if (type >= 0 && type < mNetworkByteActivityCounters.length) {
6627 return mNetworkByteActivityCounters[type].getCountLocked(which);
6628 } else {
6629 return 0;
6630 }
6631 }
6632
6633 @Override
6634 public long getNetworkActivityPackets(int type, int which) {
6635 if (type >= 0 && type < mNetworkPacketActivityCounters.length) {
6636 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006637 } else {
6638 return 0;
6639 }
6640 }
6641
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08006642 @Override public long getStartClockTime() {
Dianne Hackbornd48954f2015-07-22 17:20:33 -07006643 final long currentTime = System.currentTimeMillis();
6644 if (ensureStartClockTime(currentTime)) {
Joe Onoratoabded112016-02-08 16:49:39 -08006645 recordCurrentTimeChangeLocked(currentTime, mClocks.elapsedRealtime(),
6646 mClocks.uptimeMillis());
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07006647 }
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08006648 return mStartClockTime;
6649 }
6650
Dianne Hackborncd0e3352014-08-07 17:08:09 -07006651 @Override public String getStartPlatformVersion() {
6652 return mStartPlatformVersion;
6653 }
6654
6655 @Override public String getEndPlatformVersion() {
6656 return mEndPlatformVersion;
6657 }
6658
6659 @Override public int getParcelVersion() {
6660 return VERSION;
6661 }
6662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006663 @Override public boolean getIsOnBattery() {
6664 return mOnBattery;
6665 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006666
Mathew Inwoodc185f082018-08-20 14:28:54 +01006667 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006668 @Override public SparseArray<? extends BatteryStats.Uid> getUidStats() {
6669 return mUidStats;
6670 }
6671
Adam Lesinski5f056f62016-07-14 16:56:08 -07006672 private static void detachTimerIfNotNull(BatteryStatsImpl.Timer timer) {
6673 if (timer != null) {
6674 timer.detach();
6675 }
6676 }
6677
6678 private static boolean resetTimerIfNotNull(BatteryStatsImpl.Timer timer,
6679 boolean detachIfReset) {
6680 if (timer != null) {
6681 return timer.reset(detachIfReset);
6682 }
6683 return true;
6684 }
6685
Bookatz867c0d72017-03-07 18:23:42 -08006686 private static boolean resetTimerIfNotNull(DualTimer timer, boolean detachIfReset) {
6687 if (timer != null) {
6688 return timer.reset(detachIfReset);
6689 }
6690 return true;
6691 }
6692
Adam Lesinski5f056f62016-07-14 16:56:08 -07006693 private static void detachLongCounterIfNotNull(LongSamplingCounter counter) {
6694 if (counter != null) {
6695 counter.detach();
6696 }
6697 }
6698
6699 private static void resetLongCounterIfNotNull(LongSamplingCounter counter,
6700 boolean detachIfReset) {
6701 if (counter != null) {
6702 counter.reset(detachIfReset);
6703 }
6704 }
6705
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006706 /**
6707 * The statistics associated with a particular uid.
6708 */
Joe Onoratoabded112016-02-08 16:49:39 -08006709 public static class Uid extends BatteryStats.Uid {
6710 /**
6711 * BatteryStatsImpl that we are associated with.
6712 */
6713 protected BatteryStatsImpl mBsi;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006715 final int mUid;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006716
Bookatz867c0d72017-03-07 18:23:42 -08006717 /** TimeBase for when uid is in background and device is on battery. */
6718 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6719 public final TimeBase mOnBatteryBackgroundTimeBase;
Bookatzc8c44962017-05-11 12:12:54 -07006720 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6721 public final TimeBase mOnBatteryScreenOffBackgroundTimeBase;
Bookatz867c0d72017-03-07 18:23:42 -08006722
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006723 boolean mWifiRunning;
6724 StopwatchTimer mWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006725
The Android Open Source Project10592532009-03-18 17:39:46 -07006726 boolean mFullWifiLockOut;
Evan Millarc64edde2009-04-18 12:26:32 -07006727 StopwatchTimer mFullWifiLockTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006728
Nick Pelly6ccaa542012-06-15 15:22:47 -07006729 boolean mWifiScanStarted;
Bookatz867c0d72017-03-07 18:23:42 -08006730 DualTimer mWifiScanTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006731
Dianne Hackborn61659e52014-07-09 16:13:01 -07006732 static final int NO_BATCHED_SCAN_STARTED = -1;
Robert Greenwalta029ea12013-09-25 16:38:12 -07006733 int mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
6734 StopwatchTimer[] mWifiBatchedScanTimer;
6735
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006736 boolean mWifiMulticastEnabled;
6737 StopwatchTimer mWifiMulticastTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006738
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006739 StopwatchTimer mAudioTurnedOnTimer;
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006740 StopwatchTimer mVideoTurnedOnTimer;
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006741 StopwatchTimer mFlashlightTurnedOnTimer;
6742 StopwatchTimer mCameraTurnedOnTimer;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006743 StopwatchTimer mForegroundActivityTimer;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006744 StopwatchTimer mForegroundServiceTimer;
Bookatzc8c44962017-05-11 12:12:54 -07006745 /** Total time spent by the uid holding any partial wakelocks. */
6746 DualTimer mAggregatedPartialWakelockTimer;
Bookatz867c0d72017-03-07 18:23:42 -08006747 DualTimer mBluetoothScanTimer;
Bookatzb1f04f32017-05-19 13:57:32 -07006748 DualTimer mBluetoothUnoptimizedScanTimer;
Bookatz956f36bf2017-04-28 09:48:17 -07006749 Counter mBluetoothScanResultCounter;
Bookatzb1f04f32017-05-19 13:57:32 -07006750 Counter mBluetoothScanResultBgCounter;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006751
Dianne Hackborna8d10942015-11-19 17:55:19 -08006752 int mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07006753 StopwatchTimer[] mProcessStateTimer;
6754
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006755 boolean mInForegroundService = false;
6756
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006757 BatchTimer mVibratorOnTimer;
6758
Dianne Hackborn617f8772009-03-31 15:04:46 -07006759 Counter[] mUserActivityCounters;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006760
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006761 LongSamplingCounter[] mNetworkByteActivityCounters;
6762 LongSamplingCounter[] mNetworkPacketActivityCounters;
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006763 LongSamplingCounter mMobileRadioActiveTime;
6764 LongSamplingCounter mMobileRadioActiveCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006766 /**
Adam Lesinski5f056f62016-07-14 16:56:08 -07006767 * How many times this UID woke up the Application Processor due to a Mobile radio packet.
6768 */
6769 private LongSamplingCounter mMobileRadioApWakeupCount;
6770
6771 /**
6772 * How many times this UID woke up the Application Processor due to a Wifi packet.
6773 */
6774 private LongSamplingCounter mWifiRadioApWakeupCount;
6775
6776 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07006777 * The amount of time this uid has kept the WiFi controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006778 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07006779 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006780 private ControllerActivityCounterImpl mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006781
6782 /**
6783 * The amount of time this uid has kept the Bluetooth controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006784 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07006785 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006786 private ControllerActivityCounterImpl mBluetoothControllerActivity;
6787
6788 /**
6789 * The amount of time this uid has kept the Modem controller in idle, tx, and rx mode.
6790 * Can be null if the UID has had no such activity.
6791 */
6792 private ControllerActivityCounterImpl mModemControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006793
6794 /**
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006795 * The CPU times we had at the last history details update.
6796 */
6797 long mLastStepUserTime;
6798 long mLastStepSystemTime;
6799 long mCurStepUserTime;
6800 long mCurStepSystemTime;
6801
Joe Onoratoabded112016-02-08 16:49:39 -08006802 LongSamplingCounter mUserCpuTime;
6803 LongSamplingCounter mSystemCpuTime;
Sudheer Shankaaf857412017-07-21 00:14:24 -07006804 LongSamplingCounter[][] mCpuClusterSpeedTimesUs;
Mike Ma3d422c32017-10-25 11:08:57 -07006805 LongSamplingCounter mCpuActiveTimeMs;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006806
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006807 LongSamplingCounterArray mCpuFreqTimeMs;
6808 LongSamplingCounterArray mScreenOffCpuFreqTimeMs;
Mike Ma3d422c32017-10-25 11:08:57 -07006809 LongSamplingCounterArray mCpuClusterTimesMs;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006810
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006811 LongSamplingCounterArray[] mProcStateTimeMs;
6812 LongSamplingCounterArray[] mProcStateScreenOffTimeMs;
6813
6814 IntArray mChildUids;
6815
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006816 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006817 * The statistics we have collected for this uid's wake locks.
6818 */
Joe Onoratoabded112016-02-08 16:49:39 -08006819 final OverflowArrayMap<Wakelock> mWakelockStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006820
6821 /**
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006822 * The statistics we have collected for this uid's syncs.
6823 */
Bookatz2bffb5b2017-04-13 11:59:33 -07006824 final OverflowArrayMap<DualTimer> mSyncStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006825
6826 /**
6827 * The statistics we have collected for this uid's jobs.
6828 */
Bookatzaa4594a2017-03-24 12:39:56 -07006829 final OverflowArrayMap<DualTimer> mJobStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006830
6831 /**
Dianne Hackborn94326cb2017-06-28 16:17:20 -07006832 * Count of the jobs that have completed and the reasons why they completed.
6833 */
6834 final ArrayMap<String, SparseIntArray> mJobCompletions = new ArrayMap<>();
6835
6836 /**
Amith Yamasani977e11f2018-02-16 11:29:54 -08006837 * Count of app launch events that had associated deferred job counts or info about
6838 * last time a job was run.
6839 */
6840 Counter mJobsDeferredEventCount;
6841
6842 /**
6843 * Count of deferred jobs that were pending when the app was launched or brought to
6844 * the foreground through a user interaction.
6845 */
6846 Counter mJobsDeferredCount;
6847
6848 /**
6849 * Sum of time since the last time a job was run for this app before it was launched.
6850 */
6851 LongSamplingCounter mJobsFreshnessTimeMs;
6852
6853 /**
6854 * Array of counts of instances where the time since the last job was run for the app
6855 * fell within one of the thresholds in {@link #JOB_FRESHNESS_BUCKETS}.
6856 */
6857 final Counter[] mJobsFreshnessBuckets;
6858
6859 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006860 * The statistics we have collected for this uid's sensor activations.
6861 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006862 final SparseArray<Sensor> mSensorStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006863
6864 /**
6865 * The statistics we have collected for this uid's processes.
6866 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006867 final ArrayMap<String, Proc> mProcessStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006868
6869 /**
6870 * The statistics we have collected for this uid's processes.
6871 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006872 final ArrayMap<String, Pkg> mPackageStats = new ArrayMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006873
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006874 /**
6875 * The transient wake stats we have collected for this uid's pids.
6876 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006877 final SparseArray<Pid> mPids = new SparseArray<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006878
Joe Onoratoabded112016-02-08 16:49:39 -08006879 public Uid(BatteryStatsImpl bsi, int uid) {
6880 mBsi = bsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006881 mUid = uid;
Joe Onoratoabded112016-02-08 16:49:39 -08006882
Bookatz867c0d72017-03-07 18:23:42 -08006883 mOnBatteryBackgroundTimeBase = new TimeBase();
6884 mOnBatteryBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
6885 mBsi.mClocks.elapsedRealtime() * 1000);
6886
Bookatzc8c44962017-05-11 12:12:54 -07006887 mOnBatteryScreenOffBackgroundTimeBase = new TimeBase();
6888 mOnBatteryScreenOffBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
6889 mBsi.mClocks.elapsedRealtime() * 1000);
6890
Joe Onoratoabded112016-02-08 16:49:39 -08006891 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6892 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Mike Ma3d422c32017-10-25 11:08:57 -07006893 mCpuActiveTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6894 mCpuClusterTimesMs = new LongSamplingCounterArray(mBsi.mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006895
Dianne Hackborn657153b2016-07-29 14:54:14 -07006896 mWakelockStats = mBsi.new OverflowArrayMap<Wakelock>(uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006897 @Override public Wakelock instantiateObject() {
6898 return new Wakelock(mBsi, Uid.this);
6899 }
6900 };
Bookatz2bffb5b2017-04-13 11:59:33 -07006901 mSyncStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
6902 @Override public DualTimer instantiateObject() {
6903 return new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
6904 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006905 }
6906 };
Bookatzaa4594a2017-03-24 12:39:56 -07006907 mJobStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
6908 @Override public DualTimer instantiateObject() {
6909 return new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
6910 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006911 }
6912 };
6913
6914 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_RUNNING,
6915 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
6916 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, this, FULL_WIFI_LOCK,
6917 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Bookatz867c0d72017-03-07 18:23:42 -08006918 mWifiScanTimer = new DualTimer(mBsi.mClocks, this, WIFI_SCAN,
6919 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006920 mWifiBatchedScanTimer = new StopwatchTimer[NUM_WIFI_BATCHED_SCAN_BINS];
Joe Onoratoabded112016-02-08 16:49:39 -08006921 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_MULTICAST_ENABLED,
6922 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006923 mProcessStateTimer = new StopwatchTimer[NUM_PROCESS_STATE];
Amith Yamasani977e11f2018-02-16 11:29:54 -08006924 mJobsDeferredEventCount = new Counter(mBsi.mOnBatteryTimeBase);
6925 mJobsDeferredCount = new Counter(mBsi.mOnBatteryTimeBase);
6926 mJobsFreshnessTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6927 mJobsFreshnessBuckets = new Counter[JOB_FRESHNESS_BUCKETS.length];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006928 }
6929
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006930 @VisibleForTesting
6931 public void setProcessStateForTest(int procState) {
6932 mProcessState = procState;
6933 }
6934
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006935 @Override
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006936 public long[] getCpuFreqTimes(int which) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006937 return nullIfAllZeros(mCpuFreqTimeMs, which);
6938 }
6939
6940 @Override
6941 public long[] getScreenOffCpuFreqTimes(int which) {
6942 return nullIfAllZeros(mScreenOffCpuFreqTimeMs, which);
6943 }
6944
6945 @Override
Mike Ma3d422c32017-10-25 11:08:57 -07006946 public long getCpuActiveTime() {
6947 return mCpuActiveTimeMs.getCountLocked(STATS_SINCE_CHARGED);
6948 }
6949
6950 @Override
6951 public long[] getCpuClusterTimes() {
6952 return nullIfAllZeros(mCpuClusterTimesMs, STATS_SINCE_CHARGED);
6953 }
6954
6955
6956 @Override
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006957 public long[] getCpuFreqTimes(int which, int procState) {
6958 if (which < 0 || which >= NUM_PROCESS_STATE) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006959 return null;
6960 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006961 if (mProcStateTimeMs == null) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006962 return null;
6963 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006964 if (!mBsi.mPerProcStateCpuTimesAvailable) {
6965 mProcStateTimeMs = null;
6966 return null;
6967 }
6968 return nullIfAllZeros(mProcStateTimeMs[procState], which);
6969 }
6970
6971 @Override
6972 public long[] getScreenOffCpuFreqTimes(int which, int procState) {
6973 if (which < 0 || which >= NUM_PROCESS_STATE) {
6974 return null;
6975 }
6976 if (mProcStateScreenOffTimeMs == null) {
6977 return null;
6978 }
6979 if (!mBsi.mPerProcStateCpuTimesAvailable) {
6980 mProcStateScreenOffTimeMs = null;
6981 return null;
6982 }
6983 return nullIfAllZeros(mProcStateScreenOffTimeMs[procState], which);
6984 }
6985
6986 public void addIsolatedUid(int isolatedUid) {
6987 if (mChildUids == null) {
6988 mChildUids = new IntArray();
6989 } else if (mChildUids.indexOf(isolatedUid) >= 0) {
6990 return;
6991 }
6992 mChildUids.add(isolatedUid);
6993 }
6994
6995 public void removeIsolatedUid(int isolatedUid) {
6996 final int idx = mChildUids == null ? -1 : mChildUids.indexOf(isolatedUid);
6997 if (idx < 0) {
6998 return;
6999 }
7000 mChildUids.remove(idx);
7001 }
7002
7003 private long[] nullIfAllZeros(LongSamplingCounterArray cpuTimesMs, int which) {
7004 if (cpuTimesMs == null) {
7005 return null;
7006 }
7007 final long[] counts = cpuTimesMs.getCountsLocked(which);
7008 if (counts == null) {
7009 return null;
7010 }
7011 // Return counts only if at least one of the elements is non-zero.
7012 for (int i = counts.length - 1; i >= 0; --i) {
7013 if (counts[i] != 0) {
7014 return counts;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007015 }
7016 }
7017 return null;
7018 }
7019
Sudheer Shankae544d162017-12-28 17:06:20 -08007020 private void addProcStateTimesMs(int procState, long[] cpuTimesMs, boolean onBattery) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007021 if (mProcStateTimeMs == null) {
7022 mProcStateTimeMs = new LongSamplingCounterArray[NUM_PROCESS_STATE];
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007023 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007024 if (mProcStateTimeMs[procState] == null
7025 || mProcStateTimeMs[procState].getSize() != cpuTimesMs.length) {
7026 mProcStateTimeMs[procState] = new LongSamplingCounterArray(
7027 mBsi.mOnBatteryTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007028 }
Sudheer Shankae544d162017-12-28 17:06:20 -08007029 mProcStateTimeMs[procState].addCountLocked(cpuTimesMs, onBattery);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007030 }
7031
Sudheer Shankae544d162017-12-28 17:06:20 -08007032 private void addProcStateScreenOffTimesMs(int procState, long[] cpuTimesMs,
7033 boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007034 if (mProcStateScreenOffTimeMs == null) {
7035 mProcStateScreenOffTimeMs = new LongSamplingCounterArray[NUM_PROCESS_STATE];
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007036 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007037 if (mProcStateScreenOffTimeMs[procState] == null
7038 || mProcStateScreenOffTimeMs[procState].getSize() != cpuTimesMs.length) {
7039 mProcStateScreenOffTimeMs[procState] = new LongSamplingCounterArray(
7040 mBsi.mOnBatteryScreenOffTimeBase);
7041 }
Sudheer Shankae544d162017-12-28 17:06:20 -08007042 mProcStateScreenOffTimeMs[procState].addCountLocked(cpuTimesMs, onBatteryScreenOff);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007043 }
7044
7045 @Override
Bookatzc8c44962017-05-11 12:12:54 -07007046 public Timer getAggregatedPartialWakelockTimer() {
7047 return mAggregatedPartialWakelockTimer;
7048 }
7049
7050 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01007051 @UnsupportedAppUsage
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007052 public ArrayMap<String, ? extends BatteryStats.Uid.Wakelock> getWakelockStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007053 return mWakelockStats.getMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007054 }
7055
7056 @Override
Ahmed ElArabawyddd09692017-10-30 17:58:29 -07007057 public Timer getMulticastWakelockStats() {
7058 return mWifiMulticastTimer;
7059 }
7060
7061 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007062 public ArrayMap<String, ? extends BatteryStats.Timer> getSyncStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007063 return mSyncStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007064 }
7065
7066 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007067 public ArrayMap<String, ? extends BatteryStats.Timer> getJobStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007068 return mJobStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007069 }
7070
7071 @Override
Dianne Hackborn94326cb2017-06-28 16:17:20 -07007072 public ArrayMap<String, SparseIntArray> getJobCompletionStats() {
7073 return mJobCompletions;
7074 }
7075
7076 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01007077 @UnsupportedAppUsage
Dianne Hackborn61659e52014-07-09 16:13:01 -07007078 public SparseArray<? extends BatteryStats.Uid.Sensor> getSensorStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007079 return mSensorStats;
7080 }
7081
7082 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01007083 @UnsupportedAppUsage
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007084 public ArrayMap<String, ? extends BatteryStats.Uid.Proc> getProcessStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007085 return mProcessStats;
7086 }
7087
7088 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007089 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg> getPackageStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007090 return mPackageStats;
7091 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007092
7093 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01007094 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007095 public int getUid() {
7096 return mUid;
7097 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007098
7099 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007100 public void noteWifiRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007101 if (!mWifiRunning) {
7102 mWifiRunning = true;
7103 if (mWifiRunningTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007104 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
7105 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007106 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007107 mWifiRunningTimer.startRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007108 }
7109 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007110
Dianne Hackborn617f8772009-03-31 15:04:46 -07007111 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007112 public void noteWifiStoppedLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007113 if (mWifiRunning) {
7114 mWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007115 mWifiRunningTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007116 }
7117 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007118
Dianne Hackborn617f8772009-03-31 15:04:46 -07007119 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007120 public void noteFullWifiLockAcquiredLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07007121 if (!mFullWifiLockOut) {
7122 mFullWifiLockOut = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007123 if (mFullWifiLockTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007124 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
7125 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007126 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007127 mFullWifiLockTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007128 }
7129 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007130
The Android Open Source Project10592532009-03-18 17:39:46 -07007131 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007132 public void noteFullWifiLockReleasedLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07007133 if (mFullWifiLockOut) {
7134 mFullWifiLockOut = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007135 mFullWifiLockTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007136 }
7137 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007138
The Android Open Source Project10592532009-03-18 17:39:46 -07007139 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007140 public void noteWifiScanStartedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007141 if (!mWifiScanStarted) {
7142 mWifiScanStarted = true;
7143 if (mWifiScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007144 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
7145 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase,
7146 mOnBatteryBackgroundTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007147 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007148 mWifiScanTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007149 }
7150 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007151
The Android Open Source Project10592532009-03-18 17:39:46 -07007152 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007153 public void noteWifiScanStoppedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007154 if (mWifiScanStarted) {
7155 mWifiScanStarted = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007156 mWifiScanTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007157 }
7158 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007159
7160 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007161 public void noteWifiBatchedScanStartedLocked(int csph, long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007162 int bin = 0;
Navtej Singh Mann3c0ce5c2015-06-11 16:53:11 -07007163 while (csph > 8 && bin < NUM_WIFI_BATCHED_SCAN_BINS-1) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007164 csph = csph >> 3;
7165 bin++;
7166 }
7167
7168 if (mWifiBatchedScanBinStarted == bin) return;
7169
7170 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
7171 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007172 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007173 }
7174 mWifiBatchedScanBinStarted = bin;
7175 if (mWifiBatchedScanTimer[bin] == null) {
7176 makeWifiBatchedScanBin(bin, null);
7177 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007178 mWifiBatchedScanTimer[bin].startRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007179 }
7180
7181 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007182 public void noteWifiBatchedScanStoppedLocked(long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007183 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
7184 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007185 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007186 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
7187 }
7188 }
7189
7190 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007191 public void noteWifiMulticastEnabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007192 if (!mWifiMulticastEnabled) {
7193 mWifiMulticastEnabled = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007194 if (mWifiMulticastTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007195 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7196 WIFI_MULTICAST_ENABLED, mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007197 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007198 mWifiMulticastTimer.startRunningLocked(elapsedRealtimeMs);
Tej Singh4503e102018-01-04 14:35:01 -08007199 StatsLog.write_non_chained(
Bookatz90867622018-01-31 15:05:57 -08007200 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED, getUid(), null,
7201 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED__STATE__ON);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007202 }
7203 }
7204
7205 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007206 public void noteWifiMulticastDisabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007207 if (mWifiMulticastEnabled) {
7208 mWifiMulticastEnabled = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007209 mWifiMulticastTimer.stopRunningLocked(elapsedRealtimeMs);
Tej Singh4503e102018-01-04 14:35:01 -08007210 StatsLog.write_non_chained(
Bookatz90867622018-01-31 15:05:57 -08007211 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED, getUid(), null,
7212 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED__STATE__OFF);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007213 }
7214 }
7215
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007216 @Override
7217 public ControllerActivityCounter getWifiControllerActivity() {
7218 return mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07007219 }
7220
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007221 @Override
7222 public ControllerActivityCounter getBluetoothControllerActivity() {
7223 return mBluetoothControllerActivity;
7224 }
7225
7226 @Override
7227 public ControllerActivityCounter getModemControllerActivity() {
7228 return mModemControllerActivity;
7229 }
7230
7231 public ControllerActivityCounterImpl getOrCreateWifiControllerActivityLocked() {
7232 if (mWifiControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007233 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007234 NUM_BT_TX_LEVELS);
Adam Lesinski50e47602015-12-04 17:04:54 -08007235 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007236 return mWifiControllerActivity;
7237 }
7238
7239 public ControllerActivityCounterImpl getOrCreateBluetoothControllerActivityLocked() {
7240 if (mBluetoothControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007241 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007242 NUM_BT_TX_LEVELS);
7243 }
7244 return mBluetoothControllerActivity;
7245 }
7246
7247 public ControllerActivityCounterImpl getOrCreateModemControllerActivityLocked() {
7248 if (mModemControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007249 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007250 ModemActivityInfo.TX_POWER_LEVELS);
7251 }
7252 return mModemControllerActivity;
Adam Lesinski50e47602015-12-04 17:04:54 -08007253 }
7254
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007255 public StopwatchTimer createAudioTurnedOnTimerLocked() {
7256 if (mAudioTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007257 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
7258 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007259 }
7260 return mAudioTurnedOnTimer;
7261 }
7262
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007263 public void noteAudioTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007264 createAudioTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
7265 }
7266
7267 public void noteAudioTurnedOffLocked(long elapsedRealtimeMs) {
7268 if (mAudioTurnedOnTimer != null) {
7269 mAudioTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007270 }
7271 }
7272
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007273 public void noteResetAudioLocked(long elapsedRealtimeMs) {
7274 if (mAudioTurnedOnTimer != null) {
7275 mAudioTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007276 }
7277 }
7278
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007279 public StopwatchTimer createVideoTurnedOnTimerLocked() {
7280 if (mVideoTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007281 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
7282 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007283 }
7284 return mVideoTurnedOnTimer;
7285 }
7286
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007287 public void noteVideoTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007288 createVideoTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
7289 }
7290
7291 public void noteVideoTurnedOffLocked(long elapsedRealtimeMs) {
7292 if (mVideoTurnedOnTimer != null) {
7293 mVideoTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007294 }
7295 }
7296
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007297 public void noteResetVideoLocked(long elapsedRealtimeMs) {
7298 if (mVideoTurnedOnTimer != null) {
7299 mVideoTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007300 }
7301 }
7302
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007303 public StopwatchTimer createFlashlightTurnedOnTimerLocked() {
7304 if (mFlashlightTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007305 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7306 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007307 }
7308 return mFlashlightTurnedOnTimer;
7309 }
7310
7311 public void noteFlashlightTurnedOnLocked(long elapsedRealtimeMs) {
7312 createFlashlightTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
7313 }
7314
7315 public void noteFlashlightTurnedOffLocked(long elapsedRealtimeMs) {
7316 if (mFlashlightTurnedOnTimer != null) {
7317 mFlashlightTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
7318 }
7319 }
7320
7321 public void noteResetFlashlightLocked(long elapsedRealtimeMs) {
7322 if (mFlashlightTurnedOnTimer != null) {
7323 mFlashlightTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
7324 }
7325 }
7326
7327 public StopwatchTimer createCameraTurnedOnTimerLocked() {
7328 if (mCameraTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007329 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
7330 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007331 }
7332 return mCameraTurnedOnTimer;
7333 }
7334
7335 public void noteCameraTurnedOnLocked(long elapsedRealtimeMs) {
7336 createCameraTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
7337 }
7338
7339 public void noteCameraTurnedOffLocked(long elapsedRealtimeMs) {
7340 if (mCameraTurnedOnTimer != null) {
7341 mCameraTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
7342 }
7343 }
7344
7345 public void noteResetCameraLocked(long elapsedRealtimeMs) {
7346 if (mCameraTurnedOnTimer != null) {
7347 mCameraTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
7348 }
7349 }
7350
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007351 public StopwatchTimer createForegroundActivityTimerLocked() {
7352 if (mForegroundActivityTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007353 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7354 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007355 }
7356 return mForegroundActivityTimer;
7357 }
7358
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007359 public StopwatchTimer createForegroundServiceTimerLocked() {
7360 if (mForegroundServiceTimer == null) {
7361 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7362 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase);
7363 }
7364 return mForegroundServiceTimer;
7365 }
7366
Bookatzc8c44962017-05-11 12:12:54 -07007367 public DualTimer createAggregatedPartialWakelockTimerLocked() {
7368 if (mAggregatedPartialWakelockTimer == null) {
7369 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
7370 AGGREGATED_WAKE_TYPE_PARTIAL, null,
7371 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase);
7372 }
7373 return mAggregatedPartialWakelockTimer;
7374 }
7375
Bookatz867c0d72017-03-07 18:23:42 -08007376 public DualTimer createBluetoothScanTimerLocked() {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007377 if (mBluetoothScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007378 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
7379 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
7380 mOnBatteryBackgroundTimeBase);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007381 }
7382 return mBluetoothScanTimer;
7383 }
7384
Bookatzb1f04f32017-05-19 13:57:32 -07007385 public DualTimer createBluetoothUnoptimizedScanTimerLocked() {
7386 if (mBluetoothUnoptimizedScanTimer == null) {
7387 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
7388 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
7389 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
7390 }
7391 return mBluetoothUnoptimizedScanTimer;
7392 }
7393
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00007394 public void noteBluetoothScanStartedLocked(long elapsedRealtimeMs,
7395 boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007396 createBluetoothScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatzb1f04f32017-05-19 13:57:32 -07007397 if (isUnoptimized) {
7398 createBluetoothUnoptimizedScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
7399 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007400 }
7401
Bookatz94c5a312017-07-11 16:49:17 -07007402 public void noteBluetoothScanStoppedLocked(long elapsedRealtimeMs, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007403 if (mBluetoothScanTimer != null) {
7404 mBluetoothScanTimer.stopRunningLocked(elapsedRealtimeMs);
7405 }
Bookatz94c5a312017-07-11 16:49:17 -07007406 if (isUnoptimized && mBluetoothUnoptimizedScanTimer != null) {
Bookatzb1f04f32017-05-19 13:57:32 -07007407 mBluetoothUnoptimizedScanTimer.stopRunningLocked(elapsedRealtimeMs);
7408 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007409 }
7410
7411 public void noteResetBluetoothScanLocked(long elapsedRealtimeMs) {
7412 if (mBluetoothScanTimer != null) {
7413 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
7414 }
Bookatzb1f04f32017-05-19 13:57:32 -07007415 if (mBluetoothUnoptimizedScanTimer != null) {
7416 mBluetoothUnoptimizedScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
7417 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007418 }
7419
Bookatz956f36bf2017-04-28 09:48:17 -07007420 public Counter createBluetoothScanResultCounterLocked() {
7421 if (mBluetoothScanResultCounter == null) {
7422 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase);
7423 }
7424 return mBluetoothScanResultCounter;
7425 }
7426
Bookatzb1f04f32017-05-19 13:57:32 -07007427 public Counter createBluetoothScanResultBgCounterLocked() {
7428 if (mBluetoothScanResultBgCounter == null) {
7429 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase);
7430 }
7431 return mBluetoothScanResultBgCounter;
7432 }
7433
Bookatz4ebc0642017-05-11 12:21:19 -07007434 public void noteBluetoothScanResultsLocked(int numNewResults) {
7435 createBluetoothScanResultCounterLocked().addAtomic(numNewResults);
Bookatzb1f04f32017-05-19 13:57:32 -07007436 // Uses background timebase, so the count will only be incremented if uid in background.
7437 createBluetoothScanResultBgCounterLocked().addAtomic(numNewResults);
Bookatz956f36bf2017-04-28 09:48:17 -07007438 }
7439
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007440 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007441 public void noteActivityResumedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007442 // We always start, since we want multiple foreground PIDs to nest
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007443 createForegroundActivityTimerLocked().startRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007444 }
7445
7446 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007447 public void noteActivityPausedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007448 if (mForegroundActivityTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007449 mForegroundActivityTimer.stopRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007450 }
7451 }
7452
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007453 public void noteForegroundServiceResumedLocked(long elapsedRealtimeMs) {
7454 createForegroundServiceTimerLocked().startRunningLocked(elapsedRealtimeMs);
7455 }
7456
7457 public void noteForegroundServicePausedLocked(long elapsedRealtimeMs) {
7458 if (mForegroundServiceTimer != null) {
7459 mForegroundServiceTimer.stopRunningLocked(elapsedRealtimeMs);
7460 }
7461 }
7462
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007463 public BatchTimer createVibratorOnTimerLocked() {
7464 if (mVibratorOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007465 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
7466 mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007467 }
7468 return mVibratorOnTimer;
7469 }
7470
7471 public void noteVibratorOnLocked(long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08007472 createVibratorOnTimerLocked().addDuration(mBsi, durationMillis);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007473 }
7474
7475 public void noteVibratorOffLocked() {
7476 if (mVibratorOnTimer != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007477 mVibratorOnTimer.abortLastDuration(mBsi);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007478 }
7479 }
7480
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007481 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01007482 @UnsupportedAppUsage
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007483 public long getWifiRunningTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007484 if (mWifiRunningTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007485 return 0;
7486 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007487 return mWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007488 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07007489
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007490 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007491 public long getFullWifiLockTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007492 if (mFullWifiLockTimer == null) {
7493 return 0;
7494 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007495 return mFullWifiLockTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07007496 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007497
7498 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01007499 @UnsupportedAppUsage
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007500 public long getWifiScanTime(long elapsedRealtimeUs, int which) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007501 if (mWifiScanTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007502 return 0;
7503 }
Bookatzaa4594a2017-03-24 12:39:56 -07007504 return mWifiScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07007505 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007506
7507 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07007508 public int getWifiScanCount(int which) {
7509 if (mWifiScanTimer == null) {
7510 return 0;
7511 }
Bookatzaa4594a2017-03-24 12:39:56 -07007512 return mWifiScanTimer.getCountLocked(which);
Bookatz867c0d72017-03-07 18:23:42 -08007513 }
7514
7515 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07007516 public Timer getWifiScanTimer() {
7517 return mWifiScanTimer;
7518 }
7519
7520 @Override
Bookatz867c0d72017-03-07 18:23:42 -08007521 public int getWifiScanBackgroundCount(int which) {
Bookatzaa4594a2017-03-24 12:39:56 -07007522 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007523 return 0;
7524 }
7525 return mWifiScanTimer.getSubTimer().getCountLocked(which);
7526 }
7527
7528 @Override
7529 public long getWifiScanActualTime(final long elapsedRealtimeUs) {
7530 if (mWifiScanTimer == null) {
7531 return 0;
7532 }
7533 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
Bookatzaa4594a2017-03-24 12:39:56 -07007534 return mWifiScanTimer.getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Bookatz867c0d72017-03-07 18:23:42 -08007535 }
7536
7537 @Override
7538 public long getWifiScanBackgroundTime(final long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07007539 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007540 return 0;
7541 }
7542 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
7543 return mWifiScanTimer.getSubTimer().getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Dianne Hackborn62793e42015-03-09 11:15:41 -07007544 }
7545
7546 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07007547 public Timer getWifiScanBackgroundTimer() {
7548 if (mWifiScanTimer == null) {
7549 return null;
7550 }
7551 return mWifiScanTimer.getSubTimer();
7552 }
7553
7554 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007555 public long getWifiBatchedScanTime(int csphBin, long elapsedRealtimeUs, int which) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007556 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
7557 if (mWifiBatchedScanTimer[csphBin] == null) {
7558 return 0;
7559 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007560 return mWifiBatchedScanTimer[csphBin].getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007561 }
7562
7563 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07007564 public int getWifiBatchedScanCount(int csphBin, int which) {
7565 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
7566 if (mWifiBatchedScanTimer[csphBin] == null) {
7567 return 0;
7568 }
7569 return mWifiBatchedScanTimer[csphBin].getCountLocked(which);
7570 }
7571
7572 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007573 public long getWifiMulticastTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007574 if (mWifiMulticastTimer == null) {
7575 return 0;
7576 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007577 return mWifiMulticastTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007578 }
7579
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007580 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007581 public Timer getAudioTurnedOnTimer() {
7582 return mAudioTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007583 }
7584
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007585 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007586 public Timer getVideoTurnedOnTimer() {
7587 return mVideoTurnedOnTimer;
7588 }
7589
7590 @Override
7591 public Timer getFlashlightTurnedOnTimer() {
7592 return mFlashlightTurnedOnTimer;
7593 }
7594
7595 @Override
7596 public Timer getCameraTurnedOnTimer() {
7597 return mCameraTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007598 }
7599
Dianne Hackborn617f8772009-03-31 15:04:46 -07007600 @Override
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007601 public Timer getForegroundActivityTimer() {
7602 return mForegroundActivityTimer;
7603 }
7604
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007605 @Override
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007606 public Timer getForegroundServiceTimer() {
7607 return mForegroundServiceTimer;
7608 }
7609
7610 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007611 public Timer getBluetoothScanTimer() {
Bookatzaa4594a2017-03-24 12:39:56 -07007612 return mBluetoothScanTimer;
Bookatz867c0d72017-03-07 18:23:42 -08007613 }
7614
7615 @Override
7616 public Timer getBluetoothScanBackgroundTimer() {
7617 if (mBluetoothScanTimer == null) {
7618 return null;
7619 }
7620 return mBluetoothScanTimer.getSubTimer();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007621 }
7622
Bookatz956f36bf2017-04-28 09:48:17 -07007623 @Override
Bookatzb1f04f32017-05-19 13:57:32 -07007624 public Timer getBluetoothUnoptimizedScanTimer() {
7625 return mBluetoothUnoptimizedScanTimer;
7626 }
7627
7628 @Override
7629 public Timer getBluetoothUnoptimizedScanBackgroundTimer() {
7630 if (mBluetoothUnoptimizedScanTimer == null) {
7631 return null;
7632 }
7633 return mBluetoothUnoptimizedScanTimer.getSubTimer();
7634 }
7635
7636 @Override
Bookatz956f36bf2017-04-28 09:48:17 -07007637 public Counter getBluetoothScanResultCounter() {
7638 return mBluetoothScanResultCounter;
7639 }
7640
Bookatzb1f04f32017-05-19 13:57:32 -07007641 @Override
7642 public Counter getBluetoothScanResultBgCounter() {
7643 return mBluetoothScanResultBgCounter;
7644 }
7645
Dianne Hackborn61659e52014-07-09 16:13:01 -07007646 void makeProcessState(int i, Parcel in) {
7647 if (i < 0 || i >= NUM_PROCESS_STATE) return;
7648
7649 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007650 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
7651 mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007652 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08007653 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
7654 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007655 }
7656 }
7657
7658 @Override
7659 public long getProcessStateTime(int state, long elapsedRealtimeUs, int which) {
7660 if (state < 0 || state >= NUM_PROCESS_STATE) return 0;
7661 if (mProcessStateTimer[state] == null) {
7662 return 0;
7663 }
7664 return mProcessStateTimer[state].getTotalTimeLocked(elapsedRealtimeUs, which);
7665 }
7666
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007667 @Override
Joe Onorato713fec82016-03-04 10:34:02 -08007668 public Timer getProcessStateTimer(int state) {
7669 if (state < 0 || state >= NUM_PROCESS_STATE) return null;
7670 return mProcessStateTimer[state];
7671 }
7672
7673 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007674 public Timer getVibratorOnTimer() {
7675 return mVibratorOnTimer;
7676 }
7677
7678 @Override
Dianne Hackborn617f8772009-03-31 15:04:46 -07007679 public void noteUserActivityLocked(int type) {
7680 if (mUserActivityCounters == null) {
7681 initUserActivityLocked();
7682 }
Jeff Browndf693de2012-07-27 12:03:38 -07007683 if (type >= 0 && type < NUM_USER_ACTIVITY_TYPES) {
7684 mUserActivityCounters[type].stepAtomic();
7685 } else {
7686 Slog.w(TAG, "Unknown user activity type " + type + " was specified.",
7687 new Throwable());
7688 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07007689 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007690
Dianne Hackborn617f8772009-03-31 15:04:46 -07007691 @Override
7692 public boolean hasUserActivity() {
7693 return mUserActivityCounters != null;
7694 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007695
Dianne Hackborn617f8772009-03-31 15:04:46 -07007696 @Override
7697 public int getUserActivityCount(int type, int which) {
7698 if (mUserActivityCounters == null) {
7699 return 0;
7700 }
Evan Millarc64edde2009-04-18 12:26:32 -07007701 return mUserActivityCounters[type].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007702 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007703
Robert Greenwalta029ea12013-09-25 16:38:12 -07007704 void makeWifiBatchedScanBin(int i, Parcel in) {
7705 if (i < 0 || i >= NUM_WIFI_BATCHED_SCAN_BINS) return;
7706
Joe Onoratoabded112016-02-08 16:49:39 -08007707 ArrayList<StopwatchTimer> collected = mBsi.mWifiBatchedScanTimers.get(i);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007708 if (collected == null) {
7709 collected = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08007710 mBsi.mWifiBatchedScanTimers.put(i, collected);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007711 }
7712 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007713 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
7714 collected, mBsi.mOnBatteryTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007715 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08007716 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
7717 collected, mBsi.mOnBatteryTimeBase, in);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007718 }
7719 }
7720
7721
Dianne Hackborn617f8772009-03-31 15:04:46 -07007722 void initUserActivityLocked() {
7723 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
7724 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007725 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007726 }
7727 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007728
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007729 void noteNetworkActivityLocked(int type, long deltaBytes, long deltaPackets) {
7730 if (mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007731 initNetworkActivityLocked();
7732 }
7733 if (type >= 0 && type < NUM_NETWORK_ACTIVITY_TYPES) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007734 mNetworkByteActivityCounters[type].addCountLocked(deltaBytes);
7735 mNetworkPacketActivityCounters[type].addCountLocked(deltaPackets);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007736 } else {
7737 Slog.w(TAG, "Unknown network activity type " + type + " was specified.",
7738 new Throwable());
7739 }
7740 }
7741
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007742 void noteMobileRadioActiveTimeLocked(long batteryUptime) {
7743 if (mNetworkByteActivityCounters == null) {
7744 initNetworkActivityLocked();
7745 }
7746 mMobileRadioActiveTime.addCountLocked(batteryUptime);
7747 mMobileRadioActiveCount.addCountLocked(1);
7748 }
7749
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007750 @Override
7751 public boolean hasNetworkActivity() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007752 return mNetworkByteActivityCounters != null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007753 }
7754
7755 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007756 public long getNetworkActivityBytes(int type, int which) {
7757 if (mNetworkByteActivityCounters != null && type >= 0
7758 && type < mNetworkByteActivityCounters.length) {
7759 return mNetworkByteActivityCounters[type].getCountLocked(which);
7760 } else {
7761 return 0;
7762 }
7763 }
7764
7765 @Override
7766 public long getNetworkActivityPackets(int type, int which) {
7767 if (mNetworkPacketActivityCounters != null && type >= 0
7768 && type < mNetworkPacketActivityCounters.length) {
7769 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007770 } else {
7771 return 0;
7772 }
7773 }
7774
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007775 @Override
7776 public long getMobileRadioActiveTime(int which) {
7777 return mMobileRadioActiveTime != null
7778 ? mMobileRadioActiveTime.getCountLocked(which) : 0;
7779 }
7780
7781 @Override
7782 public int getMobileRadioActiveCount(int which) {
7783 return mMobileRadioActiveCount != null
7784 ? (int)mMobileRadioActiveCount.getCountLocked(which) : 0;
7785 }
7786
Adam Lesinskie08af192015-03-25 16:42:59 -07007787 @Override
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007788 public long getUserCpuTimeUs(int which) {
7789 return mUserCpuTime.getCountLocked(which);
7790 }
7791
7792 @Override
7793 public long getSystemCpuTimeUs(int which) {
7794 return mSystemCpuTime.getCountLocked(which);
7795 }
7796
7797 @Override
Adam Lesinski6832f392015-09-05 18:05:40 -07007798 public long getTimeAtCpuSpeed(int cluster, int step, int which) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07007799 if (mCpuClusterSpeedTimesUs != null) {
7800 if (cluster >= 0 && cluster < mCpuClusterSpeedTimesUs.length) {
7801 final LongSamplingCounter[] cpuSpeedTimesUs = mCpuClusterSpeedTimesUs[cluster];
7802 if (cpuSpeedTimesUs != null) {
7803 if (step >= 0 && step < cpuSpeedTimesUs.length) {
7804 final LongSamplingCounter c = cpuSpeedTimesUs[step];
Adam Lesinski6832f392015-09-05 18:05:40 -07007805 if (c != null) {
7806 return c.getCountLocked(which);
7807 }
7808 }
7809 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007810 }
7811 }
7812 return 0;
7813 }
7814
Adam Lesinski5f056f62016-07-14 16:56:08 -07007815 public void noteMobileRadioApWakeupLocked() {
7816 if (mMobileRadioApWakeupCount == null) {
7817 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7818 }
7819 mMobileRadioApWakeupCount.addCountLocked(1);
7820 }
7821
7822 @Override
7823 public long getMobileRadioApWakeupCount(int which) {
7824 if (mMobileRadioApWakeupCount != null) {
7825 return mMobileRadioApWakeupCount.getCountLocked(which);
7826 }
7827 return 0;
7828 }
7829
7830 public void noteWifiRadioApWakeupLocked() {
7831 if (mWifiRadioApWakeupCount == null) {
7832 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7833 }
7834 mWifiRadioApWakeupCount.addCountLocked(1);
7835 }
7836
7837 @Override
7838 public long getWifiRadioApWakeupCount(int which) {
7839 if (mWifiRadioApWakeupCount != null) {
7840 return mWifiRadioApWakeupCount.getCountLocked(which);
7841 }
7842 return 0;
7843 }
7844
Amith Yamasani977e11f2018-02-16 11:29:54 -08007845 @Override
7846 public void getDeferredJobsCheckinLineLocked(StringBuilder sb, int which) {
7847 sb.setLength(0);
7848 final int deferredEventCount = mJobsDeferredEventCount.getCountLocked(which);
7849 if (deferredEventCount == 0) {
7850 return;
7851 }
7852 final int deferredCount = mJobsDeferredCount.getCountLocked(which);
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007853 final long totalLatency = mJobsFreshnessTimeMs.getCountLocked(which);
Amith Yamasani977e11f2018-02-16 11:29:54 -08007854 sb.append(deferredEventCount); sb.append(',');
7855 sb.append(deferredCount); sb.append(',');
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007856 sb.append(totalLatency);
Amith Yamasani977e11f2018-02-16 11:29:54 -08007857 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
7858 if (mJobsFreshnessBuckets[i] == null) {
7859 sb.append(",0");
7860 } else {
7861 sb.append(",");
7862 sb.append(mJobsFreshnessBuckets[i].getCountLocked(which));
7863 }
7864 }
7865 }
7866
7867 @Override
7868 public void getDeferredJobsLineLocked(StringBuilder sb, int which) {
7869 sb.setLength(0);
7870 final int deferredEventCount = mJobsDeferredEventCount.getCountLocked(which);
7871 if (deferredEventCount == 0) {
7872 return;
7873 }
7874 final int deferredCount = mJobsDeferredCount.getCountLocked(which);
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007875 final long totalLatency = mJobsFreshnessTimeMs.getCountLocked(which);
Amith Yamasani977e11f2018-02-16 11:29:54 -08007876 sb.append("times="); sb.append(deferredEventCount); sb.append(", ");
7877 sb.append("count="); sb.append(deferredCount); sb.append(", ");
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007878 sb.append("totalLatencyMs="); sb.append(totalLatency); sb.append(", ");
Amith Yamasani977e11f2018-02-16 11:29:54 -08007879 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
7880 sb.append("<"); sb.append(JOB_FRESHNESS_BUCKETS[i]); sb.append("ms=");
7881 if (mJobsFreshnessBuckets[i] == null) {
7882 sb.append("0");
7883 } else {
7884 sb.append(mJobsFreshnessBuckets[i].getCountLocked(which));
7885 }
7886 sb.append(" ");
7887 }
7888 }
7889
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007890 void initNetworkActivityLocked() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007891 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
7892 mNetworkPacketActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007893 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007894 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7895 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007896 }
Joe Onoratoabded112016-02-08 16:49:39 -08007897 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7898 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007899 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07007900
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007901 /**
7902 * Clear all stats for this uid. Returns true if the uid is completely
7903 * inactive so can be dropped.
7904 */
Adam Lesinski5f212c82017-03-13 12:25:13 -07007905 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
Bookatz993a0be2017-07-21 09:03:23 -07007906 public boolean reset(long uptime, long realtime) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007907 boolean active = false;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007908
Bookatz993a0be2017-07-21 09:03:23 -07007909 mOnBatteryBackgroundTimeBase.init(uptime, realtime);
7910 mOnBatteryScreenOffBackgroundTimeBase.init(uptime, realtime);
7911
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007912 if (mWifiRunningTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007913 active |= !mWifiRunningTimer.reset(false);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007914 active |= mWifiRunning;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007915 }
7916 if (mFullWifiLockTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007917 active |= !mFullWifiLockTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007918 active |= mFullWifiLockOut;
7919 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07007920 if (mWifiScanTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007921 active |= !mWifiScanTimer.reset(false);
Nick Pelly6ccaa542012-06-15 15:22:47 -07007922 active |= mWifiScanStarted;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007923 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07007924 if (mWifiBatchedScanTimer != null) {
7925 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
7926 if (mWifiBatchedScanTimer[i] != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007927 active |= !mWifiBatchedScanTimer[i].reset(false);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007928 }
7929 }
7930 active |= (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED);
7931 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007932 if (mWifiMulticastTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007933 active |= !mWifiMulticastTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007934 active |= mWifiMulticastEnabled;
7935 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007936
7937 active |= !resetTimerIfNotNull(mAudioTurnedOnTimer, false);
7938 active |= !resetTimerIfNotNull(mVideoTurnedOnTimer, false);
7939 active |= !resetTimerIfNotNull(mFlashlightTurnedOnTimer, false);
7940 active |= !resetTimerIfNotNull(mCameraTurnedOnTimer, false);
7941 active |= !resetTimerIfNotNull(mForegroundActivityTimer, false);
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007942 active |= !resetTimerIfNotNull(mForegroundServiceTimer, false);
Bookatzc8c44962017-05-11 12:12:54 -07007943 active |= !resetTimerIfNotNull(mAggregatedPartialWakelockTimer, false);
Adam Lesinski5f056f62016-07-14 16:56:08 -07007944 active |= !resetTimerIfNotNull(mBluetoothScanTimer, false);
Bookatzb1f04f32017-05-19 13:57:32 -07007945 active |= !resetTimerIfNotNull(mBluetoothUnoptimizedScanTimer, false);
Bookatz956f36bf2017-04-28 09:48:17 -07007946 if (mBluetoothScanResultCounter != null) {
7947 mBluetoothScanResultCounter.reset(false);
7948 }
Bookatzb1f04f32017-05-19 13:57:32 -07007949 if (mBluetoothScanResultBgCounter != null) {
7950 mBluetoothScanResultBgCounter.reset(false);
7951 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007952
Dianne Hackborn61659e52014-07-09 16:13:01 -07007953 if (mProcessStateTimer != null) {
7954 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
7955 if (mProcessStateTimer[i] != null) {
7956 active |= !mProcessStateTimer[i].reset(false);
7957 }
7958 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08007959 active |= (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007960 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007961 if (mVibratorOnTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007962 if (mVibratorOnTimer.reset(false)) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007963 mVibratorOnTimer.detach();
7964 mVibratorOnTimer = null;
7965 } else {
7966 active = true;
7967 }
7968 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007969
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007970 if (mUserActivityCounters != null) {
7971 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
7972 mUserActivityCounters[i].reset(false);
7973 }
7974 }
7975
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007976 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007977 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007978 mNetworkByteActivityCounters[i].reset(false);
7979 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007980 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007981 mMobileRadioActiveTime.reset(false);
7982 mMobileRadioActiveCount.reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007983 }
7984
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007985 if (mWifiControllerActivity != null) {
7986 mWifiControllerActivity.reset(false);
7987 }
Adam Lesinskie08af192015-03-25 16:42:59 -07007988
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07007989 if (mBluetoothControllerActivity != null) {
7990 mBluetoothControllerActivity.reset(false);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007991 }
7992
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07007993 if (mModemControllerActivity != null) {
7994 mModemControllerActivity.reset(false);
Adam Lesinskie08af192015-03-25 16:42:59 -07007995 }
7996
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007997 mUserCpuTime.reset(false);
7998 mSystemCpuTime.reset(false);
Adam Lesinski6832f392015-09-05 18:05:40 -07007999
Sudheer Shankaaf857412017-07-21 00:14:24 -07008000 if (mCpuClusterSpeedTimesUs != null) {
8001 for (LongSamplingCounter[] speeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008002 if (speeds != null) {
8003 for (LongSamplingCounter speed : speeds) {
8004 if (speed != null) {
8005 speed.reset(false);
8006 }
8007 }
8008 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008009 }
8010 }
8011
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008012 if (mCpuFreqTimeMs != null) {
8013 mCpuFreqTimeMs.reset(false);
8014 }
8015 if (mScreenOffCpuFreqTimeMs != null) {
8016 mScreenOffCpuFreqTimeMs.reset(false);
8017 }
8018
Mike Ma3d422c32017-10-25 11:08:57 -07008019 mCpuActiveTimeMs.reset(false);
8020 mCpuClusterTimesMs.reset(false);
8021
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008022 if (mProcStateTimeMs != null) {
8023 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8024 if (counters != null) {
8025 counters.reset(false);
8026 }
8027 }
8028 }
8029 if (mProcStateScreenOffTimeMs != null) {
8030 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8031 if (counters != null) {
8032 counters.reset(false);
8033 }
8034 }
8035 }
8036
Adam Lesinski5f056f62016-07-14 16:56:08 -07008037 resetLongCounterIfNotNull(mMobileRadioApWakeupCount, false);
8038 resetLongCounterIfNotNull(mWifiRadioApWakeupCount, false);
8039
Dianne Hackbornd953c532014-08-16 18:17:38 -07008040 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
8041 for (int iw=wakeStats.size()-1; iw>=0; iw--) {
8042 Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07008043 if (wl.reset()) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008044 wakeStats.removeAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07008045 } else {
8046 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008047 }
8048 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07008049 mWakelockStats.cleanup();
Bookatz2bffb5b2017-04-13 11:59:33 -07008050 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008051 for (int is=syncStats.size()-1; is>=0; is--) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008052 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008053 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008054 syncStats.removeAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008055 timer.detach();
8056 } else {
8057 active = true;
8058 }
8059 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07008060 mSyncStats.cleanup();
Bookatzaa4594a2017-03-24 12:39:56 -07008061 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008062 for (int ij=jobStats.size()-1; ij>=0; ij--) {
Bookatzaa4594a2017-03-24 12:39:56 -07008063 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008064 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008065 jobStats.removeAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008066 timer.detach();
8067 } else {
8068 active = true;
8069 }
8070 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07008071 mJobStats.cleanup();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008072 mJobCompletions.clear();
Amith Yamasani977e11f2018-02-16 11:29:54 -08008073
8074 mJobsDeferredEventCount.reset(false);
8075 mJobsDeferredCount.reset(false);
8076 mJobsFreshnessTimeMs.reset(false);
8077 for (int ij = 0; ij < JOB_FRESHNESS_BUCKETS.length; ij++) {
8078 if (mJobsFreshnessBuckets[ij] != null) {
8079 mJobsFreshnessBuckets[ij].reset(false);
8080 }
8081 }
8082
Dianne Hackborn61659e52014-07-09 16:13:01 -07008083 for (int ise=mSensorStats.size()-1; ise>=0; ise--) {
8084 Sensor s = mSensorStats.valueAt(ise);
8085 if (s.reset()) {
8086 mSensorStats.removeAt(ise);
8087 } else {
8088 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008089 }
8090 }
Amith Yamasani977e11f2018-02-16 11:29:54 -08008091
Dianne Hackborn61659e52014-07-09 16:13:01 -07008092 for (int ip=mProcessStats.size()-1; ip>=0; ip--) {
8093 Proc proc = mProcessStats.valueAt(ip);
Dianne Hackborna8d10942015-11-19 17:55:19 -08008094 proc.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008095 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08008096 mProcessStats.clear();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008097 if (mPids.size() > 0) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008098 for (int i=mPids.size()-1; i>=0; i--) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008099 Pid pid = mPids.valueAt(i);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008100 if (pid.mWakeNesting > 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008101 active = true;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008102 } else {
8103 mPids.removeAt(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008104 }
8105 }
8106 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008107 if (mPackageStats.size() > 0) {
8108 Iterator<Map.Entry<String, Pkg>> it = mPackageStats.entrySet().iterator();
8109 while (it.hasNext()) {
8110 Map.Entry<String, Pkg> pkgEntry = it.next();
8111 Pkg p = pkgEntry.getValue();
8112 p.detach();
8113 if (p.mServiceStats.size() > 0) {
8114 Iterator<Map.Entry<String, Pkg.Serv>> it2
8115 = p.mServiceStats.entrySet().iterator();
8116 while (it2.hasNext()) {
8117 Map.Entry<String, Pkg.Serv> servEntry = it2.next();
8118 servEntry.getValue().detach();
8119 }
8120 }
8121 }
8122 mPackageStats.clear();
8123 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008124
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08008125 mLastStepUserTime = mLastStepSystemTime = 0;
8126 mCurStepUserTime = mCurStepSystemTime = 0;
8127
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008128 if (!active) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008129 if (mWifiRunningTimer != null) {
8130 mWifiRunningTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008131 }
8132 if (mFullWifiLockTimer != null) {
8133 mFullWifiLockTimer.detach();
8134 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008135 if (mWifiScanTimer != null) {
8136 mWifiScanTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008137 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008138 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8139 if (mWifiBatchedScanTimer[i] != null) {
8140 mWifiBatchedScanTimer[i].detach();
8141 }
8142 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008143 if (mWifiMulticastTimer != null) {
8144 mWifiMulticastTimer.detach();
8145 }
8146 if (mAudioTurnedOnTimer != null) {
8147 mAudioTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008148 mAudioTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008149 }
8150 if (mVideoTurnedOnTimer != null) {
8151 mVideoTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008152 mVideoTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008153 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008154 if (mFlashlightTurnedOnTimer != null) {
8155 mFlashlightTurnedOnTimer.detach();
8156 mFlashlightTurnedOnTimer = null;
8157 }
8158 if (mCameraTurnedOnTimer != null) {
8159 mCameraTurnedOnTimer.detach();
8160 mCameraTurnedOnTimer = null;
8161 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008162 if (mForegroundActivityTimer != null) {
8163 mForegroundActivityTimer.detach();
8164 mForegroundActivityTimer = null;
8165 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008166 if (mForegroundServiceTimer != null) {
8167 mForegroundServiceTimer.detach();
8168 mForegroundServiceTimer = null;
8169 }
Bookatzc8c44962017-05-11 12:12:54 -07008170 if (mAggregatedPartialWakelockTimer != null) {
8171 mAggregatedPartialWakelockTimer.detach();
8172 mAggregatedPartialWakelockTimer = null;
8173 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008174 if (mBluetoothScanTimer != null) {
8175 mBluetoothScanTimer.detach();
8176 mBluetoothScanTimer = null;
8177 }
Bookatzb1f04f32017-05-19 13:57:32 -07008178 if (mBluetoothUnoptimizedScanTimer != null) {
8179 mBluetoothUnoptimizedScanTimer.detach();
8180 mBluetoothUnoptimizedScanTimer = null;
8181 }
Bookatz956f36bf2017-04-28 09:48:17 -07008182 if (mBluetoothScanResultCounter != null) {
8183 mBluetoothScanResultCounter.detach();
8184 mBluetoothScanResultCounter = null;
8185 }
Bookatzb1f04f32017-05-19 13:57:32 -07008186 if (mBluetoothScanResultBgCounter != null) {
8187 mBluetoothScanResultBgCounter.detach();
8188 mBluetoothScanResultBgCounter = null;
8189 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008190 if (mUserActivityCounters != null) {
8191 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
8192 mUserActivityCounters[i].detach();
8193 }
8194 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008195 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008196 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008197 mNetworkByteActivityCounters[i].detach();
8198 mNetworkPacketActivityCounters[i].detach();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008199 }
8200 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008201
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008202 if (mWifiControllerActivity != null) {
8203 mWifiControllerActivity.detach();
Adam Lesinskie08af192015-03-25 16:42:59 -07008204 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008205
8206 if (mBluetoothControllerActivity != null) {
8207 mBluetoothControllerActivity.detach();
8208 }
8209
8210 if (mModemControllerActivity != null) {
8211 mModemControllerActivity.detach();
8212 }
8213
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008214 mPids.clear();
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008215
8216 mUserCpuTime.detach();
8217 mSystemCpuTime.detach();
Adam Lesinski6832f392015-09-05 18:05:40 -07008218
Sudheer Shankaaf857412017-07-21 00:14:24 -07008219 if (mCpuClusterSpeedTimesUs != null) {
8220 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008221 if (cpuSpeeds != null) {
8222 for (LongSamplingCounter c : cpuSpeeds) {
8223 if (c != null) {
8224 c.detach();
8225 }
8226 }
8227 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008228 }
8229 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008230
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008231 if (mCpuFreqTimeMs != null) {
8232 mCpuFreqTimeMs.detach();
8233 }
8234 if (mScreenOffCpuFreqTimeMs != null) {
8235 mScreenOffCpuFreqTimeMs.detach();
8236 }
Mike Ma3d422c32017-10-25 11:08:57 -07008237 mCpuActiveTimeMs.detach();
8238 mCpuClusterTimesMs.detach();
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008239
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008240 if (mProcStateTimeMs != null) {
8241 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8242 if (counters != null) {
8243 counters.detach();
8244 }
8245 }
8246 }
8247 if (mProcStateScreenOffTimeMs != null) {
8248 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8249 if (counters != null) {
8250 counters.detach();
8251 }
8252 }
8253 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008254 detachLongCounterIfNotNull(mMobileRadioApWakeupCount);
8255 detachLongCounterIfNotNull(mWifiRadioApWakeupCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008256 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008257
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008258 return !active;
8259 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008260
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008261 void writeJobCompletionsToParcelLocked(Parcel out) {
8262 int NJC = mJobCompletions.size();
8263 out.writeInt(NJC);
8264 for (int ijc=0; ijc<NJC; ijc++) {
8265 out.writeString(mJobCompletions.keyAt(ijc));
8266 SparseIntArray types = mJobCompletions.valueAt(ijc);
8267 int NT = types.size();
8268 out.writeInt(NT);
8269 for (int it=0; it<NT; it++) {
8270 out.writeInt(types.keyAt(it));
8271 out.writeInt(types.valueAt(it));
8272 }
8273 }
8274 }
8275
Bookatz867c0d72017-03-07 18:23:42 -08008276 void writeToParcelLocked(Parcel out, long uptimeUs, long elapsedRealtimeUs) {
8277 mOnBatteryBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatzc8c44962017-05-11 12:12:54 -07008278 mOnBatteryScreenOffBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08008279
Dianne Hackbornd953c532014-08-16 18:17:38 -07008280 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
8281 int NW = wakeStats.size();
Dianne Hackborn61659e52014-07-09 16:13:01 -07008282 out.writeInt(NW);
8283 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008284 out.writeString(wakeStats.keyAt(iw));
8285 Uid.Wakelock wakelock = wakeStats.valueAt(iw);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008286 wakelock.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008287 }
8288
Bookatz2bffb5b2017-04-13 11:59:33 -07008289 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008290 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008291 out.writeInt(NS);
8292 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008293 out.writeString(syncStats.keyAt(is));
Bookatz2bffb5b2017-04-13 11:59:33 -07008294 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008295 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
8296 }
8297
Bookatzaa4594a2017-03-24 12:39:56 -07008298 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008299 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008300 out.writeInt(NJ);
8301 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008302 out.writeString(jobStats.keyAt(ij));
Bookatzaa4594a2017-03-24 12:39:56 -07008303 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008304 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
8305 }
8306
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008307 writeJobCompletionsToParcelLocked(out);
8308
Amith Yamasani977e11f2018-02-16 11:29:54 -08008309 mJobsDeferredEventCount.writeToParcel(out);
8310 mJobsDeferredCount.writeToParcel(out);
8311 mJobsFreshnessTimeMs.writeToParcel(out);
8312 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
8313 Counter.writeCounterToParcel(out, mJobsFreshnessBuckets[i]);
8314 }
8315
Dianne Hackborn61659e52014-07-09 16:13:01 -07008316 int NSE = mSensorStats.size();
8317 out.writeInt(NSE);
8318 for (int ise=0; ise<NSE; ise++) {
8319 out.writeInt(mSensorStats.keyAt(ise));
8320 Uid.Sensor sensor = mSensorStats.valueAt(ise);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008321 sensor.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008322 }
8323
Dianne Hackborn61659e52014-07-09 16:13:01 -07008324 int NP = mProcessStats.size();
8325 out.writeInt(NP);
8326 for (int ip=0; ip<NP; ip++) {
8327 out.writeString(mProcessStats.keyAt(ip));
8328 Uid.Proc proc = mProcessStats.valueAt(ip);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008329 proc.writeToParcelLocked(out);
8330 }
8331
8332 out.writeInt(mPackageStats.size());
8333 for (Map.Entry<String, Uid.Pkg> pkgEntry : mPackageStats.entrySet()) {
8334 out.writeString(pkgEntry.getKey());
8335 Uid.Pkg pkg = pkgEntry.getValue();
8336 pkg.writeToParcelLocked(out);
8337 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008338
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008339 if (mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008340 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008341 mWifiRunningTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008342 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008343 out.writeInt(0);
8344 }
8345 if (mFullWifiLockTimer != null) {
8346 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008347 mFullWifiLockTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008348 } else {
8349 out.writeInt(0);
8350 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008351 if (mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008352 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008353 mWifiScanTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008354 } else {
8355 out.writeInt(0);
8356 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008357 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8358 if (mWifiBatchedScanTimer[i] != null) {
8359 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008360 mWifiBatchedScanTimer[i].writeToParcel(out, elapsedRealtimeUs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07008361 } else {
8362 out.writeInt(0);
8363 }
8364 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008365 if (mWifiMulticastTimer != null) {
8366 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008367 mWifiMulticastTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008368 } else {
8369 out.writeInt(0);
8370 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008371
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008372 if (mAudioTurnedOnTimer != null) {
8373 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008374 mAudioTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008375 } else {
8376 out.writeInt(0);
8377 }
8378 if (mVideoTurnedOnTimer != null) {
8379 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008380 mVideoTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008381 } else {
8382 out.writeInt(0);
8383 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008384 if (mFlashlightTurnedOnTimer != null) {
8385 out.writeInt(1);
8386 mFlashlightTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
8387 } else {
8388 out.writeInt(0);
8389 }
8390 if (mCameraTurnedOnTimer != null) {
8391 out.writeInt(1);
8392 mCameraTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
8393 } else {
8394 out.writeInt(0);
8395 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008396 if (mForegroundActivityTimer != null) {
8397 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008398 mForegroundActivityTimer.writeToParcel(out, elapsedRealtimeUs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008399 } else {
8400 out.writeInt(0);
8401 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008402 if (mForegroundServiceTimer != null) {
8403 out.writeInt(1);
8404 mForegroundServiceTimer.writeToParcel(out, elapsedRealtimeUs);
8405 } else {
8406 out.writeInt(0);
8407 }
Bookatzc8c44962017-05-11 12:12:54 -07008408 if (mAggregatedPartialWakelockTimer != null) {
8409 out.writeInt(1);
8410 mAggregatedPartialWakelockTimer.writeToParcel(out, elapsedRealtimeUs);
8411 } else {
8412 out.writeInt(0);
8413 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008414 if (mBluetoothScanTimer != null) {
8415 out.writeInt(1);
8416 mBluetoothScanTimer.writeToParcel(out, elapsedRealtimeUs);
8417 } else {
8418 out.writeInt(0);
8419 }
Bookatzb1f04f32017-05-19 13:57:32 -07008420 if (mBluetoothUnoptimizedScanTimer != null) {
8421 out.writeInt(1);
8422 mBluetoothUnoptimizedScanTimer.writeToParcel(out, elapsedRealtimeUs);
8423 } else {
8424 out.writeInt(0);
8425 }
Bookatz956f36bf2017-04-28 09:48:17 -07008426 if (mBluetoothScanResultCounter != null) {
8427 out.writeInt(1);
8428 mBluetoothScanResultCounter.writeToParcel(out);
8429 } else {
8430 out.writeInt(0);
8431 }
Bookatzb1f04f32017-05-19 13:57:32 -07008432 if (mBluetoothScanResultBgCounter != null) {
8433 out.writeInt(1);
8434 mBluetoothScanResultBgCounter.writeToParcel(out);
8435 } else {
8436 out.writeInt(0);
8437 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07008438 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8439 if (mProcessStateTimer[i] != null) {
8440 out.writeInt(1);
8441 mProcessStateTimer[i].writeToParcel(out, elapsedRealtimeUs);
8442 } else {
8443 out.writeInt(0);
8444 }
8445 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008446 if (mVibratorOnTimer != null) {
8447 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008448 mVibratorOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008449 } else {
8450 out.writeInt(0);
8451 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008452 if (mUserActivityCounters != null) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07008453 out.writeInt(1);
8454 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
8455 mUserActivityCounters[i].writeToParcel(out);
8456 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008457 } else {
8458 out.writeInt(0);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008459 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008460 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008461 out.writeInt(1);
8462 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008463 mNetworkByteActivityCounters[i].writeToParcel(out);
8464 mNetworkPacketActivityCounters[i].writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008465 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08008466 mMobileRadioActiveTime.writeToParcel(out);
8467 mMobileRadioActiveCount.writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008468 } else {
8469 out.writeInt(0);
8470 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008471
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008472 if (mWifiControllerActivity != null) {
8473 out.writeInt(1);
8474 mWifiControllerActivity.writeToParcel(out, 0);
8475 } else {
8476 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07008477 }
8478
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008479 if (mBluetoothControllerActivity != null) {
8480 out.writeInt(1);
8481 mBluetoothControllerActivity.writeToParcel(out, 0);
8482 } else {
8483 out.writeInt(0);
8484 }
8485
8486 if (mModemControllerActivity != null) {
8487 out.writeInt(1);
8488 mModemControllerActivity.writeToParcel(out, 0);
8489 } else {
8490 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07008491 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008492
8493 mUserCpuTime.writeToParcel(out);
8494 mSystemCpuTime.writeToParcel(out);
8495
Sudheer Shankaaf857412017-07-21 00:14:24 -07008496 if (mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008497 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -07008498 out.writeInt(mCpuClusterSpeedTimesUs.length);
8499 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008500 if (cpuSpeeds != null) {
8501 out.writeInt(1);
8502 out.writeInt(cpuSpeeds.length);
8503 for (LongSamplingCounter c : cpuSpeeds) {
8504 if (c != null) {
8505 out.writeInt(1);
8506 c.writeToParcel(out);
8507 } else {
8508 out.writeInt(0);
8509 }
8510 }
8511 } else {
8512 out.writeInt(0);
8513 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008514 }
Adam Lesinski6832f392015-09-05 18:05:40 -07008515 } else {
8516 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008517 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008518
Sudheer Shanka59f5c002017-05-15 10:57:15 -07008519 LongSamplingCounterArray.writeToParcel(out, mCpuFreqTimeMs);
8520 LongSamplingCounterArray.writeToParcel(out, mScreenOffCpuFreqTimeMs);
Mike Ma3d422c32017-10-25 11:08:57 -07008521
8522 mCpuActiveTimeMs.writeToParcel(out);
8523 mCpuClusterTimesMs.writeToParcel(out);
8524
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008525 if (mProcStateTimeMs != null) {
8526 out.writeInt(mProcStateTimeMs.length);
8527 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8528 LongSamplingCounterArray.writeToParcel(out, counters);
8529 }
8530 } else {
8531 out.writeInt(0);
8532 }
8533 if (mProcStateScreenOffTimeMs != null) {
8534 out.writeInt(mProcStateScreenOffTimeMs.length);
8535 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8536 LongSamplingCounterArray.writeToParcel(out, counters);
8537 }
8538 } else {
8539 out.writeInt(0);
8540 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008541
Adam Lesinski5f056f62016-07-14 16:56:08 -07008542 if (mMobileRadioApWakeupCount != null) {
8543 out.writeInt(1);
8544 mMobileRadioApWakeupCount.writeToParcel(out);
8545 } else {
8546 out.writeInt(0);
8547 }
8548
8549 if (mWifiRadioApWakeupCount != null) {
8550 out.writeInt(1);
8551 mWifiRadioApWakeupCount.writeToParcel(out);
8552 } else {
8553 out.writeInt(0);
8554 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008555 }
8556
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008557 void readJobCompletionsFromParcelLocked(Parcel in) {
8558 int numJobCompletions = in.readInt();
8559 mJobCompletions.clear();
8560 for (int j = 0; j < numJobCompletions; j++) {
8561 String jobName = in.readString();
8562 int numTypes = in.readInt();
8563 if (numTypes > 0) {
8564 SparseIntArray types = new SparseIntArray();
8565 for (int k = 0; k < numTypes; k++) {
8566 int type = in.readInt();
8567 int count = in.readInt();
8568 types.put(type, count);
8569 }
8570 mJobCompletions.put(jobName, types);
8571 }
8572 }
8573 }
8574
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008575 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase, Parcel in) {
Bookatz867c0d72017-03-07 18:23:42 -08008576 mOnBatteryBackgroundTimeBase.readFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -07008577 mOnBatteryScreenOffBackgroundTimeBase.readFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -08008578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008579 int numWakelocks = in.readInt();
8580 mWakelockStats.clear();
8581 for (int j = 0; j < numWakelocks; j++) {
8582 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008583 Uid.Wakelock wakelock = new Wakelock(mBsi, this);
Bookatz5b5ec322017-05-26 09:40:38 -07008584 wakelock.readFromParcelLocked(
8585 timeBase, screenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase, in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07008586 mWakelockStats.add(wakelockName, wakelock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008587 }
8588
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008589 int numSyncs = in.readInt();
8590 mSyncStats.clear();
8591 for (int j = 0; j < numSyncs; j++) {
8592 String syncName = in.readString();
8593 if (in.readInt() != 0) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008594 mSyncStats.add(syncName, new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
8595 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008596 }
8597 }
8598
8599 int numJobs = in.readInt();
8600 mJobStats.clear();
8601 for (int j = 0; j < numJobs; j++) {
8602 String jobName = in.readString();
8603 if (in.readInt() != 0) {
Bookatzaa4594a2017-03-24 12:39:56 -07008604 mJobStats.add(jobName, new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
8605 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008606 }
8607 }
8608
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008609 readJobCompletionsFromParcelLocked(in);
8610
Amith Yamasani977e11f2018-02-16 11:29:54 -08008611 mJobsDeferredEventCount = new Counter(mBsi.mOnBatteryTimeBase, in);
8612 mJobsDeferredCount = new Counter(mBsi.mOnBatteryTimeBase, in);
8613 mJobsFreshnessTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8614 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
8615 mJobsFreshnessBuckets[i] = Counter.readCounterFromParcel(mBsi.mOnBatteryTimeBase,
8616 in);
8617 }
8618
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008619 int numSensors = in.readInt();
8620 mSensorStats.clear();
8621 for (int k = 0; k < numSensors; k++) {
8622 int sensorNumber = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008623 Uid.Sensor sensor = new Sensor(mBsi, this, sensorNumber);
Bookatz867c0d72017-03-07 18:23:42 -08008624 sensor.readFromParcelLocked(mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
8625 in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008626 mSensorStats.put(sensorNumber, sensor);
8627 }
8628
8629 int numProcs = in.readInt();
8630 mProcessStats.clear();
8631 for (int k = 0; k < numProcs; k++) {
8632 String processName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008633 Uid.Proc proc = new Proc(mBsi, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008634 proc.readFromParcelLocked(in);
8635 mProcessStats.put(processName, proc);
8636 }
8637
8638 int numPkgs = in.readInt();
8639 mPackageStats.clear();
8640 for (int l = 0; l < numPkgs; l++) {
8641 String packageName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008642 Uid.Pkg pkg = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008643 pkg.readFromParcelLocked(in);
8644 mPackageStats.put(packageName, pkg);
8645 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008646
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008647 mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008648 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008649 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
8650 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008651 } else {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008652 mWifiRunningTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008653 }
8654 mFullWifiLockOut = false;
8655 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008656 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
8657 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008658 } else {
8659 mFullWifiLockTimer = null;
8660 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008661 mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008662 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08008663 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
8664 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
8665 in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008666 } else {
Nick Pelly6ccaa542012-06-15 15:22:47 -07008667 mWifiScanTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008668 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008669 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
8670 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8671 if (in.readInt() != 0) {
8672 makeWifiBatchedScanBin(i, in);
8673 } else {
8674 mWifiBatchedScanTimer[i] = null;
8675 }
8676 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008677 mWifiMulticastEnabled = false;
8678 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008679 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_MULTICAST_ENABLED,
8680 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008681 } else {
8682 mWifiMulticastTimer = null;
8683 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008684 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008685 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
8686 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008687 } else {
8688 mAudioTurnedOnTimer = null;
8689 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008690 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008691 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
8692 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008693 } else {
8694 mVideoTurnedOnTimer = null;
8695 }
8696 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008697 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8698 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008699 } else {
8700 mFlashlightTurnedOnTimer = null;
8701 }
8702 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008703 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
8704 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008705 } else {
8706 mCameraTurnedOnTimer = null;
8707 }
8708 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008709 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8710 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008711 } else {
8712 mForegroundActivityTimer = null;
8713 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008714 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008715 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8716 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase, in);
8717 } else {
8718 mForegroundServiceTimer = null;
8719 }
8720 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -07008721 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
8722 AGGREGATED_WAKE_TYPE_PARTIAL, null,
8723 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase,
8724 in);
8725 } else {
8726 mAggregatedPartialWakelockTimer = null;
8727 }
8728 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08008729 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
8730 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
8731 mOnBatteryBackgroundTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008732 } else {
8733 mBluetoothScanTimer = null;
8734 }
Bookatz956f36bf2017-04-28 09:48:17 -07008735 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -07008736 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
8737 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
8738 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in);
8739 } else {
8740 mBluetoothUnoptimizedScanTimer = null;
8741 }
8742 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -07008743 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase, in);
8744 } else {
8745 mBluetoothScanResultCounter = null;
8746 }
Bookatzb1f04f32017-05-19 13:57:32 -07008747 if (in.readInt() != 0) {
8748 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase, in);
8749 } else {
8750 mBluetoothScanResultBgCounter = null;
8751 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08008752 mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07008753 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8754 if (in.readInt() != 0) {
8755 makeProcessState(i, in);
8756 } else {
8757 mProcessStateTimer[i] = null;
8758 }
8759 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008760 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008761 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
8762 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008763 } else {
8764 mVibratorOnTimer = null;
8765 }
8766 if (in.readInt() != 0) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07008767 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
8768 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08008769 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008770 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008771 } else {
8772 mUserActivityCounters = null;
Dianne Hackborn617f8772009-03-31 15:04:46 -07008773 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008774 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008775 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
8776 mNetworkPacketActivityCounters
8777 = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008778 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008779 mNetworkByteActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08008780 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008781 mNetworkPacketActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08008782 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008783 }
Joe Onoratoabded112016-02-08 16:49:39 -08008784 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8785 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008786 } else {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008787 mNetworkByteActivityCounters = null;
8788 mNetworkPacketActivityCounters = null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008789 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008790
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008791 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008792 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008793 NUM_WIFI_TX_LEVELS, in);
8794 } else {
8795 mWifiControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07008796 }
8797
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008798 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008799 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008800 NUM_BT_TX_LEVELS, in);
8801 } else {
8802 mBluetoothControllerActivity = null;
8803 }
8804
8805 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008806 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008807 ModemActivityInfo.TX_POWER_LEVELS, in);
8808 } else {
8809 mModemControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07008810 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008811
Joe Onoratoabded112016-02-08 16:49:39 -08008812 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8813 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008814
Adam Lesinski6832f392015-09-05 18:05:40 -07008815 if (in.readInt() != 0) {
8816 int numCpuClusters = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008817 if (mBsi.mPowerProfile != null && mBsi.mPowerProfile.getNumCpuClusters() != numCpuClusters) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008818 throw new ParcelFormatException("Incompatible number of cpu clusters");
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008819 }
Adam Lesinski6832f392015-09-05 18:05:40 -07008820
Sudheer Shankaaf857412017-07-21 00:14:24 -07008821 mCpuClusterSpeedTimesUs = new LongSamplingCounter[numCpuClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -07008822 for (int cluster = 0; cluster < numCpuClusters; cluster++) {
8823 if (in.readInt() != 0) {
8824 int numSpeeds = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008825 if (mBsi.mPowerProfile != null &&
8826 mBsi.mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != numSpeeds) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008827 throw new ParcelFormatException("Incompatible number of cpu speeds");
8828 }
8829
8830 final LongSamplingCounter[] cpuSpeeds = new LongSamplingCounter[numSpeeds];
Sudheer Shankaaf857412017-07-21 00:14:24 -07008831 mCpuClusterSpeedTimesUs[cluster] = cpuSpeeds;
Adam Lesinski6832f392015-09-05 18:05:40 -07008832 for (int speed = 0; speed < numSpeeds; speed++) {
8833 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008834 cpuSpeeds[speed] = new LongSamplingCounter(
8835 mBsi.mOnBatteryTimeBase, in);
Adam Lesinski6832f392015-09-05 18:05:40 -07008836 }
8837 }
Adam Lesinskia57a5402015-09-28 10:21:33 -07008838 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008839 mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -07008840 }
8841 }
8842 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008843 mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008844 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008845
Sudheer Shanka59f5c002017-05-15 10:57:15 -07008846 mCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(in, mBsi.mOnBatteryTimeBase);
8847 mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(
8848 in, mBsi.mOnBatteryScreenOffTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008849
Mike Ma3d422c32017-10-25 11:08:57 -07008850 mCpuActiveTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8851 mCpuClusterTimesMs = new LongSamplingCounterArray(mBsi.mOnBatteryTimeBase, in);
8852
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008853 int length = in.readInt();
8854 if (length == NUM_PROCESS_STATE) {
8855 mProcStateTimeMs = new LongSamplingCounterArray[length];
8856 for (int procState = 0; procState < length; ++procState) {
8857 mProcStateTimeMs[procState] = LongSamplingCounterArray.readFromParcel(
8858 in, mBsi.mOnBatteryTimeBase);
8859 }
8860 } else {
8861 mProcStateTimeMs = null;
8862 }
8863 length = in.readInt();
8864 if (length == NUM_PROCESS_STATE) {
8865 mProcStateScreenOffTimeMs = new LongSamplingCounterArray[length];
8866 for (int procState = 0; procState < length; ++procState) {
8867 mProcStateScreenOffTimeMs[procState] = LongSamplingCounterArray.readFromParcel(
8868 in, mBsi.mOnBatteryScreenOffTimeBase);
8869 }
8870 } else {
8871 mProcStateScreenOffTimeMs = null;
8872 }
8873
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008874 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07008875 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8876 } else {
8877 mMobileRadioApWakeupCount = null;
8878 }
8879
8880 if (in.readInt() != 0) {
8881 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8882 } else {
8883 mWifiRadioApWakeupCount = null;
8884 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008885 }
8886
Amith Yamasani977e11f2018-02-16 11:29:54 -08008887 public void noteJobsDeferredLocked(int numDeferred, long sinceLast) {
8888 mJobsDeferredEventCount.addAtomic(1);
8889 mJobsDeferredCount.addAtomic(numDeferred);
8890 if (sinceLast != 0) {
8891 // Add the total time, which can be divided by the event count to get an average
8892 mJobsFreshnessTimeMs.addCountLocked(sinceLast);
8893 // Also keep track of how many times there were in these different buckets.
8894 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
8895 if (sinceLast < JOB_FRESHNESS_BUCKETS[i]) {
8896 if (mJobsFreshnessBuckets[i] == null) {
8897 mJobsFreshnessBuckets[i] = new Counter(
8898 mBsi.mOnBatteryTimeBase);
8899 }
8900 mJobsFreshnessBuckets[i].addAtomic(1);
8901 break;
8902 }
8903 }
8904 }
8905 }
8906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008907 /**
8908 * The statistics associated with a particular wake lock.
8909 */
Joe Onoratoabded112016-02-08 16:49:39 -08008910 public static class Wakelock extends BatteryStats.Uid.Wakelock {
8911 /**
8912 * BatteryStatsImpl that we are associated with.
8913 */
8914 protected BatteryStatsImpl mBsi;
8915
8916 /**
8917 * BatteryStatsImpl that we are associated with.
8918 */
8919 protected Uid mUid;
8920
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008921 /**
8922 * How long (in ms) this uid has been keeping the device partially awake.
Bookatz5b5ec322017-05-26 09:40:38 -07008923 * 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 -08008924 */
Bookatz5b5ec322017-05-26 09:40:38 -07008925 DualTimer mTimerPartial;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008926
8927 /**
8928 * How long (in ms) this uid has been keeping the device fully awake.
8929 */
Evan Millarc64edde2009-04-18 12:26:32 -07008930 StopwatchTimer mTimerFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008931
8932 /**
8933 * How long (in ms) this uid has had a window keeping the device awake.
8934 */
Evan Millarc64edde2009-04-18 12:26:32 -07008935 StopwatchTimer mTimerWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008936
8937 /**
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008938 * How long (in ms) this uid has had a draw wake lock.
Adam Lesinski9425fe22015-06-19 12:02:13 -07008939 */
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008940 StopwatchTimer mTimerDraw;
Adam Lesinski9425fe22015-06-19 12:02:13 -07008941
Joe Onoratoabded112016-02-08 16:49:39 -08008942 public Wakelock(BatteryStatsImpl bsi, Uid uid) {
8943 mBsi = bsi;
8944 mUid = uid;
8945 }
8946
Adam Lesinski9425fe22015-06-19 12:02:13 -07008947 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008948 * Reads a possibly null Timer from a Parcel. The timer is associated with the
8949 * proper timer pool from the given BatteryStatsImpl object.
8950 *
8951 * @param in the Parcel to be read from.
8952 * return a new Timer, or null.
8953 */
Joe Onorato92fd23f2016-07-25 11:18:42 -07008954 private StopwatchTimer readStopwatchTimerFromParcel(int type,
8955 ArrayList<StopwatchTimer> pool, TimeBase timeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008956 if (in.readInt() == 0) {
8957 return null;
8958 }
8959
Joe Onoratoabded112016-02-08 16:49:39 -08008960 return new StopwatchTimer(mBsi.mClocks, mUid, type, pool, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008961 }
8962
Joe Onorato92fd23f2016-07-25 11:18:42 -07008963 /**
8964 * Reads a possibly null Timer from a Parcel. The timer is associated with the
8965 * proper timer pool from the given BatteryStatsImpl object.
8966 *
8967 * @param in the Parcel to be read from.
8968 * return a new Timer, or null.
8969 */
Bookatz5b5ec322017-05-26 09:40:38 -07008970 private DualTimer readDualTimerFromParcel(int type, ArrayList<StopwatchTimer> pool,
8971 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07008972 if (in.readInt() == 0) {
8973 return null;
8974 }
8975
Bookatz5b5ec322017-05-26 09:40:38 -07008976 return new DualTimer(mBsi.mClocks, mUid, type, pool, timeBase, bgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07008977 }
8978
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008979 boolean reset() {
8980 boolean wlactive = false;
8981 if (mTimerFull != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008982 wlactive |= !mTimerFull.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008983 }
8984 if (mTimerPartial != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008985 wlactive |= !mTimerPartial.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008986 }
8987 if (mTimerWindow != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008988 wlactive |= !mTimerWindow.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008989 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008990 if (mTimerDraw != null) {
8991 wlactive |= !mTimerDraw.reset(false);
Adam Lesinski9425fe22015-06-19 12:02:13 -07008992 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008993 if (!wlactive) {
8994 if (mTimerFull != null) {
8995 mTimerFull.detach();
8996 mTimerFull = null;
8997 }
8998 if (mTimerPartial != null) {
8999 mTimerPartial.detach();
9000 mTimerPartial = null;
9001 }
9002 if (mTimerWindow != null) {
9003 mTimerWindow.detach();
9004 mTimerWindow = null;
9005 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07009006 if (mTimerDraw != null) {
9007 mTimerDraw.detach();
9008 mTimerDraw = null;
Adam Lesinski9425fe22015-06-19 12:02:13 -07009009 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009010 }
9011 return !wlactive;
9012 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009013
Bookatz5b5ec322017-05-26 09:40:38 -07009014 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase,
9015 TimeBase screenOffBgTimeBase, Parcel in) {
9016 mTimerPartial = readDualTimerFromParcel(WAKE_TYPE_PARTIAL,
9017 mBsi.mPartialTimers, screenOffTimeBase, screenOffBgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07009018 mTimerFull = readStopwatchTimerFromParcel(WAKE_TYPE_FULL,
9019 mBsi.mFullTimers, timeBase, in);
9020 mTimerWindow = readStopwatchTimerFromParcel(WAKE_TYPE_WINDOW,
9021 mBsi.mWindowTimers, timeBase, in);
9022 mTimerDraw = readStopwatchTimerFromParcel(WAKE_TYPE_DRAW,
9023 mBsi.mDrawTimers, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009024 }
9025
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009026 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
9027 Timer.writeTimerToParcel(out, mTimerPartial, elapsedRealtimeUs);
9028 Timer.writeTimerToParcel(out, mTimerFull, elapsedRealtimeUs);
9029 Timer.writeTimerToParcel(out, mTimerWindow, elapsedRealtimeUs);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07009030 Timer.writeTimerToParcel(out, mTimerDraw, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009031 }
9032
9033 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01009034 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009035 public Timer getWakeTime(int type) {
9036 switch (type) {
9037 case WAKE_TYPE_FULL: return mTimerFull;
9038 case WAKE_TYPE_PARTIAL: return mTimerPartial;
9039 case WAKE_TYPE_WINDOW: return mTimerWindow;
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07009040 case WAKE_TYPE_DRAW: return mTimerDraw;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009041 default: throw new IllegalArgumentException("type = " + type);
9042 }
9043 }
9044 }
9045
Joe Onoratoabded112016-02-08 16:49:39 -08009046 public static class Sensor extends BatteryStats.Uid.Sensor {
9047 /**
9048 * BatteryStatsImpl that we are associated with.
9049 */
9050 protected BatteryStatsImpl mBsi;
9051
9052 /**
Bookatz867c0d72017-03-07 18:23:42 -08009053 * Uid that we are associated with.
Joe Onoratoabded112016-02-08 16:49:39 -08009054 */
9055 protected Uid mUid;
9056
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009057 final int mHandle;
Bookatz867c0d72017-03-07 18:23:42 -08009058 DualTimer mTimer;
Amith Yamasaniab9ad192016-12-06 12:46:59 -08009059
Joe Onoratoabded112016-02-08 16:49:39 -08009060 public Sensor(BatteryStatsImpl bsi, Uid uid, int handle) {
9061 mBsi = bsi;
9062 mUid = uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009063 mHandle = handle;
9064 }
9065
Bookatz867c0d72017-03-07 18:23:42 -08009066 private DualTimer readTimersFromParcel(
9067 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009068 if (in.readInt() == 0) {
9069 return null;
9070 }
9071
Joe Onoratoabded112016-02-08 16:49:39 -08009072 ArrayList<StopwatchTimer> pool = mBsi.mSensorTimers.get(mHandle);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009073 if (pool == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07009074 pool = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08009075 mBsi.mSensorTimers.put(mHandle, pool);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009076 }
Bookatz867c0d72017-03-07 18:23:42 -08009077 return new DualTimer(mBsi.mClocks, mUid, 0, pool, timeBase, bgTimeBase, in);
Amith Yamasaniab9ad192016-12-06 12:46:59 -08009078 }
9079
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009080 boolean reset() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009081 if (mTimer.reset(true)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009082 mTimer = null;
9083 return true;
9084 }
9085 return false;
9086 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009087
Bookatz867c0d72017-03-07 18:23:42 -08009088 void readFromParcelLocked(TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
9089 mTimer = readTimersFromParcel(timeBase, bgTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009090 }
9091
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009092 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07009093 Timer.writeTimerToParcel(out, mTimer, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009094 }
9095
9096 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01009097 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009098 public Timer getSensorTime() {
Bookatzaa4594a2017-03-24 12:39:56 -07009099 return mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009100 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009101
9102 @Override
Bookatz867c0d72017-03-07 18:23:42 -08009103 public Timer getSensorBackgroundTime() {
9104 if (mTimer == null) {
9105 return null;
9106 }
9107 return mTimer.getSubTimer();
Amith Yamasaniab9ad192016-12-06 12:46:59 -08009108 }
9109
9110 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01009111 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009112 public int getHandle() {
9113 return mHandle;
9114 }
9115 }
9116
9117 /**
9118 * The statistics associated with a particular process.
9119 */
Joe Onoratoabded112016-02-08 16:49:39 -08009120 public static class Proc extends BatteryStats.Uid.Proc implements TimeBaseObs {
9121 /**
9122 * BatteryStatsImpl that we are associated with.
9123 */
9124 protected BatteryStatsImpl mBsi;
9125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009126 /**
Dianne Hackborncd0e3352014-08-07 17:08:09 -07009127 * The name of this process.
9128 */
9129 final String mName;
9130
9131 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -08009132 * Remains true until removed from the stats.
9133 */
9134 boolean mActive = true;
9135
9136 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07009137 * Total time (in ms) spent executing in user code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009138 */
9139 long mUserTime;
9140
9141 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07009142 * Total time (in ms) spent executing in kernel code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009143 */
9144 long mSystemTime;
9145
9146 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07009147 * Amount of time (in ms) the process was running in the foreground.
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009148 */
9149 long mForegroundTime;
9150
9151 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009152 * Number of times the process has been started.
9153 */
9154 int mStarts;
9155
9156 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009157 * Number of times the process has crashed.
9158 */
9159 int mNumCrashes;
9160
9161 /**
9162 * Number of times the process has had an ANR.
9163 */
9164 int mNumAnrs;
9165
9166 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009167 * The amount of user time loaded from a previous save.
9168 */
9169 long mLoadedUserTime;
9170
9171 /**
9172 * The amount of system time loaded from a previous save.
9173 */
9174 long mLoadedSystemTime;
9175
9176 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009177 * The amount of foreground time loaded from a previous save.
9178 */
9179 long mLoadedForegroundTime;
9180
9181 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009182 * The number of times the process has started from a previous save.
9183 */
9184 int mLoadedStarts;
9185
9186 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009187 * Number of times the process has crashed from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009188 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009189 int mLoadedNumCrashes;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009190
9191 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009192 * Number of times the process has had an ANR from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009193 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009194 int mLoadedNumAnrs;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009195
9196 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009197 * The amount of user time when last unplugged.
9198 */
9199 long mUnpluggedUserTime;
9200
9201 /**
9202 * The amount of system time when last unplugged.
9203 */
9204 long mUnpluggedSystemTime;
9205
9206 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009207 * The amount of foreground time since unplugged.
9208 */
9209 long mUnpluggedForegroundTime;
9210
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009211 /**
9212 * The number of times the process has started before unplugged.
9213 */
9214 int mUnpluggedStarts;
9215
Dianne Hackborn61659e52014-07-09 16:13:01 -07009216 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009217 * Number of times the process has crashed before unplugged.
9218 */
9219 int mUnpluggedNumCrashes;
9220
9221 /**
9222 * Number of times the process has had an ANR before unplugged.
9223 */
9224 int mUnpluggedNumAnrs;
9225
Dianne Hackborn287952c2010-09-22 22:34:31 -07009226 ArrayList<ExcessivePower> mExcessivePower;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009227
Joe Onoratoabded112016-02-08 16:49:39 -08009228 public Proc(BatteryStatsImpl bsi, String name) {
9229 mBsi = bsi;
Dianne Hackborncd0e3352014-08-07 17:08:09 -07009230 mName = name;
Joe Onoratoabded112016-02-08 16:49:39 -08009231 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009232 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07009233
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009234 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009235 mUnpluggedUserTime = mUserTime;
9236 mUnpluggedSystemTime = mSystemTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009237 mUnpluggedForegroundTime = mForegroundTime;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009238 mUnpluggedStarts = mStarts;
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009239 mUnpluggedNumCrashes = mNumCrashes;
9240 mUnpluggedNumAnrs = mNumAnrs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009241 }
9242
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009243 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009244 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009245
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009246 void detach() {
Dianne Hackborn099bc622014-01-22 13:39:16 -08009247 mActive = false;
Joe Onoratoabded112016-02-08 16:49:39 -08009248 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009249 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009250
Dianne Hackborn287952c2010-09-22 22:34:31 -07009251 public int countExcessivePowers() {
9252 return mExcessivePower != null ? mExcessivePower.size() : 0;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009253 }
9254
Dianne Hackborn287952c2010-09-22 22:34:31 -07009255 public ExcessivePower getExcessivePower(int i) {
9256 if (mExcessivePower != null) {
9257 return mExcessivePower.get(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009258 }
9259 return null;
9260 }
9261
Dianne Hackborn287952c2010-09-22 22:34:31 -07009262 public void addExcessiveCpu(long overTime, long usedTime) {
9263 if (mExcessivePower == null) {
9264 mExcessivePower = new ArrayList<ExcessivePower>();
9265 }
9266 ExcessivePower ew = new ExcessivePower();
9267 ew.type = ExcessivePower.TYPE_CPU;
9268 ew.overTime = overTime;
9269 ew.usedTime = usedTime;
9270 mExcessivePower.add(ew);
9271 }
9272
9273 void writeExcessivePowerToParcelLocked(Parcel out) {
9274 if (mExcessivePower == null) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009275 out.writeInt(0);
9276 return;
9277 }
9278
Dianne Hackborn287952c2010-09-22 22:34:31 -07009279 final int N = mExcessivePower.size();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009280 out.writeInt(N);
9281 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009282 ExcessivePower ew = mExcessivePower.get(i);
9283 out.writeInt(ew.type);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009284 out.writeLong(ew.overTime);
9285 out.writeLong(ew.usedTime);
9286 }
9287 }
9288
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009289 void readExcessivePowerFromParcelLocked(Parcel in) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009290 final int N = in.readInt();
9291 if (N == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009292 mExcessivePower = null;
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009293 return;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009294 }
9295
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08009296 if (N > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009297 throw new ParcelFormatException(
9298 "File corrupt: too many excessive power entries " + N);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08009299 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009300
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009301 mExcessivePower = new ArrayList<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009302 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009303 ExcessivePower ew = new ExcessivePower();
9304 ew.type = in.readInt();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009305 ew.overTime = in.readLong();
9306 ew.usedTime = in.readLong();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009307 mExcessivePower.add(ew);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009308 }
9309 }
9310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009311 void writeToParcelLocked(Parcel out) {
9312 out.writeLong(mUserTime);
9313 out.writeLong(mSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009314 out.writeLong(mForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009315 out.writeInt(mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009316 out.writeInt(mNumCrashes);
9317 out.writeInt(mNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009318 out.writeLong(mLoadedUserTime);
9319 out.writeLong(mLoadedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009320 out.writeLong(mLoadedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009321 out.writeInt(mLoadedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009322 out.writeInt(mLoadedNumCrashes);
9323 out.writeInt(mLoadedNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009324 out.writeLong(mUnpluggedUserTime);
9325 out.writeLong(mUnpluggedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009326 out.writeLong(mUnpluggedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009327 out.writeInt(mUnpluggedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009328 out.writeInt(mUnpluggedNumCrashes);
9329 out.writeInt(mUnpluggedNumAnrs);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009330 writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009331 }
9332
9333 void readFromParcelLocked(Parcel in) {
9334 mUserTime = in.readLong();
9335 mSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009336 mForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009337 mStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009338 mNumCrashes = in.readInt();
9339 mNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009340 mLoadedUserTime = in.readLong();
9341 mLoadedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009342 mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009343 mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009344 mLoadedNumCrashes = in.readInt();
9345 mLoadedNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009346 mUnpluggedUserTime = in.readLong();
9347 mUnpluggedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009348 mUnpluggedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009349 mUnpluggedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009350 mUnpluggedNumCrashes = in.readInt();
9351 mUnpluggedNumAnrs = in.readInt();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009352 readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009353 }
9354
Mathew Inwoodc185f082018-08-20 14:28:54 +01009355 @UnsupportedAppUsage
Adam Lesinski06af1fa2015-05-05 17:35:35 -07009356 public void addCpuTimeLocked(int utime, int stime) {
Sudheer Shankac57729a2018-02-09 15:44:42 -08009357 addCpuTimeLocked(utime, stime, mBsi.mOnBatteryTimeBase.isRunning());
9358 }
9359
9360 public void addCpuTimeLocked(int utime, int stime, boolean isRunning) {
9361 if (isRunning) {
9362 mUserTime += utime;
9363 mSystemTime += stime;
9364 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009365 }
9366
Mathew Inwoodc185f082018-08-20 14:28:54 +01009367 @UnsupportedAppUsage
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009368 public void addForegroundTimeLocked(long ttime) {
9369 mForegroundTime += ttime;
9370 }
9371
Mathew Inwoodc185f082018-08-20 14:28:54 +01009372 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009373 public void incStartsLocked() {
9374 mStarts++;
9375 }
9376
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009377 public void incNumCrashesLocked() {
9378 mNumCrashes++;
9379 }
9380
9381 public void incNumAnrsLocked() {
9382 mNumAnrs++;
9383 }
9384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009385 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -08009386 public boolean isActive() {
9387 return mActive;
9388 }
9389
9390 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01009391 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009392 public long getUserTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009393 long val = mUserTime;
9394 if (which == STATS_CURRENT) {
9395 val -= mLoadedUserTime;
9396 } else if (which == STATS_SINCE_UNPLUGGED) {
9397 val -= mUnpluggedUserTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009398 }
9399 return val;
9400 }
9401
9402 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01009403 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009404 public long getSystemTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009405 long val = mSystemTime;
9406 if (which == STATS_CURRENT) {
9407 val -= mLoadedSystemTime;
9408 } else if (which == STATS_SINCE_UNPLUGGED) {
9409 val -= mUnpluggedSystemTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009410 }
9411 return val;
9412 }
9413
9414 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01009415 @UnsupportedAppUsage
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009416 public long getForegroundTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009417 long val = mForegroundTime;
9418 if (which == STATS_CURRENT) {
9419 val -= mLoadedForegroundTime;
9420 } else if (which == STATS_SINCE_UNPLUGGED) {
9421 val -= mUnpluggedForegroundTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009422 }
9423 return val;
9424 }
9425
9426 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01009427 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009428 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009429 int val = mStarts;
9430 if (which == STATS_CURRENT) {
9431 val -= mLoadedStarts;
9432 } else if (which == STATS_SINCE_UNPLUGGED) {
9433 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009434 }
9435 return val;
9436 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07009437
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009438 @Override
9439 public int getNumCrashes(int which) {
9440 int val = mNumCrashes;
9441 if (which == STATS_CURRENT) {
9442 val -= mLoadedNumCrashes;
9443 } else if (which == STATS_SINCE_UNPLUGGED) {
9444 val -= mUnpluggedNumCrashes;
9445 }
9446 return val;
9447 }
9448
9449 @Override
9450 public int getNumAnrs(int which) {
9451 int val = mNumAnrs;
9452 if (which == STATS_CURRENT) {
9453 val -= mLoadedNumAnrs;
9454 } else if (which == STATS_SINCE_UNPLUGGED) {
9455 val -= mUnpluggedNumAnrs;
9456 }
9457 return val;
9458 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009459 }
9460
9461 /**
9462 * The statistics associated with a particular package.
9463 */
Joe Onoratoabded112016-02-08 16:49:39 -08009464 public static class Pkg extends BatteryStats.Uid.Pkg implements TimeBaseObs {
9465 /**
9466 * BatteryStatsImpl that we are associated with.
9467 */
9468 protected BatteryStatsImpl mBsi;
9469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009470 /**
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009471 * Number of times wakeup alarms have occurred for this app.
Bookatz98d4d5c2017-08-01 19:07:54 -07009472 * On screen-off timebase starting in report v25.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009473 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009474 ArrayMap<String, Counter> mWakeupAlarms = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009475
9476 /**
9477 * The statics we have collected for this package's services.
9478 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009479 final ArrayMap<String, Serv> mServiceStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009480
Joe Onoratoabded112016-02-08 16:49:39 -08009481 public Pkg(BatteryStatsImpl bsi) {
9482 mBsi = bsi;
9483 mBsi.mOnBatteryScreenOffTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009484 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009485
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009486 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009487 }
9488
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009489 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009490 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009491
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009492 void detach() {
Joe Onoratoabded112016-02-08 16:49:39 -08009493 mBsi.mOnBatteryScreenOffTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009494 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009496 void readFromParcelLocked(Parcel in) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009497 int numWA = in.readInt();
9498 mWakeupAlarms.clear();
9499 for (int i=0; i<numWA; i++) {
9500 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -07009501 mWakeupAlarms.put(tag, new Counter(mBsi.mOnBatteryScreenOffTimeBase, in));
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009502 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009503
9504 int numServs = in.readInt();
9505 mServiceStats.clear();
9506 for (int m = 0; m < numServs; m++) {
9507 String serviceName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08009508 Uid.Pkg.Serv serv = new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009509 mServiceStats.put(serviceName, serv);
9510
9511 serv.readFromParcelLocked(in);
9512 }
9513 }
9514
9515 void writeToParcelLocked(Parcel out) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009516 int numWA = mWakeupAlarms.size();
9517 out.writeInt(numWA);
9518 for (int i=0; i<numWA; i++) {
9519 out.writeString(mWakeupAlarms.keyAt(i));
9520 mWakeupAlarms.valueAt(i).writeToParcel(out);
9521 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009522
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009523 final int NS = mServiceStats.size();
9524 out.writeInt(NS);
9525 for (int i=0; i<NS; i++) {
9526 out.writeString(mServiceStats.keyAt(i));
9527 Uid.Pkg.Serv serv = mServiceStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009528 serv.writeToParcelLocked(out);
9529 }
9530 }
9531
9532 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009533 public ArrayMap<String, ? extends BatteryStats.Counter> getWakeupAlarmStats() {
9534 return mWakeupAlarms;
9535 }
9536
9537 public void noteWakeupAlarmLocked(String tag) {
9538 Counter c = mWakeupAlarms.get(tag);
9539 if (c == null) {
Bookatz98d4d5c2017-08-01 19:07:54 -07009540 c = new Counter(mBsi.mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009541 mWakeupAlarms.put(tag, c);
9542 }
9543 c.stepAtomic();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009544 }
9545
9546 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009547 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg.Serv> getServiceStats() {
9548 return mServiceStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009549 }
9550
9551 /**
9552 * The statistics associated with a particular service.
9553 */
Joe Onoratoabded112016-02-08 16:49:39 -08009554 public static class Serv extends BatteryStats.Uid.Pkg.Serv implements TimeBaseObs {
9555 /**
9556 * BatteryStatsImpl that we are associated with.
9557 */
9558 protected BatteryStatsImpl mBsi;
9559
9560 /**
9561 * The android package in which this service resides.
9562 */
9563 protected Pkg mPkg;
9564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009565 /**
9566 * Total time (ms in battery uptime) the service has been left started.
9567 */
Joe Onoratoabded112016-02-08 16:49:39 -08009568 protected long mStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009569
9570 /**
9571 * If service has been started and not yet stopped, this is
9572 * when it was started.
9573 */
Joe Onoratoabded112016-02-08 16:49:39 -08009574 protected long mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009575
9576 /**
9577 * True if we are currently running.
9578 */
Joe Onoratoabded112016-02-08 16:49:39 -08009579 protected boolean mRunning;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009580
9581 /**
9582 * Total number of times startService() has been called.
9583 */
Joe Onoratoabded112016-02-08 16:49:39 -08009584 protected int mStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009585
9586 /**
9587 * Total time (ms in battery uptime) the service has been left launched.
9588 */
Joe Onoratoabded112016-02-08 16:49:39 -08009589 protected long mLaunchedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009590
9591 /**
9592 * If service has been launched and not yet exited, this is
9593 * when it was launched (ms in battery uptime).
9594 */
Joe Onoratoabded112016-02-08 16:49:39 -08009595 protected long mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009596
9597 /**
9598 * True if we are currently launched.
9599 */
Joe Onoratoabded112016-02-08 16:49:39 -08009600 protected boolean mLaunched;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009601
9602 /**
9603 * Total number times the service has been launched.
9604 */
Joe Onoratoabded112016-02-08 16:49:39 -08009605 protected int mLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009606
9607 /**
9608 * The amount of time spent started loaded from a previous save
9609 * (ms in battery uptime).
9610 */
Joe Onoratoabded112016-02-08 16:49:39 -08009611 protected long mLoadedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009612
9613 /**
9614 * The number of starts loaded from a previous save.
9615 */
Joe Onoratoabded112016-02-08 16:49:39 -08009616 protected int mLoadedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009617
9618 /**
9619 * The number of launches loaded from a previous save.
9620 */
Joe Onoratoabded112016-02-08 16:49:39 -08009621 protected int mLoadedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009622
9623 /**
9624 * The amount of time spent started as of the last run (ms
9625 * in battery uptime).
9626 */
Joe Onoratoabded112016-02-08 16:49:39 -08009627 protected long mLastStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009628
9629 /**
9630 * The number of starts as of the last run.
9631 */
Joe Onoratoabded112016-02-08 16:49:39 -08009632 protected int mLastStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009633
9634 /**
9635 * The number of launches as of the last run.
9636 */
Joe Onoratoabded112016-02-08 16:49:39 -08009637 protected int mLastLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009638
9639 /**
9640 * The amount of time spent started when last unplugged (ms
9641 * in battery uptime).
9642 */
Joe Onoratoabded112016-02-08 16:49:39 -08009643 protected long mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009644
9645 /**
9646 * The number of starts when last unplugged.
9647 */
Joe Onoratoabded112016-02-08 16:49:39 -08009648 protected int mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009649
9650 /**
9651 * The number of launches when last unplugged.
9652 */
Joe Onoratoabded112016-02-08 16:49:39 -08009653 protected int mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009654
Joe Onoratoabded112016-02-08 16:49:39 -08009655 /**
9656 * Construct a Serv. Also adds it to the on-battery time base as a listener.
9657 */
9658 public Serv(BatteryStatsImpl bsi) {
9659 mBsi = bsi;
9660 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009661 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009662
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009663 public void onTimeStarted(long elapsedRealtime, long baseUptime,
9664 long baseRealtime) {
9665 mUnpluggedStartTime = getStartTimeToNowLocked(baseUptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009666 mUnpluggedStarts = mStarts;
9667 mUnpluggedLaunches = mLaunches;
9668 }
9669
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009670 public void onTimeStopped(long elapsedRealtime, long baseUptime,
9671 long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009672 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009673
Joe Onoratoabded112016-02-08 16:49:39 -08009674 /**
9675 * Remove this Serv as a listener from the time base.
9676 */
9677 public void detach() {
9678 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009679 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009680
Joe Onoratoabded112016-02-08 16:49:39 -08009681 public void readFromParcelLocked(Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009682 mStartTime = in.readLong();
9683 mRunningSince = in.readLong();
9684 mRunning = in.readInt() != 0;
9685 mStarts = in.readInt();
9686 mLaunchedTime = in.readLong();
9687 mLaunchedSince = in.readLong();
9688 mLaunched = in.readInt() != 0;
9689 mLaunches = in.readInt();
9690 mLoadedStartTime = in.readLong();
9691 mLoadedStarts = in.readInt();
9692 mLoadedLaunches = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07009693 mLastStartTime = 0;
9694 mLastStarts = 0;
9695 mLastLaunches = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009696 mUnpluggedStartTime = in.readLong();
9697 mUnpluggedStarts = in.readInt();
9698 mUnpluggedLaunches = in.readInt();
9699 }
9700
Joe Onoratoabded112016-02-08 16:49:39 -08009701 public void writeToParcelLocked(Parcel out) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009702 out.writeLong(mStartTime);
9703 out.writeLong(mRunningSince);
9704 out.writeInt(mRunning ? 1 : 0);
9705 out.writeInt(mStarts);
9706 out.writeLong(mLaunchedTime);
9707 out.writeLong(mLaunchedSince);
9708 out.writeInt(mLaunched ? 1 : 0);
9709 out.writeInt(mLaunches);
9710 out.writeLong(mLoadedStartTime);
9711 out.writeInt(mLoadedStarts);
9712 out.writeInt(mLoadedLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009713 out.writeLong(mUnpluggedStartTime);
9714 out.writeInt(mUnpluggedStarts);
9715 out.writeInt(mUnpluggedLaunches);
9716 }
9717
Joe Onoratoabded112016-02-08 16:49:39 -08009718 public long getLaunchTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009719 if (!mLaunched) return mLaunchedTime;
9720 return mLaunchedTime + batteryUptime - mLaunchedSince;
9721 }
9722
Joe Onoratoabded112016-02-08 16:49:39 -08009723 public long getStartTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009724 if (!mRunning) return mStartTime;
9725 return mStartTime + batteryUptime - mRunningSince;
9726 }
9727
Mathew Inwoodc185f082018-08-20 14:28:54 +01009728 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009729 public void startLaunchedLocked() {
9730 if (!mLaunched) {
9731 mLaunches++;
Joe Onoratoabded112016-02-08 16:49:39 -08009732 mLaunchedSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009733 mLaunched = true;
9734 }
9735 }
9736
Mathew Inwoodc185f082018-08-20 14:28:54 +01009737 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009738 public void stopLaunchedLocked() {
9739 if (mLaunched) {
Joe Onoratoabded112016-02-08 16:49:39 -08009740 long time = mBsi.getBatteryUptimeLocked() - mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009741 if (time > 0) {
9742 mLaunchedTime += time;
9743 } else {
9744 mLaunches--;
9745 }
9746 mLaunched = false;
9747 }
9748 }
9749
Mathew Inwoodc185f082018-08-20 14:28:54 +01009750 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009751 public void startRunningLocked() {
9752 if (!mRunning) {
9753 mStarts++;
Joe Onoratoabded112016-02-08 16:49:39 -08009754 mRunningSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009755 mRunning = true;
9756 }
9757 }
9758
Mathew Inwoodc185f082018-08-20 14:28:54 +01009759 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009760 public void stopRunningLocked() {
9761 if (mRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08009762 long time = mBsi.getBatteryUptimeLocked() - mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009763 if (time > 0) {
9764 mStartTime += time;
9765 } else {
9766 mStarts--;
9767 }
9768 mRunning = false;
9769 }
9770 }
9771
Mathew Inwoodc185f082018-08-20 14:28:54 +01009772 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009773 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -08009774 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009775 }
9776
9777 @Override
9778 public int getLaunches(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009779 int val = mLaunches;
9780 if (which == STATS_CURRENT) {
9781 val -= mLoadedLaunches;
9782 } else if (which == STATS_SINCE_UNPLUGGED) {
9783 val -= mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009784 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009785 return val;
9786 }
9787
9788 @Override
9789 public long getStartTime(long now, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009790 long val = getStartTimeToNowLocked(now);
9791 if (which == STATS_CURRENT) {
9792 val -= mLoadedStartTime;
9793 } else if (which == STATS_SINCE_UNPLUGGED) {
9794 val -= mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009795 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009796 return val;
9797 }
9798
9799 @Override
9800 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009801 int val = mStarts;
9802 if (which == STATS_CURRENT) {
9803 val -= mLoadedStarts;
9804 } else if (which == STATS_SINCE_UNPLUGGED) {
9805 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009806 }
9807
9808 return val;
9809 }
9810 }
9811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009812 final Serv newServiceStatsLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08009813 return new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009814 }
9815 }
9816
9817 /**
9818 * Retrieve the statistics object for a particular process, creating
9819 * if needed.
9820 */
9821 public Proc getProcessStatsLocked(String name) {
9822 Proc ps = mProcessStats.get(name);
9823 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08009824 ps = new Proc(mBsi, name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009825 mProcessStats.put(name, ps);
9826 }
9827
9828 return ps;
9829 }
9830
Andreas Gampe3f24e692018-02-05 13:24:28 -08009831 @GuardedBy("mBsi")
Dianne Hackborna8d10942015-11-19 17:55:19 -08009832 public void updateUidProcessStateLocked(int procState) {
9833 int uidRunningState;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009834 // Make special note of Foreground Services
9835 final boolean userAwareService =
9836 (procState == ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009837 uidRunningState = BatteryStats.mapToInternalProcessState(procState);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009838
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009839 if (mProcessState == uidRunningState && userAwareService == mInForegroundService) {
9840 return;
9841 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08009842
Bookatz867c0d72017-03-07 18:23:42 -08009843 final long elapsedRealtimeMs = mBsi.mClocks.elapsedRealtime();
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009844 if (mProcessState != uidRunningState) {
9845 final long uptimeMs = mBsi.mClocks.uptimeMillis();
Dianne Hackborna8d10942015-11-19 17:55:19 -08009846
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009847 if (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
9848 mProcessStateTimer[mProcessState].stopRunningLocked(elapsedRealtimeMs);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009849
Sudheer Shanka5c19b892018-01-05 17:25:46 -08009850 if (mBsi.trackPerProcStateCpuTimes()) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009851 if (mBsi.mPendingUids.size() == 0) {
Sudheer Shankae544d162017-12-28 17:06:20 -08009852 mBsi.mExternalSync.scheduleReadProcStateCpuTimes(
9853 mBsi.mOnBatteryTimeBase.isRunning(),
Sudheer Shankac20379e2018-02-15 00:06:21 -08009854 mBsi.mOnBatteryScreenOffTimeBase.isRunning(),
9855 mBsi.mConstants.PROC_STATE_CPU_TIMES_READ_DELAY_MS);
Mike Ma234d1822018-03-13 18:53:21 -07009856 mBsi.mNumSingleUidCpuTimeReads++;
Sudheer Shankac20379e2018-02-15 00:06:21 -08009857 } else {
Mike Ma234d1822018-03-13 18:53:21 -07009858 mBsi.mNumBatchedSingleUidCpuTimeReads++;
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009859 }
9860 if (mBsi.mPendingUids.indexOfKey(mUid) < 0
9861 || ArrayUtils.contains(CRITICAL_PROC_STATES, mProcessState)) {
9862 mBsi.mPendingUids.put(mUid, mProcessState);
9863 }
9864 } else {
9865 mBsi.mPendingUids.clear();
9866 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07009867 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009868 mProcessState = uidRunningState;
9869 if (uidRunningState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
9870 if (mProcessStateTimer[uidRunningState] == null) {
9871 makeProcessState(uidRunningState, null);
9872 }
9873 mProcessStateTimer[uidRunningState].startRunningLocked(elapsedRealtimeMs);
9874 }
9875
9876 updateOnBatteryBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
9877 updateOnBatteryScreenOffBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009878 }
Bookatz867c0d72017-03-07 18:23:42 -08009879
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009880 if (userAwareService != mInForegroundService) {
9881 if (userAwareService) {
9882 noteForegroundServiceResumedLocked(elapsedRealtimeMs);
9883 } else {
9884 noteForegroundServicePausedLocked(elapsedRealtimeMs);
9885 }
9886 mInForegroundService = userAwareService;
9887 }
Bookatz867c0d72017-03-07 18:23:42 -08009888 }
9889
Bookatzc8c44962017-05-11 12:12:54 -07009890 /** Whether to consider Uid to be in the background for background timebase purposes. */
9891 public boolean isInBackground() {
Bookatz867c0d72017-03-07 18:23:42 -08009892 // Note that PROCESS_STATE_CACHED and ActivityManager.PROCESS_STATE_NONEXISTENT is
9893 // also considered to be 'background' for our purposes, because it's not foreground.
Bookatzc8c44962017-05-11 12:12:54 -07009894 return mProcessState >= PROCESS_STATE_BACKGROUND;
9895 }
9896
9897 public boolean updateOnBatteryBgTimeBase(long uptimeUs, long realtimeUs) {
9898 boolean on = mBsi.mOnBatteryTimeBase.isRunning() && isInBackground();
9899 return mOnBatteryBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
9900 }
9901
9902 public boolean updateOnBatteryScreenOffBgTimeBase(long uptimeUs, long realtimeUs) {
9903 boolean on = mBsi.mOnBatteryScreenOffTimeBase.isRunning() && isInBackground();
9904 return mOnBatteryScreenOffBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009905 }
9906
Dianne Hackbornb5e31652010-09-07 12:13:55 -07009907 public SparseArray<? extends Pid> getPidStats() {
9908 return mPids;
9909 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009910
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009911 public Pid getPidStatsLocked(int pid) {
9912 Pid p = mPids.get(pid);
9913 if (p == null) {
9914 p = new Pid();
9915 mPids.put(pid, p);
9916 }
9917 return p;
9918 }
9919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009920 /**
9921 * Retrieve the statistics object for a particular service, creating
9922 * if needed.
9923 */
9924 public Pkg getPackageStatsLocked(String name) {
9925 Pkg ps = mPackageStats.get(name);
9926 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08009927 ps = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009928 mPackageStats.put(name, ps);
9929 }
9930
9931 return ps;
9932 }
9933
9934 /**
9935 * Retrieve the statistics object for a particular service, creating
9936 * if needed.
9937 */
9938 public Pkg.Serv getServiceStatsLocked(String pkg, String serv) {
9939 Pkg ps = getPackageStatsLocked(pkg);
9940 Pkg.Serv ss = ps.mServiceStats.get(serv);
9941 if (ss == null) {
9942 ss = ps.newServiceStatsLocked();
9943 ps.mServiceStats.put(serv, ss);
9944 }
9945
9946 return ss;
9947 }
9948
Dianne Hackbornd953c532014-08-16 18:17:38 -07009949 public void readSyncSummaryFromParcelLocked(String name, Parcel in) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009950 DualTimer timer = mSyncStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07009951 timer.readSummaryFromParcelLocked(in);
9952 mSyncStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009953 }
9954
Dianne Hackbornd953c532014-08-16 18:17:38 -07009955 public void readJobSummaryFromParcelLocked(String name, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07009956 DualTimer timer = mJobStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07009957 timer.readSummaryFromParcelLocked(in);
9958 mJobStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009959 }
9960
Dianne Hackbornd953c532014-08-16 18:17:38 -07009961 public void readWakeSummaryFromParcelLocked(String wlName, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08009962 Wakelock wl = new Wakelock(mBsi, this);
Dianne Hackbornd953c532014-08-16 18:17:38 -07009963 mWakelockStats.add(wlName, wl);
9964 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009965 getWakelockTimerLocked(wl, WAKE_TYPE_FULL).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009966 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07009967 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009968 getWakelockTimerLocked(wl, WAKE_TYPE_PARTIAL).readSummaryFromParcelLocked(in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07009969 }
9970 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009971 getWakelockTimerLocked(wl, WAKE_TYPE_WINDOW).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009972 }
Adam Lesinski9425fe22015-06-19 12:02:13 -07009973 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009974 getWakelockTimerLocked(wl, WAKE_TYPE_DRAW).readSummaryFromParcelLocked(in);
Adam Lesinski9425fe22015-06-19 12:02:13 -07009975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009976 }
9977
Bookatz867c0d72017-03-07 18:23:42 -08009978 public DualTimer getSensorTimerLocked(int sensor, boolean create) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009979 Sensor se = mSensorStats.get(sensor);
9980 if (se == null) {
9981 if (!create) {
9982 return null;
9983 }
Joe Onoratoabded112016-02-08 16:49:39 -08009984 se = new Sensor(mBsi, this, sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009985 mSensorStats.put(sensor, se);
9986 }
Bookatz867c0d72017-03-07 18:23:42 -08009987 DualTimer t = se.mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009988 if (t != null) {
9989 return t;
9990 }
Joe Onoratoabded112016-02-08 16:49:39 -08009991 ArrayList<StopwatchTimer> timers = mBsi.mSensorTimers.get(sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009992 if (timers == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07009993 timers = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08009994 mBsi.mSensorTimers.put(sensor, timers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009995 }
Bookatz867c0d72017-03-07 18:23:42 -08009996 t = new DualTimer(mBsi.mClocks, this, BatteryStats.SENSOR, timers,
9997 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009998 se.mTimer = t;
9999 return t;
10000 }
10001
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010002 public void noteStartSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -070010003 DualTimer t = mSyncStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010004 if (t != null) {
10005 t.startRunningLocked(elapsedRealtimeMs);
10006 }
10007 }
10008
10009 public void noteStopSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -070010010 DualTimer t = mSyncStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010011 if (t != null) {
10012 t.stopRunningLocked(elapsedRealtimeMs);
10013 }
10014 }
10015
10016 public void noteStartJobLocked(String name, long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -070010017 DualTimer t = mJobStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010018 if (t != null) {
10019 t.startRunningLocked(elapsedRealtimeMs);
10020 }
10021 }
10022
Dianne Hackborn94326cb2017-06-28 16:17:20 -070010023 public void noteStopJobLocked(String name, long elapsedRealtimeMs, int stopReason) {
Bookatzaa4594a2017-03-24 12:39:56 -070010024 DualTimer t = mJobStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010025 if (t != null) {
10026 t.stopRunningLocked(elapsedRealtimeMs);
10027 }
Dianne Hackborn94326cb2017-06-28 16:17:20 -070010028 if (mBsi.mOnBatteryTimeBase.isRunning()) {
10029 SparseIntArray types = mJobCompletions.get(name);
10030 if (types == null) {
10031 types = new SparseIntArray();
10032 mJobCompletions.put(name, types);
10033 }
10034 int last = types.get(stopReason, 0);
10035 types.put(stopReason, last + 1);
10036 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010037 }
10038
Bookatz5b5ec322017-05-26 09:40:38 -070010039 public StopwatchTimer getWakelockTimerLocked(Wakelock wl, int type) {
10040 if (wl == null) {
10041 return null;
10042 }
10043 switch (type) {
10044 case WAKE_TYPE_PARTIAL: {
10045 DualTimer t = wl.mTimerPartial;
10046 if (t == null) {
10047 t = new DualTimer(mBsi.mClocks, this, WAKE_TYPE_PARTIAL,
10048 mBsi.mPartialTimers, mBsi.mOnBatteryScreenOffTimeBase,
10049 mOnBatteryScreenOffBackgroundTimeBase);
10050 wl.mTimerPartial = t;
10051 }
10052 return t;
10053 }
10054 case WAKE_TYPE_FULL: {
10055 StopwatchTimer t = wl.mTimerFull;
10056 if (t == null) {
10057 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_FULL,
10058 mBsi.mFullTimers, mBsi.mOnBatteryTimeBase);
10059 wl.mTimerFull = t;
10060 }
10061 return t;
10062 }
10063 case WAKE_TYPE_WINDOW: {
10064 StopwatchTimer t = wl.mTimerWindow;
10065 if (t == null) {
10066 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_WINDOW,
10067 mBsi.mWindowTimers, mBsi.mOnBatteryTimeBase);
10068 wl.mTimerWindow = t;
10069 }
10070 return t;
10071 }
10072 case WAKE_TYPE_DRAW: {
10073 StopwatchTimer t = wl.mTimerDraw;
10074 if (t == null) {
10075 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_DRAW,
10076 mBsi.mDrawTimers, mBsi.mOnBatteryTimeBase);
10077 wl.mTimerDraw = t;
10078 }
10079 return t;
10080 }
10081 default:
10082 throw new IllegalArgumentException("type=" + type);
10083 }
10084 }
10085
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010086 public void noteStartWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070010087 Wakelock wl = mWakelockStats.startObject(name);
10088 if (wl != null) {
Bookatz5b5ec322017-05-26 09:40:38 -070010089 getWakelockTimerLocked(wl, type).startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010090 }
Bookatzc8c44962017-05-11 12:12:54 -070010091 if (type == WAKE_TYPE_PARTIAL) {
10092 createAggregatedPartialWakelockTimerLocked().startRunningLocked(elapsedRealtimeMs);
10093 if (pid >= 0) {
10094 Pid p = getPidStatsLocked(pid);
10095 if (p.mWakeNesting++ == 0) {
10096 p.mWakeStartMs = elapsedRealtimeMs;
10097 }
Dianne Hackbornb8071d792010-09-09 16:45:15 -070010098 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010099 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010100 }
10101
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010102 public void noteStopWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070010103 Wakelock wl = mWakelockStats.stopObject(name);
10104 if (wl != null) {
Bookatzd6746242017-10-24 18:39:35 -070010105 StopwatchTimer wlt = getWakelockTimerLocked(wl, type);
10106 wlt.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010107 }
Bookatzc8c44962017-05-11 12:12:54 -070010108 if (type == WAKE_TYPE_PARTIAL) {
10109 if (mAggregatedPartialWakelockTimer != null) {
10110 mAggregatedPartialWakelockTimer.stopRunningLocked(elapsedRealtimeMs);
10111 }
10112 if (pid >= 0) {
10113 Pid p = mPids.get(pid);
10114 if (p != null && p.mWakeNesting > 0) {
10115 if (p.mWakeNesting-- == 1) {
10116 p.mWakeSumMs += elapsedRealtimeMs - p.mWakeStartMs;
10117 p.mWakeStartMs = 0;
10118 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -080010119 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010120 }
10121 }
10122 }
10123
Dianne Hackborn287952c2010-09-22 22:34:31 -070010124 public void reportExcessiveCpuLocked(String proc, long overTime, long usedTime) {
10125 Proc p = getProcessStatsLocked(proc);
10126 if (p != null) {
10127 p.addExcessiveCpu(overTime, usedTime);
10128 }
10129 }
10130
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010131 public void noteStartSensor(int sensor, long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -080010132 DualTimer t = getSensorTimerLocked(sensor, /* create= */ true);
Amith Yamasani154d1242017-02-16 10:01:48 -080010133 t.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010134 }
10135
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010136 public void noteStopSensor(int sensor, long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010137 // Don't create a timer if one doesn't already exist
Bookatz867c0d72017-03-07 18:23:42 -080010138 DualTimer t = getSensorTimerLocked(sensor, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010139 if (t != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010140 t.stopRunningLocked(elapsedRealtimeMs);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010141 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010142 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010143
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010144 public void noteStartGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -080010145 noteStartSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010146 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010147
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010148 public void noteStopGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -080010149 noteStopSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010150 }
10151
10152 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -080010153 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010154 }
10155 }
10156
Sudheer Shanka9b735c52017-05-09 18:26:18 -070010157 public long[] getCpuFreqs() {
10158 return mCpuFreqs;
10159 }
10160
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010161 public BatteryStatsImpl(File systemDir, Handler handler, PlatformIdleStateCallback cb,
10162 UserInfoProvider userInfoProvider) {
10163 this(new SystemClocks(), systemDir, handler, cb, userInfoProvider);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010164 }
10165
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010166 private BatteryStatsImpl(Clocks clocks, File systemDir, Handler handler,
10167 PlatformIdleStateCallback cb,
10168 UserInfoProvider userInfoProvider) {
Joe Onoratoabded112016-02-08 16:49:39 -080010169 init(clocks);
10170
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010171 if (systemDir != null) {
10172 mFile = new JournaledFile(new File(systemDir, "batterystats.bin"),
10173 new File(systemDir, "batterystats.bin.tmp"));
10174 } else {
10175 mFile = null;
10176 }
10177 mCheckinFile = new AtomicFile(new File(systemDir, "batterystats-checkin.bin"));
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010178 mDailyFile = new AtomicFile(new File(systemDir, "batterystats-daily.xml"));
Jeff Brown6f357d32014-01-15 20:40:55 -080010179 mHandler = new MyHandler(handler.getLooper());
Sudheer Shanka5c19b892018-01-05 17:25:46 -080010180 mConstants = new Constants(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010181 mStartCount++;
Joe Onoratoabded112016-02-08 16:49:39 -080010182 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -070010183 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -070010184 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010185 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010186 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010187 }
Joe Onoratoabded112016-02-08 16:49:39 -080010188 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase);
10189 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
10190 mOnBatteryTimeBase);
10191 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -11, null,
10192 mOnBatteryTimeBase);
10193 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
10194 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null, mOnBatteryTimeBase);
10195 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase);
10196 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase);
10197 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
10198 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i, null,
10199 mOnBatteryTimeBase);
10200 }
10201 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
10202 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010203 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010204 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010205 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010206 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010207 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010208 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
10209 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010210 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010211 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase, NUM_WIFI_TX_LEVELS);
10212 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
10213 NUM_BT_TX_LEVELS);
10214 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
10215 ModemActivityInfo.TX_POWER_LEVELS);
Joe Onoratoabded112016-02-08 16:49:39 -080010216 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null, mOnBatteryTimeBase);
10217 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
10218 mOnBatteryTimeBase);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010219 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010220 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase);
10221 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080010222 mWifiMulticastWakelockTimer = new StopwatchTimer(mClocks, null,
10223 WIFI_AGGREGATE_MULTICAST_ENABLED, null, mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -080010224 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase);
10225 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null, mOnBatteryTimeBase);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010226 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010227 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i, null,
Dianne Hackborn3251b902014-06-20 14:40:53 -070010228 mOnBatteryTimeBase);
10229 }
Joe Onoratoabded112016-02-08 16:49:39 -080010230 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
10231 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i, null,
10232 mOnBatteryTimeBase);
10233 }
10234 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
10235 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i, null,
10236 mOnBatteryTimeBase);
10237 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080010238 mWifiActiveTimer = new StopwatchTimer(mClocks, null, -900, null, mOnBatteryTimeBase);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080010239 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
10240 mGpsSignalQualityTimer[i] = new StopwatchTimer(mClocks, null, -1000-i, null,
10241 mOnBatteryTimeBase);
10242 }
Joe Onoratoabded112016-02-08 16:49:39 -080010243 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
10244 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
10245 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase);
10246 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase);
10247 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010248 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -070010249 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Mike Ma15313c92017-11-15 17:58:21 -080010250 mDischargeLightDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
10251 mDischargeDeepDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010252 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010253 mOnBattery = mOnBatteryInternal = false;
Joe Onoratoabded112016-02-08 16:49:39 -080010254 long uptime = mClocks.uptimeMillis() * 1000;
10255 long realtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010256 initTimes(uptime, realtime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070010257 mStartPlatformVersion = mEndPlatformVersion = Build.ID;
Evan Millar633a1742009-04-02 16:36:33 -070010258 mDischargeStartLevel = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010259 mDischargeUnplugLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010260 mDischargePlugLevel = -1;
Evan Millar633a1742009-04-02 16:36:33 -070010261 mDischargeCurrentLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010262 mCurrentBatteryLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010263 initDischarge();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010264 clearHistoryLocked();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010265 updateDailyDeadlineLocked();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010266 mPlatformIdleStateCallback = cb;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010267 mUserInfoProvider = userInfoProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010268 }
10269
Mathew Inwoodc185f082018-08-20 14:28:54 +010010270 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010271 public BatteryStatsImpl(Parcel p) {
Joe Onoratoabded112016-02-08 16:49:39 -080010272 this(new SystemClocks(), p);
10273 }
10274
10275 public BatteryStatsImpl(Clocks clocks, Parcel p) {
10276 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070010277 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010278 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010279 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -070010280 mHandler = null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010281 mExternalSync = null;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080010282 mConstants = new Constants(mHandler);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010283 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010284 readFromParcel(p);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010285 mPlatformIdleStateCallback = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010286 }
10287
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010288 public void setPowerProfileLocked(PowerProfile profile) {
10289 mPowerProfile = profile;
Adam Lesinski6832f392015-09-05 18:05:40 -070010290
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010291 // We need to initialize the KernelCpuSpeedReaders to read from
10292 // the first cpu of each core. Once we have the PowerProfile, we have access to this
10293 // information.
10294 final int numClusters = mPowerProfile.getNumCpuClusters();
10295 mKernelCpuSpeedReaders = new KernelCpuSpeedReader[numClusters];
10296 int firstCpuOfCluster = 0;
10297 for (int i = 0; i < numClusters; i++) {
10298 final int numSpeedSteps = mPowerProfile.getNumSpeedStepsInCpuCluster(i);
10299 mKernelCpuSpeedReaders[i] = new KernelCpuSpeedReader(firstCpuOfCluster,
10300 numSpeedSteps);
10301 firstCpuOfCluster += mPowerProfile.getNumCoresInCpuCluster(i);
10302 }
Adam Lesinskif9b20a92016-06-17 17:30:01 -070010303
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010304 if (mEstimatedBatteryCapacity == -1) {
10305 // Initialize the estimated battery capacity to a known preset one.
10306 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
Adam Lesinskie08af192015-03-25 16:42:59 -070010307 }
10308 }
10309
Dianne Hackborn0d903a82010-09-07 23:51:03 -070010310 public void setCallback(BatteryCallback cb) {
10311 mCallback = cb;
10312 }
10313
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010314 public void setRadioScanningTimeoutLocked(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -070010315 if (mPhoneSignalScanningTimer != null) {
10316 mPhoneSignalScanningTimer.setTimeout(timeout);
10317 }
10318 }
10319
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070010320 public void setExternalStatsSyncLocked(ExternalStatsSync sync) {
10321 mExternalSync = sync;
10322 }
10323
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010324 public void updateDailyDeadlineLocked() {
10325 // Get the current time.
10326 long currentTime = mDailyStartTime = System.currentTimeMillis();
10327 Calendar calDeadline = Calendar.getInstance();
10328 calDeadline.setTimeInMillis(currentTime);
10329
10330 // Move time up to the next day, ranging from 1am to 3pm.
10331 calDeadline.set(Calendar.DAY_OF_YEAR, calDeadline.get(Calendar.DAY_OF_YEAR) + 1);
10332 calDeadline.set(Calendar.MILLISECOND, 0);
10333 calDeadline.set(Calendar.SECOND, 0);
10334 calDeadline.set(Calendar.MINUTE, 0);
10335 calDeadline.set(Calendar.HOUR_OF_DAY, 1);
10336 mNextMinDailyDeadline = calDeadline.getTimeInMillis();
10337 calDeadline.set(Calendar.HOUR_OF_DAY, 3);
10338 mNextMaxDailyDeadline = calDeadline.getTimeInMillis();
10339 }
10340
10341 public void recordDailyStatsIfNeededLocked(boolean settled) {
10342 long currentTime = System.currentTimeMillis();
10343 if (currentTime >= mNextMaxDailyDeadline) {
10344 recordDailyStatsLocked();
10345 } else if (settled && currentTime >= mNextMinDailyDeadline) {
10346 recordDailyStatsLocked();
10347 } else if (currentTime < (mDailyStartTime-(1000*60*60*24))) {
10348 recordDailyStatsLocked();
10349 }
10350 }
10351
10352 public void recordDailyStatsLocked() {
10353 DailyItem item = new DailyItem();
10354 item.mStartTime = mDailyStartTime;
10355 item.mEndTime = System.currentTimeMillis();
10356 boolean hasData = false;
10357 if (mDailyDischargeStepTracker.mNumStepDurations > 0) {
10358 hasData = true;
10359 item.mDischargeSteps = new LevelStepTracker(
10360 mDailyDischargeStepTracker.mNumStepDurations,
10361 mDailyDischargeStepTracker.mStepDurations);
10362 }
10363 if (mDailyChargeStepTracker.mNumStepDurations > 0) {
10364 hasData = true;
10365 item.mChargeSteps = new LevelStepTracker(
10366 mDailyChargeStepTracker.mNumStepDurations,
10367 mDailyChargeStepTracker.mStepDurations);
10368 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010369 if (mDailyPackageChanges != null) {
10370 hasData = true;
10371 item.mPackageChanges = mDailyPackageChanges;
10372 mDailyPackageChanges = null;
10373 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010374 mDailyDischargeStepTracker.init();
10375 mDailyChargeStepTracker.init();
10376 updateDailyDeadlineLocked();
10377
10378 if (hasData) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080010379 final long startTime = SystemClock.uptimeMillis();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010380 mDailyItems.add(item);
10381 while (mDailyItems.size() > MAX_DAILY_ITEMS) {
10382 mDailyItems.remove(0);
10383 }
10384 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
10385 try {
10386 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010010387 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010388 writeDailyItemsLocked(out);
Dianne Hackborne17b4452018-01-10 13:15:40 -080010389 final long initialTime = SystemClock.uptimeMillis() - startTime;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010390 BackgroundThread.getHandler().post(new Runnable() {
10391 @Override
10392 public void run() {
10393 synchronized (mCheckinFile) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080010394 final long startTime2 = SystemClock.uptimeMillis();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010395 FileOutputStream stream = null;
10396 try {
10397 stream = mDailyFile.startWrite();
10398 memStream.writeTo(stream);
10399 stream.flush();
10400 FileUtils.sync(stream);
10401 stream.close();
10402 mDailyFile.finishWrite(stream);
Dianne Hackborne17b4452018-01-10 13:15:40 -080010403 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
10404 "batterystats-daily",
10405 initialTime + SystemClock.uptimeMillis() - startTime2);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010406 } catch (IOException e) {
10407 Slog.w("BatteryStats",
10408 "Error writing battery daily items", e);
10409 mDailyFile.failWrite(stream);
10410 }
10411 }
10412 }
10413 });
10414 } catch (IOException e) {
10415 }
10416 }
10417 }
10418
10419 private void writeDailyItemsLocked(XmlSerializer out) throws IOException {
10420 StringBuilder sb = new StringBuilder(64);
10421 out.startDocument(null, true);
10422 out.startTag(null, "daily-items");
10423 for (int i=0; i<mDailyItems.size(); i++) {
10424 final DailyItem dit = mDailyItems.get(i);
10425 out.startTag(null, "item");
10426 out.attribute(null, "start", Long.toString(dit.mStartTime));
10427 out.attribute(null, "end", Long.toString(dit.mEndTime));
10428 writeDailyLevelSteps(out, "dis", dit.mDischargeSteps, sb);
10429 writeDailyLevelSteps(out, "chg", dit.mChargeSteps, sb);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010430 if (dit.mPackageChanges != null) {
10431 for (int j=0; j<dit.mPackageChanges.size(); j++) {
10432 PackageChange pc = dit.mPackageChanges.get(j);
10433 if (pc.mUpdate) {
10434 out.startTag(null, "upd");
10435 out.attribute(null, "pkg", pc.mPackageName);
Dianne Hackborn3accca02013-09-20 09:32:11 -070010436 out.attribute(null, "ver", Long.toString(pc.mVersionCode));
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010437 out.endTag(null, "upd");
10438 } else {
10439 out.startTag(null, "rem");
10440 out.attribute(null, "pkg", pc.mPackageName);
10441 out.endTag(null, "rem");
10442 }
10443 }
10444 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010445 out.endTag(null, "item");
10446 }
10447 out.endTag(null, "daily-items");
10448 out.endDocument();
10449 }
10450
10451 private void writeDailyLevelSteps(XmlSerializer out, String tag, LevelStepTracker steps,
10452 StringBuilder tmpBuilder) throws IOException {
10453 if (steps != null) {
10454 out.startTag(null, tag);
10455 out.attribute(null, "n", Integer.toString(steps.mNumStepDurations));
10456 for (int i=0; i<steps.mNumStepDurations; i++) {
10457 out.startTag(null, "s");
10458 tmpBuilder.setLength(0);
10459 steps.encodeEntryAt(i, tmpBuilder);
10460 out.attribute(null, "v", tmpBuilder.toString());
10461 out.endTag(null, "s");
10462 }
10463 out.endTag(null, tag);
10464 }
10465 }
10466
10467 public void readDailyStatsLocked() {
10468 Slog.d(TAG, "Reading daily items from " + mDailyFile.getBaseFile());
10469 mDailyItems.clear();
10470 FileInputStream stream;
10471 try {
10472 stream = mDailyFile.openRead();
10473 } catch (FileNotFoundException e) {
10474 return;
10475 }
10476 try {
10477 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010010478 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010479 readDailyItemsLocked(parser);
10480 } catch (XmlPullParserException e) {
10481 } finally {
10482 try {
10483 stream.close();
10484 } catch (IOException e) {
10485 }
10486 }
10487 }
10488
10489 private void readDailyItemsLocked(XmlPullParser parser) {
10490 try {
10491 int type;
10492 while ((type = parser.next()) != XmlPullParser.START_TAG
10493 && type != XmlPullParser.END_DOCUMENT) {
10494 ;
10495 }
10496
10497 if (type != XmlPullParser.START_TAG) {
10498 throw new IllegalStateException("no start tag found");
10499 }
10500
10501 int outerDepth = parser.getDepth();
10502 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10503 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10504 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10505 continue;
10506 }
10507
10508 String tagName = parser.getName();
10509 if (tagName.equals("item")) {
10510 readDailyItemTagLocked(parser);
10511 } else {
10512 Slog.w(TAG, "Unknown element under <daily-items>: "
10513 + parser.getName());
10514 XmlUtils.skipCurrentTag(parser);
10515 }
10516 }
10517
10518 } catch (IllegalStateException e) {
10519 Slog.w(TAG, "Failed parsing daily " + e);
10520 } catch (NullPointerException e) {
10521 Slog.w(TAG, "Failed parsing daily " + e);
10522 } catch (NumberFormatException e) {
10523 Slog.w(TAG, "Failed parsing daily " + e);
10524 } catch (XmlPullParserException e) {
10525 Slog.w(TAG, "Failed parsing daily " + e);
10526 } catch (IOException e) {
10527 Slog.w(TAG, "Failed parsing daily " + e);
10528 } catch (IndexOutOfBoundsException e) {
10529 Slog.w(TAG, "Failed parsing daily " + e);
10530 }
10531 }
10532
10533 void readDailyItemTagLocked(XmlPullParser parser) throws NumberFormatException,
10534 XmlPullParserException, IOException {
10535 DailyItem dit = new DailyItem();
10536 String attr = parser.getAttributeValue(null, "start");
10537 if (attr != null) {
10538 dit.mStartTime = Long.parseLong(attr);
10539 }
10540 attr = parser.getAttributeValue(null, "end");
10541 if (attr != null) {
10542 dit.mEndTime = Long.parseLong(attr);
10543 }
10544 int outerDepth = parser.getDepth();
10545 int type;
10546 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10547 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10548 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10549 continue;
10550 }
10551
10552 String tagName = parser.getName();
10553 if (tagName.equals("dis")) {
10554 readDailyItemTagDetailsLocked(parser, dit, false, "dis");
10555 } else if (tagName.equals("chg")) {
10556 readDailyItemTagDetailsLocked(parser, dit, true, "chg");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010557 } else if (tagName.equals("upd")) {
10558 if (dit.mPackageChanges == null) {
10559 dit.mPackageChanges = new ArrayList<>();
10560 }
10561 PackageChange pc = new PackageChange();
10562 pc.mUpdate = true;
10563 pc.mPackageName = parser.getAttributeValue(null, "pkg");
10564 String verStr = parser.getAttributeValue(null, "ver");
Dianne Hackborn3accca02013-09-20 09:32:11 -070010565 pc.mVersionCode = verStr != null ? Long.parseLong(verStr) : 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010566 dit.mPackageChanges.add(pc);
10567 XmlUtils.skipCurrentTag(parser);
10568 } else if (tagName.equals("rem")) {
10569 if (dit.mPackageChanges == null) {
10570 dit.mPackageChanges = new ArrayList<>();
10571 }
10572 PackageChange pc = new PackageChange();
10573 pc.mUpdate = false;
10574 pc.mPackageName = parser.getAttributeValue(null, "pkg");
10575 dit.mPackageChanges.add(pc);
10576 XmlUtils.skipCurrentTag(parser);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010577 } else {
10578 Slog.w(TAG, "Unknown element under <item>: "
10579 + parser.getName());
10580 XmlUtils.skipCurrentTag(parser);
10581 }
10582 }
10583 mDailyItems.add(dit);
10584 }
10585
10586 void readDailyItemTagDetailsLocked(XmlPullParser parser, DailyItem dit, boolean isCharge,
10587 String tag)
10588 throws NumberFormatException, XmlPullParserException, IOException {
10589 final String numAttr = parser.getAttributeValue(null, "n");
10590 if (numAttr == null) {
10591 Slog.w(TAG, "Missing 'n' attribute at " + parser.getPositionDescription());
10592 XmlUtils.skipCurrentTag(parser);
10593 return;
10594 }
10595 final int num = Integer.parseInt(numAttr);
10596 LevelStepTracker steps = new LevelStepTracker(num);
10597 if (isCharge) {
10598 dit.mChargeSteps = steps;
10599 } else {
10600 dit.mDischargeSteps = steps;
10601 }
10602 int i = 0;
10603 int outerDepth = parser.getDepth();
10604 int type;
10605 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10606 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10607 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10608 continue;
10609 }
10610
10611 String tagName = parser.getName();
10612 if ("s".equals(tagName)) {
10613 if (i < num) {
10614 String valueAttr = parser.getAttributeValue(null, "v");
10615 if (valueAttr != null) {
10616 steps.decodeEntryAt(i, valueAttr);
10617 i++;
10618 }
10619 }
10620 } else {
10621 Slog.w(TAG, "Unknown element under <" + tag + ">: "
10622 + parser.getName());
10623 XmlUtils.skipCurrentTag(parser);
10624 }
10625 }
10626 steps.mNumStepDurations = i;
10627 }
10628
10629 @Override
10630 public DailyItem getDailyItemLocked(int daysAgo) {
10631 int index = mDailyItems.size()-1-daysAgo;
10632 return index >= 0 ? mDailyItems.get(index) : null;
10633 }
10634
10635 @Override
10636 public long getCurrentDailyStartTime() {
10637 return mDailyStartTime;
10638 }
10639
10640 @Override
10641 public long getNextMinDailyDeadline() {
10642 return mNextMinDailyDeadline;
10643 }
10644
10645 @Override
10646 public long getNextMaxDailyDeadline() {
10647 return mNextMaxDailyDeadline;
10648 }
10649
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010650 @Override
10651 public boolean startIteratingOldHistoryLocked() {
10652 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
10653 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010654 if ((mHistoryIterator = mHistory) == null) {
10655 return false;
10656 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010657 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010658 mHistoryReadTmp.clear();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010659 mReadOverflow = false;
10660 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010661 return true;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010662 }
10663
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010664 @Override
10665 public boolean getNextOldHistoryLocked(HistoryItem out) {
10666 boolean end = mHistoryBuffer.dataPosition() >= mHistoryBuffer.dataSize();
10667 if (!end) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010668 readHistoryDelta(mHistoryBuffer, mHistoryReadTmp);
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010669 mReadOverflow |= mHistoryReadTmp.cmd == HistoryItem.CMD_OVERFLOW;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010670 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010671 HistoryItem cur = mHistoryIterator;
10672 if (cur == null) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010673 if (!mReadOverflow && !end) {
10674 Slog.w(TAG, "Old history ends before new history!");
10675 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010676 return false;
10677 }
10678 out.setTo(cur);
10679 mHistoryIterator = cur.next;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010680 if (!mReadOverflow) {
10681 if (end) {
10682 Slog.w(TAG, "New history ends before old history!");
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010683 } else if (!out.same(mHistoryReadTmp)) {
Dianne Hackborn8c841092013-06-24 13:46:13 -070010684 PrintWriter pw = new FastPrintWriter(new LogWriter(android.util.Log.WARN, TAG));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010685 pw.println("Histories differ!");
10686 pw.println("Old history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010687 (new HistoryPrinter()).printNextItem(pw, out, 0, false, true);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010688 pw.println("New history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010689 (new HistoryPrinter()).printNextItem(pw, mHistoryReadTmp, 0, false,
10690 true);
Dianne Hackborn8c841092013-06-24 13:46:13 -070010691 pw.flush();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010692 }
10693 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010694 return true;
10695 }
10696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010697 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010698 public void finishIteratingOldHistoryLocked() {
10699 mIteratingHistory = false;
10700 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010701 mHistoryIterator = null;
10702 }
10703
10704 public int getHistoryTotalSize() {
10705 return MAX_HISTORY_BUFFER;
10706 }
10707
10708 public int getHistoryUsedSize() {
10709 return mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010710 }
10711
10712 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +010010713 @UnsupportedAppUsage
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010714 public boolean startIteratingHistoryLocked() {
10715 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
10716 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010717 if (mHistoryBuffer.dataSize() <= 0) {
10718 return false;
10719 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010720 mHistoryBuffer.setDataPosition(0);
10721 mReadOverflow = false;
10722 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010723 mReadHistoryStrings = new String[mHistoryTagPool.size()];
10724 mReadHistoryUids = new int[mHistoryTagPool.size()];
10725 mReadHistoryChars = 0;
10726 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
10727 final HistoryTag tag = ent.getKey();
10728 final int idx = ent.getValue();
10729 mReadHistoryStrings[idx] = tag.string;
10730 mReadHistoryUids[idx] = tag.uid;
10731 mReadHistoryChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080010732 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010733 return true;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010734 }
10735
10736 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -080010737 public int getHistoryStringPoolSize() {
10738 return mReadHistoryStrings.length;
10739 }
10740
10741 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010742 public int getHistoryStringPoolBytes() {
10743 // Each entry is a fixed 12 bytes: 4 for index, 4 for uid, 4 for string size
10744 // Each string character is 2 bytes.
10745 return (mReadHistoryStrings.length * 12) + (mReadHistoryChars * 2);
10746 }
10747
10748 @Override
10749 public String getHistoryTagPoolString(int index) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080010750 return mReadHistoryStrings[index];
10751 }
10752
10753 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010754 public int getHistoryTagPoolUid(int index) {
10755 return mReadHistoryUids[index];
10756 }
10757
10758 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +010010759 @UnsupportedAppUsage
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010760 public boolean getNextHistoryLocked(HistoryItem out) {
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010761 final int pos = mHistoryBuffer.dataPosition();
10762 if (pos == 0) {
10763 out.clear();
10764 }
10765 boolean end = pos >= mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010766 if (end) {
10767 return false;
10768 }
10769
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010770 final long lastRealtime = out.time;
10771 final long lastWalltime = out.currentTime;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010772 readHistoryDelta(mHistoryBuffer, out);
Dianne Hackborn37de0982014-05-09 09:32:18 -070010773 if (out.cmd != HistoryItem.CMD_CURRENT_TIME
10774 && out.cmd != HistoryItem.CMD_RESET && lastWalltime != 0) {
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010775 out.currentTime = lastWalltime + (out.time - lastRealtime);
10776 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010777 return true;
10778 }
10779
10780 @Override
10781 public void finishIteratingHistoryLocked() {
10782 mIteratingHistory = false;
10783 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn099bc622014-01-22 13:39:16 -080010784 mReadHistoryStrings = null;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010785 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010786
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010787 @Override
Dianne Hackbornb5e31652010-09-07 12:13:55 -070010788 public long getHistoryBaseTime() {
10789 return mHistoryBaseTime;
10790 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010791
Dianne Hackbornb5e31652010-09-07 12:13:55 -070010792 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010793 public int getStartCount() {
10794 return mStartCount;
10795 }
10796
Mathew Inwoodc185f082018-08-20 14:28:54 +010010797 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010798 public boolean isOnBattery() {
10799 return mOnBattery;
10800 }
10801
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010802 public boolean isCharging() {
10803 return mCharging;
10804 }
10805
Mike Mac2f518a2017-09-19 16:06:03 -070010806 public boolean isScreenOn(int state) {
Chris Phoenix10a4a642017-09-25 13:21:00 -070010807 return state == Display.STATE_ON || state == Display.STATE_VR
10808 || state == Display.STATE_ON_SUSPEND;
Mike Mac2f518a2017-09-19 16:06:03 -070010809 }
10810
10811 public boolean isScreenOff(int state) {
10812 return state == Display.STATE_OFF;
10813 }
10814
10815 public boolean isScreenDoze(int state) {
10816 return state == Display.STATE_DOZE || state == Display.STATE_DOZE_SUSPEND;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010817 }
10818
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010819 void initTimes(long uptime, long realtime) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080010820 mStartClockTime = System.currentTimeMillis();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010821 mOnBatteryTimeBase.init(uptime, realtime);
10822 mOnBatteryScreenOffTimeBase.init(uptime, realtime);
Dianne Hackborn4590e522014-03-24 13:36:46 -070010823 mRealtime = 0;
10824 mUptime = 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010825 mRealtimeStart = realtime;
Dianne Hackborn4590e522014-03-24 13:36:46 -070010826 mUptimeStart = uptime;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010827 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010828
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010829 void initDischarge() {
10830 mLowDischargeAmountSinceCharge = 0;
10831 mHighDischargeAmountSinceCharge = 0;
10832 mDischargeAmountScreenOn = 0;
10833 mDischargeAmountScreenOnSinceCharge = 0;
10834 mDischargeAmountScreenOff = 0;
10835 mDischargeAmountScreenOffSinceCharge = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010836 mDischargeAmountScreenDoze = 0;
10837 mDischargeAmountScreenDozeSinceCharge = 0;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010838 mDischargeStepTracker.init();
10839 mChargeStepTracker.init();
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010840 mDischargeScreenOffCounter.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -070010841 mDischargeScreenDozeCounter.reset(false);
Mike Ma15313c92017-11-15 17:58:21 -080010842 mDischargeLightDozeCounter.reset(false);
10843 mDischargeDeepDozeCounter.reset(false);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010844 mDischargeCounter.reset(false);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010845 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010846
10847 public void resetAllStatsCmdLocked() {
10848 resetAllStatsLocked();
Joe Onoratoabded112016-02-08 16:49:39 -080010849 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -070010850 long uptime = mSecUptime * 1000;
Joe Onoratoabded112016-02-08 16:49:39 -080010851 long mSecRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010852 long realtime = mSecRealtime * 1000;
10853 mDischargeStartLevel = mHistoryCur.batteryLevel;
10854 pullPendingStateUpdatesLocked();
Dianne Hackborn40c87252014-03-19 16:55:40 -070010855 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010856 mDischargeCurrentLevel = mDischargeUnplugLevel = mDischargePlugLevel
10857 = mCurrentBatteryLevel = mHistoryCur.batteryLevel;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010858 mOnBatteryTimeBase.reset(uptime, realtime);
10859 mOnBatteryScreenOffTimeBase.reset(uptime, realtime);
10860 if ((mHistoryCur.states&HistoryItem.STATE_BATTERY_PLUGGED_FLAG) == 0) {
Mike Mac2f518a2017-09-19 16:06:03 -070010861 if (isScreenOn(mScreenState)) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010862 mDischargeScreenOnUnplugLevel = mHistoryCur.batteryLevel;
Mike Mac2f518a2017-09-19 16:06:03 -070010863 mDischargeScreenDozeUnplugLevel = 0;
10864 mDischargeScreenOffUnplugLevel = 0;
10865 } else if (isScreenDoze(mScreenState)) {
10866 mDischargeScreenOnUnplugLevel = 0;
10867 mDischargeScreenDozeUnplugLevel = mHistoryCur.batteryLevel;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010868 mDischargeScreenOffUnplugLevel = 0;
10869 } else {
10870 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010871 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010872 mDischargeScreenOffUnplugLevel = mHistoryCur.batteryLevel;
10873 }
10874 mDischargeAmountScreenOn = 0;
10875 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010876 mDischargeAmountScreenDoze = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010877 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070010878 initActiveHistoryEventsLocked(mSecRealtime, mSecUptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010879 }
10880
10881 private void resetAllStatsLocked() {
Adam Lesinski8ce36942016-05-26 16:05:35 -070010882 final long uptimeMillis = mClocks.uptimeMillis();
10883 final long elapsedRealtimeMillis = mClocks.elapsedRealtime();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010884 mStartCount = 0;
Adam Lesinski8ce36942016-05-26 16:05:35 -070010885 initTimes(uptimeMillis * 1000, elapsedRealtimeMillis * 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010886 mScreenOnTimer.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -070010887 mScreenDozeTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010888 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010889 mScreenBrightnessTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010890 }
Adam Lesinski1a76a622016-06-22 10:28:47 -070010891
10892 if (mPowerProfile != null) {
10893 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
10894 } else {
10895 mEstimatedBatteryCapacity = -1;
10896 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070010897 mMinLearnedBatteryCapacity = -1;
10898 mMaxLearnedBatteryCapacity = -1;
Jeff Browne95c3cd2014-05-02 16:59:26 -070010899 mInteractiveTimer.reset(false);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070010900 mPowerSaveModeEnabledTimer.reset(false);
Adam Lesinski8ce36942016-05-26 16:05:35 -070010901 mLastIdleTimeStart = elapsedRealtimeMillis;
Dianne Hackborn08c47a52015-10-15 12:38:14 -070010902 mLongestLightIdleTime = 0;
10903 mLongestFullIdleTime = 0;
10904 mDeviceIdleModeLightTimer.reset(false);
10905 mDeviceIdleModeFullTimer.reset(false);
10906 mDeviceLightIdlingTimer.reset(false);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010907 mDeviceIdlingTimer.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010908 mPhoneOnTimer.reset(false);
10909 mAudioOnTimer.reset(false);
10910 mVideoOnTimer.reset(false);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070010911 mFlashlightOnTimer.reset(false);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070010912 mCameraOnTimer.reset(false);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010913 mBluetoothScanTimer.reset(false);
Wink Saville52840902011-02-18 12:40:47 -080010914 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010915 mPhoneSignalStrengthsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010916 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010917 mPhoneSignalScanningTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010918 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010919 mPhoneDataConnectionsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010920 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010921 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010922 mNetworkByteActivityCounters[i].reset(false);
10923 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010924 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010925 mMobileRadioActiveTimer.reset(false);
10926 mMobileRadioActivePerAppTimer.reset(false);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010927 mMobileRadioActiveAdjustedTime.reset(false);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080010928 mMobileRadioActiveUnknownTime.reset(false);
10929 mMobileRadioActiveUnknownCount.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010930 mWifiOnTimer.reset(false);
10931 mGlobalWifiRunningTimer.reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010932 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010933 mWifiStateTimer[i].reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010934 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070010935 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
10936 mWifiSupplStateTimer[i].reset(false);
10937 }
10938 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
10939 mWifiSignalStrengthsTimer[i].reset(false);
10940 }
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080010941 mWifiMulticastWakelockTimer.reset(false);
Siddharth Rayb50a6842017-12-14 15:15:28 -080010942 mWifiActiveTimer.reset(false);
10943 mWifiActivity.reset(false);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080010944 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
10945 mGpsSignalQualityTimer[i].reset(false);
10946 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010947 mBluetoothActivity.reset(false);
10948 mModemActivity.reset(false);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080010949 mNumConnectivityChange = mLoadedNumConnectivityChange = mUnpluggedNumConnectivityChange = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010950
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010951 for (int i=0; i<mUidStats.size(); i++) {
Bookatz993a0be2017-07-21 09:03:23 -070010952 if (mUidStats.valueAt(i).reset(uptimeMillis * 1000, elapsedRealtimeMillis * 1000)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010953 mUidStats.remove(mUidStats.keyAt(i));
10954 i--;
10955 }
10956 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010957
Bookatz50df7112017-08-04 14:53:26 -070010958 if (mRpmStats.size() > 0) {
10959 for (SamplingTimer timer : mRpmStats.values()) {
10960 mOnBatteryTimeBase.remove(timer);
10961 }
10962 mRpmStats.clear();
10963 }
10964 if (mScreenOffRpmStats.size() > 0) {
10965 for (SamplingTimer timer : mScreenOffRpmStats.values()) {
10966 mOnBatteryScreenOffTimeBase.remove(timer);
10967 }
10968 mScreenOffRpmStats.clear();
10969 }
10970
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010971 if (mKernelWakelockStats.size() > 0) {
10972 for (SamplingTimer timer : mKernelWakelockStats.values()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010973 mOnBatteryScreenOffTimeBase.remove(timer);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010974 }
10975 mKernelWakelockStats.clear();
10976 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010977
James Carr3a226052016-07-01 14:49:52 -070010978 if (mKernelMemoryStats.size() > 0) {
10979 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
10980 mOnBatteryTimeBase.remove(mKernelMemoryStats.valueAt(i));
10981 }
10982 mKernelMemoryStats.clear();
10983 }
10984
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010985 if (mWakeupReasonStats.size() > 0) {
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070010986 for (SamplingTimer timer : mWakeupReasonStats.values()) {
10987 mOnBatteryTimeBase.remove(timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010988 }
10989 mWakeupReasonStats.clear();
10990 }
10991
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080010992 mLastHistoryStepDetails = null;
10993 mLastStepCpuUserTime = mLastStepCpuSystemTime = 0;
10994 mCurStepCpuUserTime = mCurStepCpuSystemTime = 0;
10995 mLastStepCpuUserTime = mCurStepCpuUserTime = 0;
10996 mLastStepCpuSystemTime = mCurStepCpuSystemTime = 0;
10997 mLastStepStatUserTime = mCurStepStatUserTime = 0;
10998 mLastStepStatSystemTime = mCurStepStatSystemTime = 0;
10999 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime = 0;
11000 mLastStepStatIrqTime = mCurStepStatIrqTime = 0;
11001 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime = 0;
11002 mLastStepStatIdleTime = mCurStepStatIdleTime = 0;
11003
Mike Ma234d1822018-03-13 18:53:21 -070011004 mNumAllUidCpuTimeReads = 0;
11005 mNumUidsRemoved = 0;
11006
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011007 initDischarge();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011008
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011009 clearHistoryLocked();
Fyodor Kupolov8aa51242018-04-23 12:44:51 -070011010 mHandler.sendEmptyMessage(MSG_REPORT_RESET_STATS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011011 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011012
Dianne Hackborn40c87252014-03-19 16:55:40 -070011013 private void initActiveHistoryEventsLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080011014 for (int i=0; i<HistoryItem.EVENT_COUNT; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011015 if (!mRecordAllHistory && i == HistoryItem.EVENT_PROC) {
11016 // Not recording process starts/stops.
11017 continue;
11018 }
Dianne Hackborn37de0982014-05-09 09:32:18 -070011019 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(i);
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080011020 if (active == null) {
11021 continue;
11022 }
Dianne Hackborn37de0982014-05-09 09:32:18 -070011023 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
11024 SparseIntArray uids = ent.getValue();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080011025 for (int j=0; j<uids.size(); j++) {
Dianne Hackborn37de0982014-05-09 09:32:18 -070011026 addHistoryEventLocked(elapsedRealtimeMs, uptimeMs, i, ent.getKey(),
11027 uids.keyAt(j));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080011028 }
11029 }
11030 }
11031 }
11032
Mike Mac2f518a2017-09-19 16:06:03 -070011033 void updateDischargeScreenLevelsLocked(int oldState, int newState) {
11034 updateOldDischargeScreenLevelLocked(oldState);
11035 updateNewDischargeScreenLevelLocked(newState);
11036 }
11037
11038 private void updateOldDischargeScreenLevelLocked(int state) {
11039 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011040 int diff = mDischargeScreenOnUnplugLevel - mDischargeCurrentLevel;
11041 if (diff > 0) {
11042 mDischargeAmountScreenOn += diff;
11043 mDischargeAmountScreenOnSinceCharge += diff;
11044 }
Mike Mac2f518a2017-09-19 16:06:03 -070011045 } else if (isScreenDoze(state)) {
11046 int diff = mDischargeScreenDozeUnplugLevel - mDischargeCurrentLevel;
11047 if (diff > 0) {
11048 mDischargeAmountScreenDoze += diff;
11049 mDischargeAmountScreenDozeSinceCharge += diff;
11050 }
11051 } else if (isScreenOff(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011052 int diff = mDischargeScreenOffUnplugLevel - mDischargeCurrentLevel;
11053 if (diff > 0) {
11054 mDischargeAmountScreenOff += diff;
11055 mDischargeAmountScreenOffSinceCharge += diff;
11056 }
11057 }
Mike Mac2f518a2017-09-19 16:06:03 -070011058 }
11059
11060 private void updateNewDischargeScreenLevelLocked(int state) {
11061 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011062 mDischargeScreenOnUnplugLevel = mDischargeCurrentLevel;
11063 mDischargeScreenOffUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070011064 mDischargeScreenDozeUnplugLevel = 0;
11065 } else if (isScreenDoze(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011066 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070011067 mDischargeScreenDozeUnplugLevel = mDischargeCurrentLevel;
11068 mDischargeScreenOffUnplugLevel = 0;
11069 } else if (isScreenOff(state)) {
11070 mDischargeScreenOnUnplugLevel = 0;
11071 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011072 mDischargeScreenOffUnplugLevel = mDischargeCurrentLevel;
11073 }
11074 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011075
Dianne Hackborna7c837f2014-01-15 16:20:44 -080011076 public void pullPendingStateUpdatesLocked() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -080011077 if (mOnBatteryInternal) {
Mike Mac2f518a2017-09-19 16:06:03 -070011078 updateDischargeScreenLevelsLocked(mScreenState, mScreenState);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080011079 }
Dianne Hackborna7c837f2014-01-15 16:20:44 -080011080 }
11081
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011082 private final NetworkStatsFactory mNetworkStatsFactory = new NetworkStatsFactory();
11083 private final Pools.Pool<NetworkStats> mNetworkStatsPool = new Pools.SynchronizedPool<>(6);
11084
11085 private final Object mWifiNetworkLock = new Object();
11086
11087 @GuardedBy("mWifiNetworkLock")
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011088 private String[] mWifiIfaces = EmptyArray.STRING;
11089
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011090 @GuardedBy("mWifiNetworkLock")
11091 private NetworkStats mLastWifiNetworkStats = new NetworkStats(0, -1);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011092
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011093 private final Object mModemNetworkLock = new Object();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011094
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011095 @GuardedBy("mModemNetworkLock")
11096 private String[] mModemIfaces = EmptyArray.STRING;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011097
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011098 @GuardedBy("mModemNetworkLock")
11099 private NetworkStats mLastModemNetworkStats = new NetworkStats(0, -1);
11100
11101 private NetworkStats readNetworkStatsLocked(String[] ifaces) {
11102 try {
11103 if (!ArrayUtils.isEmpty(ifaces)) {
11104 return mNetworkStatsFactory.readNetworkStatsDetail(NetworkStats.UID_ALL, ifaces,
11105 NetworkStats.TAG_NONE, mNetworkStatsPool.acquire());
11106 }
11107 } catch (IOException e) {
11108 Slog.e(TAG, "failed to read network stats for ifaces: " + Arrays.toString(ifaces));
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011109 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011110 return null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011111 }
11112
Chenjie Yu89083392018-01-11 14:53:31 -080011113 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011114 * Distribute WiFi energy info and network traffic to apps.
11115 * @param info The energy information from the WiFi controller.
11116 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011117 public void updateWifiState(@Nullable final WifiActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011118 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011119 Slog.d(TAG, "Updating wifi stats: " + Arrays.toString(mWifiIfaces));
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011120 }
11121
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011122 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070011123 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011124 synchronized (mWifiNetworkLock) {
11125 final NetworkStats latestStats = readNetworkStatsLocked(mWifiIfaces);
11126 if (latestStats != null) {
11127 delta = NetworkStats.subtract(latestStats, mLastWifiNetworkStats, null, null,
11128 mNetworkStatsPool.acquire());
11129 mNetworkStatsPool.release(mLastWifiNetworkStats);
11130 mLastWifiNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070011131 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011132 }
11133
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011134 synchronized (this) {
11135 if (!mOnBatteryInternal) {
11136 if (delta != null) {
11137 mNetworkStatsPool.release(delta);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011138 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011139 return;
11140 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011141
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011142 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
11143 SparseLongArray rxPackets = new SparseLongArray();
11144 SparseLongArray txPackets = new SparseLongArray();
11145 long totalTxPackets = 0;
11146 long totalRxPackets = 0;
11147 if (delta != null) {
11148 NetworkStats.Entry entry = new NetworkStats.Entry();
11149 final int size = delta.size();
11150 for (int i = 0; i < size; i++) {
11151 entry = delta.getValues(i, entry);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011152
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011153 if (DEBUG_ENERGY) {
11154 Slog.d(TAG, "Wifi uid " + entry.uid + ": delta rx=" + entry.rxBytes
11155 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
11156 + " txPackets=" + entry.txPackets);
11157 }
11158
11159 if (entry.rxBytes == 0 && entry.txBytes == 0) {
11160 // Skip the lookup below since there is no work to do.
11161 continue;
11162 }
11163
11164 final Uid u = getUidStatsLocked(mapUid(entry.uid));
11165 if (entry.rxBytes != 0) {
11166 u.noteNetworkActivityLocked(NETWORK_WIFI_RX_DATA, entry.rxBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -080011167 entry.rxPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011168 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11169 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_RX_DATA, entry.rxBytes,
11170 entry.rxPackets);
11171 }
11172 mNetworkByteActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
11173 entry.rxBytes);
11174 mNetworkPacketActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
11175 entry.rxPackets);
11176
11177 rxPackets.put(u.getUid(), entry.rxPackets);
11178
11179 // Sum the total number of packets so that the Rx Power can
11180 // be evenly distributed amongst the apps.
11181 totalRxPackets += entry.rxPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -080011182 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011183
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011184 if (entry.txBytes != 0) {
11185 u.noteNetworkActivityLocked(NETWORK_WIFI_TX_DATA, entry.txBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -080011186 entry.txPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011187 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11188 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_TX_DATA, entry.txBytes,
11189 entry.txPackets);
11190 }
11191 mNetworkByteActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
11192 entry.txBytes);
11193 mNetworkPacketActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
11194 entry.txPackets);
11195
11196 txPackets.put(u.getUid(), entry.txPackets);
11197
11198 // Sum the total number of packets so that the Tx Power can
11199 // be evenly distributed amongst the apps.
11200 totalTxPackets += entry.txPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -080011201 }
Adam Lesinskiba88e682015-12-08 12:06:55 -080011202 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011203 mNetworkStatsPool.release(delta);
11204 delta = null;
Adam Lesinskie08af192015-03-25 16:42:59 -070011205 }
11206
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011207 if (info != null) {
11208 mHasWifiReporting = true;
Adam Lesinskie08af192015-03-25 16:42:59 -070011209
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011210 // Measured in mAms
11211 final long txTimeMs = info.getControllerTxTimeMillis();
11212 final long rxTimeMs = info.getControllerRxTimeMillis();
Siddharth Rayb50a6842017-12-14 15:15:28 -080011213 final long scanTimeMs = info.getControllerScanTimeMillis();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011214 final long idleTimeMs = info.getControllerIdleTimeMillis();
11215 final long totalTimeMs = txTimeMs + rxTimeMs + idleTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -070011216
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011217 long leftOverRxTimeMs = rxTimeMs;
11218 long leftOverTxTimeMs = txTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -070011219
Adam Lesinskie08af192015-03-25 16:42:59 -070011220 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011221 Slog.d(TAG, "------ BEGIN WiFi power blaming ------");
11222 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
11223 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
11224 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms");
11225 Slog.d(TAG, " Total Time: " + totalTimeMs + " ms");
Siddharth Rayb50a6842017-12-14 15:15:28 -080011226 Slog.d(TAG, " Scan Time: " + scanTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070011227 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011228
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011229 long totalWifiLockTimeMs = 0;
11230 long totalScanTimeMs = 0;
11231
11232 // On the first pass, collect some totals so that we can normalize power
11233 // calculations if we need to.
11234 final int uidStatsSize = mUidStats.size();
11235 for (int i = 0; i < uidStatsSize; i++) {
11236 final Uid uid = mUidStats.valueAt(i);
11237
11238 // Sum the total scan power for all apps.
11239 totalScanTimeMs += uid.mWifiScanTimer.getTimeSinceMarkLocked(
11240 elapsedRealtimeMs * 1000) / 1000;
11241
11242 // Sum the total time holding wifi lock for all apps.
11243 totalWifiLockTimeMs += uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
11244 elapsedRealtimeMs * 1000) / 1000;
11245 }
11246
11247 if (DEBUG_ENERGY && totalScanTimeMs > rxTimeMs) {
11248 Slog.d(TAG,
11249 " !Estimated scan time > Actual rx time (" + totalScanTimeMs + " ms > "
11250 + rxTimeMs + " ms). Normalizing scan time.");
11251 }
11252 if (DEBUG_ENERGY && totalScanTimeMs > txTimeMs) {
11253 Slog.d(TAG,
11254 " !Estimated scan time > Actual tx time (" + totalScanTimeMs + " ms > "
11255 + txTimeMs + " ms). Normalizing scan time.");
11256 }
11257
11258 // Actually assign and distribute power usage to apps.
11259 for (int i = 0; i < uidStatsSize; i++) {
11260 final Uid uid = mUidStats.valueAt(i);
11261
11262 long scanTimeSinceMarkMs = uid.mWifiScanTimer.getTimeSinceMarkLocked(
11263 elapsedRealtimeMs * 1000) / 1000;
11264 if (scanTimeSinceMarkMs > 0) {
11265 // Set the new mark so that next time we get new data since this point.
11266 uid.mWifiScanTimer.setMark(elapsedRealtimeMs);
11267
11268 long scanRxTimeSinceMarkMs = scanTimeSinceMarkMs;
11269 long scanTxTimeSinceMarkMs = scanTimeSinceMarkMs;
11270
11271 // Our total scan time is more than the reported Tx/Rx time.
11272 // This is possible because the cost of a scan is approximate.
11273 // Let's normalize the result so that we evenly blame each app
11274 // scanning.
11275 //
11276 // This means that we may have apps that transmitted/received packets not be
11277 // blamed for this, but this is fine as scans are relatively more expensive.
11278 if (totalScanTimeMs > rxTimeMs) {
11279 scanRxTimeSinceMarkMs = (rxTimeMs * scanRxTimeSinceMarkMs) /
11280 totalScanTimeMs;
11281 }
11282 if (totalScanTimeMs > txTimeMs) {
11283 scanTxTimeSinceMarkMs = (txTimeMs * scanTxTimeSinceMarkMs) /
11284 totalScanTimeMs;
11285 }
11286
11287 if (DEBUG_ENERGY) {
11288 Slog.d(TAG, " ScanTime for UID " + uid.getUid() + ": Rx:"
11289 + scanRxTimeSinceMarkMs + " ms Tx:"
11290 + scanTxTimeSinceMarkMs + " ms)");
11291 }
11292
11293 ControllerActivityCounterImpl activityCounter =
11294 uid.getOrCreateWifiControllerActivityLocked();
11295 activityCounter.getRxTimeCounter().addCountLocked(scanRxTimeSinceMarkMs);
11296 activityCounter.getTxTimeCounters()[0].addCountLocked(
11297 scanTxTimeSinceMarkMs);
11298 leftOverRxTimeMs -= scanRxTimeSinceMarkMs;
11299 leftOverTxTimeMs -= scanTxTimeSinceMarkMs;
11300 }
11301
11302 // Distribute evenly the power consumed while Idle to each app holding a WiFi
11303 // lock.
11304 final long wifiLockTimeSinceMarkMs =
11305 uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
11306 elapsedRealtimeMs * 1000) / 1000;
11307 if (wifiLockTimeSinceMarkMs > 0) {
11308 // Set the new mark so that next time we get new data since this point.
11309 uid.mFullWifiLockTimer.setMark(elapsedRealtimeMs);
11310
11311 final long myIdleTimeMs = (wifiLockTimeSinceMarkMs * idleTimeMs)
11312 / totalWifiLockTimeMs;
11313 if (DEBUG_ENERGY) {
11314 Slog.d(TAG, " IdleTime for UID " + uid.getUid() + ": "
11315 + myIdleTimeMs + " ms");
11316 }
11317 uid.getOrCreateWifiControllerActivityLocked().getIdleTimeCounter()
11318 .addCountLocked(myIdleTimeMs);
11319 }
11320 }
11321
Adam Lesinskie08af192015-03-25 16:42:59 -070011322 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011323 Slog.d(TAG, " New RxPower: " + leftOverRxTimeMs + " ms");
11324 Slog.d(TAG, " New TxPower: " + leftOverTxTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070011325 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011326
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011327 // Distribute the remaining Tx power appropriately between all apps that transmitted
11328 // packets.
11329 for (int i = 0; i < txPackets.size(); i++) {
11330 final Uid uid = getUidStatsLocked(txPackets.keyAt(i));
11331 final long myTxTimeMs = (txPackets.valueAt(i) * leftOverTxTimeMs)
11332 / totalTxPackets;
11333 if (DEBUG_ENERGY) {
11334 Slog.d(TAG, " TxTime for UID " + uid.getUid() + ": " + myTxTimeMs + " ms");
11335 }
11336 uid.getOrCreateWifiControllerActivityLocked().getTxTimeCounters()[0]
11337 .addCountLocked(myTxTimeMs);
11338 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011339
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011340 // Distribute the remaining Rx power appropriately between all apps that received
11341 // packets.
11342 for (int i = 0; i < rxPackets.size(); i++) {
11343 final Uid uid = getUidStatsLocked(rxPackets.keyAt(i));
11344 final long myRxTimeMs = (rxPackets.valueAt(i) * leftOverRxTimeMs)
11345 / totalRxPackets;
11346 if (DEBUG_ENERGY) {
11347 Slog.d(TAG, " RxTime for UID " + uid.getUid() + ": " + myRxTimeMs + " ms");
11348 }
11349 uid.getOrCreateWifiControllerActivityLocked().getRxTimeCounter()
11350 .addCountLocked(myRxTimeMs);
11351 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011352
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011353 // Any left over power use will be picked up by the WiFi category in BatteryStatsHelper.
11354
11355
11356 // Update WiFi controller stats.
11357 mWifiActivity.getRxTimeCounter().addCountLocked(info.getControllerRxTimeMillis());
11358 mWifiActivity.getTxTimeCounters()[0].addCountLocked(
11359 info.getControllerTxTimeMillis());
Siddharth Rayb50a6842017-12-14 15:15:28 -080011360 mWifiActivity.getScanTimeCounter().addCountLocked(
11361 info.getControllerScanTimeMillis());
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011362 mWifiActivity.getIdleTimeCounter().addCountLocked(
11363 info.getControllerIdleTimeMillis());
11364
11365 // POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11366 final double opVolt = mPowerProfile.getAveragePower(
11367 PowerProfile.POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11368 if (opVolt != 0) {
11369 // We store the power drain as mAms.
11370 mWifiActivity.getPowerCounter().addCountLocked(
11371 (long) (info.getControllerEnergyUsed() / opVolt));
11372 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011373 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011374 }
11375 }
11376
Chenjie Yu89083392018-01-11 14:53:31 -080011377 private ModemActivityInfo mLastModemActivityInfo =
11378 new ModemActivityInfo(0, 0, 0, new int[0], 0, 0);
11379
Chenjie Yua54e54d2018-02-14 20:12:52 -080011380 private ModemActivityInfo getDeltaModemActivityInfo(ModemActivityInfo activityInfo) {
11381 if (activityInfo == null) {
11382 return null;
11383 }
11384 int[] txTimeMs = new int[ModemActivityInfo.TX_POWER_LEVELS];
11385 for (int i = 0; i < ModemActivityInfo.TX_POWER_LEVELS; i++) {
11386 txTimeMs[i] = activityInfo.getTxTimeMillis()[i]
11387 - mLastModemActivityInfo.getTxTimeMillis()[i];
11388 }
11389 ModemActivityInfo deltaInfo = new ModemActivityInfo(activityInfo.getTimestamp(),
11390 activityInfo.getSleepTimeMillis() - mLastModemActivityInfo.getSleepTimeMillis(),
11391 activityInfo.getIdleTimeMillis() - mLastModemActivityInfo.getIdleTimeMillis(),
11392 txTimeMs,
11393 activityInfo.getRxTimeMillis() - mLastModemActivityInfo.getRxTimeMillis(),
11394 activityInfo.getEnergyUsed() - mLastModemActivityInfo.getEnergyUsed());
11395 mLastModemActivityInfo = activityInfo;
11396 return deltaInfo;
11397 }
11398
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011399 /**
11400 * Distribute Cell radio energy info and network traffic to apps.
11401 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011402 public void updateMobileRadioState(@Nullable final ModemActivityInfo activityInfo) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011403 if (DEBUG_ENERGY) {
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011404 Slog.d(TAG, "Updating mobile radio stats with " + activityInfo);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011405 }
Chenjie Yua54e54d2018-02-14 20:12:52 -080011406 ModemActivityInfo deltaInfo = getDeltaModemActivityInfo(activityInfo);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011407
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011408 // Add modem tx power to history.
Chenjie Yua54e54d2018-02-14 20:12:52 -080011409 addModemTxPowerToHistory(deltaInfo);
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011410
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011411 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070011412 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011413 synchronized (mModemNetworkLock) {
11414 final NetworkStats latestStats = readNetworkStatsLocked(mModemIfaces);
11415 if (latestStats != null) {
11416 delta = NetworkStats.subtract(latestStats, mLastModemNetworkStats, null, null,
11417 mNetworkStatsPool.acquire());
11418 mNetworkStatsPool.release(mLastModemNetworkStats);
11419 mLastModemNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070011420 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011421 }
11422
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011423 synchronized (this) {
11424 if (!mOnBatteryInternal) {
11425 if (delta != null) {
11426 mNetworkStatsPool.release(delta);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011427 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011428 return;
Adam Lesinskie08af192015-03-25 16:42:59 -070011429 }
11430
Chenjie Yua54e54d2018-02-14 20:12:52 -080011431 if (deltaInfo != null) {
Siddharth Ray2038af82018-01-17 17:40:26 -080011432 mHasModemReporting = true;
11433 mModemActivity.getIdleTimeCounter().addCountLocked(
Chenjie Yua54e54d2018-02-14 20:12:52 -080011434 deltaInfo.getIdleTimeMillis());
Siddharth Rayed754702018-02-15 12:44:37 -080011435 mModemActivity.getSleepTimeCounter().addCountLocked(
11436 deltaInfo.getSleepTimeMillis());
Chenjie Yua54e54d2018-02-14 20:12:52 -080011437 mModemActivity.getRxTimeCounter().addCountLocked(deltaInfo.getRxTimeMillis());
Siddharth Ray2038af82018-01-17 17:40:26 -080011438 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
11439 mModemActivity.getTxTimeCounters()[lvl]
Chenjie Yua54e54d2018-02-14 20:12:52 -080011440 .addCountLocked(deltaInfo.getTxTimeMillis()[lvl]);
Siddharth Ray2038af82018-01-17 17:40:26 -080011441 }
11442
11443 // POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11444 final double opVolt = mPowerProfile.getAveragePower(
11445 PowerProfile.POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11446 if (opVolt != 0) {
11447 double energyUsed =
Chenjie Yua54e54d2018-02-14 20:12:52 -080011448 deltaInfo.getSleepTimeMillis() *
Siddharth Ray2038af82018-01-17 17:40:26 -080011449 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_SLEEP)
Chenjie Yua54e54d2018-02-14 20:12:52 -080011450 + deltaInfo.getIdleTimeMillis() *
Siddharth Ray2038af82018-01-17 17:40:26 -080011451 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_IDLE)
Chenjie Yua54e54d2018-02-14 20:12:52 -080011452 + deltaInfo.getRxTimeMillis() *
Siddharth Ray2038af82018-01-17 17:40:26 -080011453 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_RX);
Chenjie Yua54e54d2018-02-14 20:12:52 -080011454 int[] txTimeMs = deltaInfo.getTxTimeMillis();
Chenjie Yu89083392018-01-11 14:53:31 -080011455 for (int i = 0; i < Math.min(txTimeMs.length,
Chenjie Yua54e54d2018-02-14 20:12:52 -080011456 SignalStrength.NUM_SIGNAL_STRENGTH_BINS); i++) {
Chenjie Yu89083392018-01-11 14:53:31 -080011457 energyUsed += txTimeMs[i] * mPowerProfile.getAveragePower(
Chenjie Yua54e54d2018-02-14 20:12:52 -080011458 PowerProfile.POWER_MODEM_CONTROLLER_TX, i);
Siddharth Ray2038af82018-01-17 17:40:26 -080011459 }
11460
11461 // We store the power drain as mAms.
11462 mModemActivity.getPowerCounter().addCountLocked((long) energyUsed);
11463 }
11464 }
11465
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070011466 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011467 long radioTime = mMobileRadioActivePerAppTimer.getTimeSinceMarkLocked(
11468 elapsedRealtimeMs * 1000);
11469 mMobileRadioActivePerAppTimer.setMark(elapsedRealtimeMs);
11470
11471 long totalRxPackets = 0;
11472 long totalTxPackets = 0;
11473 if (delta != null) {
11474 NetworkStats.Entry entry = new NetworkStats.Entry();
11475 final int size = delta.size();
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011476 for (int i = 0; i < size; i++) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011477 entry = delta.getValues(i, entry);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011478 if (entry.rxPackets == 0 && entry.txPackets == 0) {
11479 continue;
11480 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011481
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011482 if (DEBUG_ENERGY) {
11483 Slog.d(TAG, "Mobile uid " + entry.uid + ": delta rx=" + entry.rxBytes
11484 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
11485 + " txPackets=" + entry.txPackets);
11486 }
11487
11488 totalRxPackets += entry.rxPackets;
11489 totalTxPackets += entry.txPackets;
11490
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011491 final Uid u = getUidStatsLocked(mapUid(entry.uid));
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011492 u.noteNetworkActivityLocked(NETWORK_MOBILE_RX_DATA, entry.rxBytes,
11493 entry.rxPackets);
11494 u.noteNetworkActivityLocked(NETWORK_MOBILE_TX_DATA, entry.txBytes,
11495 entry.txPackets);
11496 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11497 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_RX_DATA,
11498 entry.rxBytes, entry.rxPackets);
11499 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_TX_DATA,
11500 entry.txBytes, entry.txPackets);
11501 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011502
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011503 mNetworkByteActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
11504 entry.rxBytes);
11505 mNetworkByteActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
11506 entry.txBytes);
11507 mNetworkPacketActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
11508 entry.rxPackets);
11509 mNetworkPacketActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
11510 entry.txPackets);
11511 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011512
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011513 // Now distribute proportional blame to the apps that did networking.
11514 long totalPackets = totalRxPackets + totalTxPackets;
11515 if (totalPackets > 0) {
11516 for (int i = 0; i < size; i++) {
11517 entry = delta.getValues(i, entry);
11518 if (entry.rxPackets == 0 && entry.txPackets == 0) {
11519 continue;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011520 }
11521
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011522 final Uid u = getUidStatsLocked(mapUid(entry.uid));
11523
11524 // Distribute total radio active time in to this app.
11525 final long appPackets = entry.rxPackets + entry.txPackets;
11526 final long appRadioTime = (radioTime * appPackets) / totalPackets;
11527 u.noteMobileRadioActiveTimeLocked(appRadioTime);
11528
11529 // Remove this app from the totals, so that we don't lose any time
11530 // due to rounding.
11531 radioTime -= appRadioTime;
11532 totalPackets -= appPackets;
11533
Chenjie Yua54e54d2018-02-14 20:12:52 -080011534 if (deltaInfo != null) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011535 ControllerActivityCounterImpl activityCounter =
11536 u.getOrCreateModemControllerActivityLocked();
11537 if (totalRxPackets > 0 && entry.rxPackets > 0) {
Chenjie Yua54e54d2018-02-14 20:12:52 -080011538 final long rxMs = (entry.rxPackets * deltaInfo.getRxTimeMillis())
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011539 / totalRxPackets;
11540 activityCounter.getRxTimeCounter().addCountLocked(rxMs);
11541 }
11542
11543 if (totalTxPackets > 0 && entry.txPackets > 0) {
11544 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
11545 long txMs =
Chenjie Yua54e54d2018-02-14 20:12:52 -080011546 entry.txPackets * deltaInfo.getTxTimeMillis()[lvl];
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011547 txMs /= totalTxPackets;
11548 activityCounter.getTxTimeCounters()[lvl].addCountLocked(txMs);
11549 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011550 }
11551 }
11552 }
11553 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011554
11555 if (radioTime > 0) {
11556 // Whoops, there is some radio time we can't blame on an app!
11557 mMobileRadioActiveUnknownTime.addCountLocked(radioTime);
11558 mMobileRadioActiveUnknownCount.addCountLocked(1);
11559 }
11560
11561 mNetworkStatsPool.release(delta);
11562 delta = null;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011563 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011564 }
11565 }
11566
11567 /**
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011568 * Add modem tx power to history
11569 * Device is said to be in high cellular transmit power when it has spent most of the transmit
11570 * time at the highest power level.
11571 * @param activityInfo
11572 */
Siddharth Raya67fb562018-02-28 13:46:16 -080011573 private synchronized void addModemTxPowerToHistory(final ModemActivityInfo activityInfo) {
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011574 if (activityInfo == null) {
11575 return;
11576 }
11577 int[] txTimeMs = activityInfo.getTxTimeMillis();
11578 if (txTimeMs == null || txTimeMs.length != ModemActivityInfo.TX_POWER_LEVELS) {
11579 return;
11580 }
11581 final long elapsedRealtime = mClocks.elapsedRealtime();
11582 final long uptime = mClocks.uptimeMillis();
11583 int levelMaxTimeSpent = 0;
11584 for (int i = 1; i < txTimeMs.length; i++) {
11585 if (txTimeMs[i] > txTimeMs[levelMaxTimeSpent]) {
11586 levelMaxTimeSpent = i;
11587 }
11588 }
11589 if (levelMaxTimeSpent == ModemActivityInfo.TX_POWER_LEVELS - 1) {
11590 if (!mIsCellularTxPowerHigh) {
11591 mHistoryCur.states2 |= HistoryItem.STATE2_CELLULAR_HIGH_TX_POWER_FLAG;
11592 addHistoryRecordLocked(elapsedRealtime, uptime);
11593 mIsCellularTxPowerHigh = true;
11594 }
11595 return;
11596 }
11597 if (mIsCellularTxPowerHigh) {
11598 mHistoryCur.states2 &= ~HistoryItem.STATE2_CELLULAR_HIGH_TX_POWER_FLAG;
11599 addHistoryRecordLocked(elapsedRealtime, uptime);
11600 mIsCellularTxPowerHigh = false;
11601 }
11602 return;
11603 }
11604
Mike Ma561a8d92018-03-20 18:24:05 -070011605 private final class BluetoothActivityInfoCache {
11606 long idleTimeMs;
11607 long rxTimeMs;
11608 long txTimeMs;
11609 long energy;
11610
11611 SparseLongArray uidRxBytes = new SparseLongArray();
11612 SparseLongArray uidTxBytes = new SparseLongArray();
11613
11614 void set(BluetoothActivityEnergyInfo info) {
11615 idleTimeMs = info.getControllerIdleTimeMillis();
11616 rxTimeMs = info.getControllerRxTimeMillis();
11617 txTimeMs = info.getControllerTxTimeMillis();
11618 energy = info.getControllerEnergyUsed();
11619 if (info.getUidTraffic() != null) {
11620 for (UidTraffic traffic : info.getUidTraffic()) {
11621 uidRxBytes.put(traffic.getUid(), traffic.getRxBytes());
11622 uidTxBytes.put(traffic.getUid(), traffic.getTxBytes());
11623 }
11624 }
11625 }
11626 }
11627
11628 private final BluetoothActivityInfoCache mLastBluetoothActivityInfo
11629 = new BluetoothActivityInfoCache();
11630
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011631 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011632 * Distribute Bluetooth energy info and network traffic to apps.
Mike Ma561a8d92018-03-20 18:24:05 -070011633 *
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011634 * @param info The energy information from the bluetooth controller.
11635 */
11636 public void updateBluetoothStateLocked(@Nullable final BluetoothActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011637 if (DEBUG_ENERGY) {
Adam Lesinski50e47602015-12-04 17:04:54 -080011638 Slog.d(TAG, "Updating bluetooth stats: " + info);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011639 }
11640
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011641 if (info == null || !mOnBatteryInternal) {
11642 return;
11643 }
Adam Lesinskie283d332015-04-16 12:29:25 -070011644
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011645 mHasBluetoothReporting = true;
11646
Bookatz867c0d72017-03-07 18:23:42 -080011647 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Mike Ma561a8d92018-03-20 18:24:05 -070011648 final long rxTimeMs =
11649 info.getControllerRxTimeMillis() - mLastBluetoothActivityInfo.rxTimeMs;
11650 final long txTimeMs =
11651 info.getControllerTxTimeMillis() - mLastBluetoothActivityInfo.txTimeMs;
11652 final long idleTimeMs =
11653 info.getControllerIdleTimeMillis() - mLastBluetoothActivityInfo.idleTimeMs;
11654
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011655 if (DEBUG_ENERGY) {
11656 Slog.d(TAG, "------ BEGIN BLE power blaming ------");
11657 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
11658 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
Chenjie Yu89083392018-01-11 14:53:31 -080011659 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms");
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011660 }
11661
11662 long totalScanTimeMs = 0;
11663
11664 final int uidCount = mUidStats.size();
11665 for (int i = 0; i < uidCount; i++) {
11666 final Uid u = mUidStats.valueAt(i);
11667 if (u.mBluetoothScanTimer == null) {
11668 continue;
Adam Lesinskie283d332015-04-16 12:29:25 -070011669 }
Adam Lesinski50e47602015-12-04 17:04:54 -080011670
Bookatzaa4594a2017-03-24 12:39:56 -070011671 totalScanTimeMs += u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011672 elapsedRealtimeMs * 1000) / 1000;
11673 }
11674
11675 final boolean normalizeScanRxTime = (totalScanTimeMs > rxTimeMs);
11676 final boolean normalizeScanTxTime = (totalScanTimeMs > txTimeMs);
11677
11678 if (DEBUG_ENERGY) {
11679 Slog.d(TAG, "Normalizing scan power for RX=" + normalizeScanRxTime
11680 + " TX=" + normalizeScanTxTime);
11681 }
11682
11683 long leftOverRxTimeMs = rxTimeMs;
11684 long leftOverTxTimeMs = txTimeMs;
11685
11686 for (int i = 0; i < uidCount; i++) {
11687 final Uid u = mUidStats.valueAt(i);
11688 if (u.mBluetoothScanTimer == null) {
11689 continue;
11690 }
11691
Bookatzaa4594a2017-03-24 12:39:56 -070011692 long scanTimeSinceMarkMs = u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011693 elapsedRealtimeMs * 1000) / 1000;
11694 if (scanTimeSinceMarkMs > 0) {
11695 // Set the new mark so that next time we get new data since this point.
11696 u.mBluetoothScanTimer.setMark(elapsedRealtimeMs);
11697
11698 long scanTimeRxSinceMarkMs = scanTimeSinceMarkMs;
11699 long scanTimeTxSinceMarkMs = scanTimeSinceMarkMs;
11700
11701 if (normalizeScanRxTime) {
11702 // Scan time is longer than the total rx time in the controller,
11703 // so distribute the scan time proportionately. This means regular traffic
11704 // will not blamed, but scans are more expensive anyways.
11705 scanTimeRxSinceMarkMs = (rxTimeMs * scanTimeRxSinceMarkMs) / totalScanTimeMs;
11706 }
11707
11708 if (normalizeScanTxTime) {
11709 // Scan time is longer than the total tx time in the controller,
11710 // so distribute the scan time proportionately. This means regular traffic
11711 // will not blamed, but scans are more expensive anyways.
11712 scanTimeTxSinceMarkMs = (txTimeMs * scanTimeTxSinceMarkMs) / totalScanTimeMs;
11713 }
11714
11715 final ControllerActivityCounterImpl counter =
11716 u.getOrCreateBluetoothControllerActivityLocked();
11717 counter.getRxTimeCounter().addCountLocked(scanTimeRxSinceMarkMs);
11718 counter.getTxTimeCounters()[0].addCountLocked(scanTimeTxSinceMarkMs);
11719
11720 leftOverRxTimeMs -= scanTimeRxSinceMarkMs;
11721 leftOverTxTimeMs -= scanTimeTxSinceMarkMs;
11722 }
11723 }
11724
11725 if (DEBUG_ENERGY) {
Mike Ma561a8d92018-03-20 18:24:05 -070011726 Slog.d(TAG, "Left over time for traffic RX=" + leftOverRxTimeMs + " TX="
11727 + leftOverTxTimeMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011728 }
11729
11730 //
11731 // Now distribute blame to apps that did bluetooth traffic.
11732 //
11733
11734 long totalTxBytes = 0;
11735 long totalRxBytes = 0;
11736
11737 final UidTraffic[] uidTraffic = info.getUidTraffic();
Mike Ma561a8d92018-03-20 18:24:05 -070011738 final int numUids = uidTraffic != null ? uidTraffic.length : 0;
11739 for (int i = 0; i < numUids; i++) {
11740 final UidTraffic traffic = uidTraffic[i];
11741 final long rxBytes = traffic.getRxBytes() - mLastBluetoothActivityInfo.uidRxBytes.get(
11742 traffic.getUid());
11743 final long txBytes = traffic.getTxBytes() - mLastBluetoothActivityInfo.uidTxBytes.get(
11744 traffic.getUid());
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011745
11746 // Add to the global counters.
Mike Ma561a8d92018-03-20 18:24:05 -070011747 mNetworkByteActivityCounters[NETWORK_BT_RX_DATA].addCountLocked(rxBytes);
11748 mNetworkByteActivityCounters[NETWORK_BT_TX_DATA].addCountLocked(txBytes);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011749
11750 // Add to the UID counters.
11751 final Uid u = getUidStatsLocked(mapUid(traffic.getUid()));
Mike Ma561a8d92018-03-20 18:24:05 -070011752 u.noteNetworkActivityLocked(NETWORK_BT_RX_DATA, rxBytes, 0);
11753 u.noteNetworkActivityLocked(NETWORK_BT_TX_DATA, txBytes, 0);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011754
11755 // Calculate the total traffic.
Mike Ma561a8d92018-03-20 18:24:05 -070011756 totalRxBytes += rxBytes;
11757 totalTxBytes += txBytes;
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011758 }
11759
Mike Ma561a8d92018-03-20 18:24:05 -070011760 if ((totalTxBytes != 0 || totalRxBytes != 0) && (leftOverRxTimeMs != 0
11761 || leftOverTxTimeMs != 0)) {
11762 for (int i = 0; i < numUids; i++) {
11763 final UidTraffic traffic = uidTraffic[i];
11764 final int uid = traffic.getUid();
11765 final long rxBytes =
11766 traffic.getRxBytes() - mLastBluetoothActivityInfo.uidRxBytes.get(uid);
11767 final long txBytes =
11768 traffic.getTxBytes() - mLastBluetoothActivityInfo.uidTxBytes.get(uid);
Adam Lesinski50e47602015-12-04 17:04:54 -080011769
Mike Ma561a8d92018-03-20 18:24:05 -070011770 final Uid u = getUidStatsLocked(mapUid(uid));
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011771 final ControllerActivityCounterImpl counter =
11772 u.getOrCreateBluetoothControllerActivityLocked();
11773
Mike Ma561a8d92018-03-20 18:24:05 -070011774 if (totalRxBytes > 0 && rxBytes > 0) {
11775 final long timeRxMs = (leftOverRxTimeMs * rxBytes) / totalRxBytes;
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011776 if (DEBUG_ENERGY) {
Mike Ma561a8d92018-03-20 18:24:05 -070011777 Slog.d(TAG, "UID=" + uid + " rx_bytes=" + rxBytes + " rx_time=" + timeRxMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011778 }
11779 counter.getRxTimeCounter().addCountLocked(timeRxMs);
11780 leftOverRxTimeMs -= timeRxMs;
11781 }
11782
Mike Ma561a8d92018-03-20 18:24:05 -070011783 if (totalTxBytes > 0 && txBytes > 0) {
11784 final long timeTxMs = (leftOverTxTimeMs * txBytes) / totalTxBytes;
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011785 if (DEBUG_ENERGY) {
Mike Ma561a8d92018-03-20 18:24:05 -070011786 Slog.d(TAG, "UID=" + uid + " tx_bytes=" + txBytes + " tx_time=" + timeTxMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011787 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011788 counter.getTxTimeCounters()[0].addCountLocked(timeTxMs);
11789 leftOverTxTimeMs -= timeTxMs;
11790 }
Adam Lesinski50e47602015-12-04 17:04:54 -080011791 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011792 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011793
Chenjie Yu89083392018-01-11 14:53:31 -080011794 mBluetoothActivity.getRxTimeCounter().addCountLocked(rxTimeMs);
11795 mBluetoothActivity.getTxTimeCounters()[0].addCountLocked(txTimeMs);
11796 mBluetoothActivity.getIdleTimeCounter().addCountLocked(idleTimeMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011797
11798 // POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11799 final double opVolt = mPowerProfile.getAveragePower(
11800 PowerProfile.POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11801 if (opVolt != 0) {
11802 // We store the power drain as mAms.
11803 mBluetoothActivity.getPowerCounter().addCountLocked(
Mike Ma561a8d92018-03-20 18:24:05 -070011804 (long) ((info.getControllerEnergyUsed() - mLastBluetoothActivityInfo.energy)
11805 / opVolt));
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011806 }
Mike Ma561a8d92018-03-20 18:24:05 -070011807 mLastBluetoothActivityInfo.set(info);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011808 }
11809
11810 /**
Bookatz0b8a0502017-09-13 11:51:52 -070011811 * Read and record Resource Power Manager (RPM) state and voter times.
11812 * If RPM stats were fetched more recently than RPM_STATS_UPDATE_FREQ_MS ago, uses the old data
11813 * instead of fetching it anew.
Bookatz50df7112017-08-04 14:53:26 -070011814 */
11815 public void updateRpmStatsLocked() {
11816 if (mPlatformIdleStateCallback == null) return;
Bookatz0b8a0502017-09-13 11:51:52 -070011817 long now = SystemClock.elapsedRealtime();
11818 if (now - mLastRpmStatsUpdateTimeMs >= RPM_STATS_UPDATE_FREQ_MS) {
11819 mPlatformIdleStateCallback.fillLowPowerStats(mTmpRpmStats);
11820 mLastRpmStatsUpdateTimeMs = now;
11821 }
Bookatz50df7112017-08-04 14:53:26 -070011822
11823 for (Map.Entry<String, RpmStats.PowerStatePlatformSleepState> pstate
11824 : mTmpRpmStats.mPlatformLowPowerStats.entrySet()) {
11825
11826 // Update values for this platform state.
11827 final String pName = pstate.getKey();
11828 final long pTimeUs = pstate.getValue().mTimeMs * 1000;
11829 final int pCount = pstate.getValue().mCount;
11830 getRpmTimerLocked(pName).update(pTimeUs, pCount);
Bookatz82b341172017-09-07 19:06:08 -070011831 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11832 getScreenOffRpmTimerLocked(pName).update(pTimeUs, pCount);
11833 }
Bookatz50df7112017-08-04 14:53:26 -070011834
11835 // Update values for each voter of this platform state.
11836 for (Map.Entry<String, RpmStats.PowerStateElement> voter
11837 : pstate.getValue().mVoters.entrySet()) {
11838 final String vName = pName + "." + voter.getKey();
11839 final long vTimeUs = voter.getValue().mTimeMs * 1000;
11840 final int vCount = voter.getValue().mCount;
11841 getRpmTimerLocked(vName).update(vTimeUs, vCount);
Bookatz82b341172017-09-07 19:06:08 -070011842 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11843 getScreenOffRpmTimerLocked(vName).update(vTimeUs, vCount);
11844 }
Bookatz50df7112017-08-04 14:53:26 -070011845 }
11846 }
11847
11848 for (Map.Entry<String, RpmStats.PowerStateSubsystem> subsys
11849 : mTmpRpmStats.mSubsystemLowPowerStats.entrySet()) {
11850
11851 final String subsysName = subsys.getKey();
11852 for (Map.Entry<String, RpmStats.PowerStateElement> sstate
11853 : subsys.getValue().mStates.entrySet()) {
11854 final String name = subsysName + "." + sstate.getKey();
11855 final long timeUs = sstate.getValue().mTimeMs * 1000;
11856 final int count = sstate.getValue().mCount;
11857 getRpmTimerLocked(name).update(timeUs, count);
Bookatz82b341172017-09-07 19:06:08 -070011858 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11859 getScreenOffRpmTimerLocked(name).update(timeUs, count);
11860 }
Bookatz50df7112017-08-04 14:53:26 -070011861 }
11862 }
11863 }
11864
11865 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011866 * Read and distribute kernel wake lock use across apps.
11867 */
11868 public void updateKernelWakelocksLocked() {
11869 final KernelWakelockStats wakelockStats = mKernelWakelockReader.readKernelWakelockStats(
11870 mTmpWakelockStats);
11871 if (wakelockStats == null) {
11872 // Not crashing might make board bringup easier.
11873 Slog.w(TAG, "Couldn't get kernel wake lock stats");
11874 return;
11875 }
11876
11877 for (Map.Entry<String, KernelWakelockStats.Entry> ent : wakelockStats.entrySet()) {
11878 String name = ent.getKey();
11879 KernelWakelockStats.Entry kws = ent.getValue();
11880
11881 SamplingTimer kwlt = mKernelWakelockStats.get(name);
11882 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -070011883 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011884 mKernelWakelockStats.put(name, kwlt);
11885 }
Adam Lesinskid84ad302016-05-17 18:31:02 -070011886
Adam Lesinski757c6ea2016-04-21 09:55:41 -070011887 kwlt.update(kws.mTotalTime, kws.mCount);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011888 kwlt.setUpdateVersion(kws.mVersion);
11889 }
11890
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011891 int numWakelocksSetStale = 0;
Adam Lesinskid84ad302016-05-17 18:31:02 -070011892 // Set timers to stale if they didn't appear in /d/wakeup_sources (or /proc/wakelocks)
11893 // this time.
11894 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
11895 SamplingTimer st = ent.getValue();
11896 if (st.getUpdateVersion() != wakelockStats.kernelWakelockVersion) {
11897 st.endSample();
11898 numWakelocksSetStale++;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011899 }
11900 }
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011901
Adam Lesinskid84ad302016-05-17 18:31:02 -070011902 // Record whether we've seen a non-zero time (for debugging b/22716723).
11903 if (wakelockStats.isEmpty()) {
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011904 Slog.wtf(TAG, "All kernel wakelocks had time of zero");
11905 }
11906
11907 if (numWakelocksSetStale == mKernelWakelockStats.size()) {
11908 Slog.wtf(TAG, "All kernel wakelocks were set stale. new version=" +
11909 wakelockStats.kernelWakelockVersion);
11910 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011911 }
11912
Adam Lesinski72478f02015-06-17 15:39:43 -070011913 // We use an anonymous class to access these variables,
11914 // so they can't live on the stack or they'd have to be
11915 // final MutableLong objects (more allocations).
11916 // Used in updateCpuTimeLocked().
11917 long mTempTotalCpuUserTimeUs;
11918 long mTempTotalCpuSystemTimeUs;
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011919 long[][] mWakeLockAllocationsUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070011920
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011921 /**
James Carr3a226052016-07-01 14:49:52 -070011922 * Reads the newest memory stats from the kernel.
11923 */
11924 public void updateKernelMemoryBandwidthLocked() {
11925 mKernelMemoryBandwidthStats.updateStats();
11926 LongSparseLongArray bandwidthEntries = mKernelMemoryBandwidthStats.getBandwidthEntries();
11927 final int bandwidthEntryCount = bandwidthEntries.size();
11928 int index;
11929 for (int i = 0; i < bandwidthEntryCount; i++) {
11930 SamplingTimer timer;
11931 if ((index = mKernelMemoryStats.indexOfKey(bandwidthEntries.keyAt(i))) >= 0) {
11932 timer = mKernelMemoryStats.valueAt(index);
11933 } else {
11934 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
11935 mKernelMemoryStats.put(bandwidthEntries.keyAt(i), timer);
11936 }
11937 timer.update(bandwidthEntries.valueAt(i), 1);
11938 if (DEBUG_MEMORY) {
11939 Slog.d(TAG, String.format("Added entry %d and updated timer to: "
11940 + "mUnpluggedReportedTotalTime %d size %d", bandwidthEntries.keyAt(i),
11941 mKernelMemoryStats.get(
11942 bandwidthEntries.keyAt(i)).mUnpluggedReportedTotalTime,
11943 mKernelMemoryStats.size()));
11944 }
11945 }
11946 }
11947
Sudheer Shankac57729a2018-02-09 15:44:42 -080011948 public boolean isOnBatteryLocked() {
11949 return mOnBatteryTimeBase.isRunning();
11950 }
11951
11952 public boolean isOnBatteryScreenOffLocked() {
11953 return mOnBatteryScreenOffTimeBase.isRunning();
11954 }
11955
James Carr3a226052016-07-01 14:49:52 -070011956 /**
Adam Lesinski72478f02015-06-17 15:39:43 -070011957 * Read and distribute CPU usage across apps. If their are partial wakelocks being held
11958 * and we are on battery with screen off, we give more of the cpu time to those apps holding
11959 * wakelocks. If the screen is on, we just assign the actual cpu time an app used.
Sudheer Shankac57729a2018-02-09 15:44:42 -080011960 * It's possible this will be invoked after the internal battery/screen states are updated, so
11961 * passing the appropriate battery/screen states to try attribute the cpu times to correct
11962 * buckets.
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011963 */
Andreas Gampe3f24e692018-02-05 13:24:28 -080011964 @GuardedBy("this")
Sudheer Shankac57729a2018-02-09 15:44:42 -080011965 public void updateCpuTimeLocked(boolean onBattery, boolean onBatteryScreenOff) {
Adam Lesinski52290c9c2015-09-21 16:54:52 -070011966 if (mPowerProfile == null) {
11967 return;
11968 }
11969
Adam Lesinski72478f02015-06-17 15:39:43 -070011970 if (DEBUG_ENERGY_CPU) {
11971 Slog.d(TAG, "!Cpu updating!");
11972 }
11973
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011974 if (mCpuFreqs == null) {
11975 mCpuFreqs = mKernelUidCpuFreqTimeReader.readFreqs(mPowerProfile);
11976 }
11977
Sudheer Shanka38383232017-07-25 09:55:03 -070011978 // Calculate the wakelocks we have to distribute amongst. The system is excluded as it is
11979 // usually holding the wakelock on behalf of an app.
11980 // And Only distribute cpu power to wakelocks if the screen is off and we're on battery.
11981 ArrayList<StopwatchTimer> partialTimersToConsider = null;
Sudheer Shankac57729a2018-02-09 15:44:42 -080011982 if (onBatteryScreenOff) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011983 partialTimersToConsider = new ArrayList<>();
11984 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070011985 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070011986 // Since the collection and blaming of wakelocks can be scheduled to run after
11987 // some delay, the mPartialTimers list may have new entries. We can't blame
11988 // the newly added timer for past cpu time, so we only consider timers that
11989 // were present for one round of collection. Once a timer has gone through
11990 // a round of collection, its mInList field is set to true.
Adam Lesinski72478f02015-06-17 15:39:43 -070011991 if (timer.mInList && timer.mUid != null && timer.mUid.mUid != Process.SYSTEM_UID) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011992 partialTimersToConsider.add(timer);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011993 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011994 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011995 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011996 markPartialTimersAsEligible();
Adam Lesinski72478f02015-06-17 15:39:43 -070011997
Sudheer Shanka38383232017-07-25 09:55:03 -070011998 // When the battery is not on, we don't attribute the cpu times to any timers but we still
11999 // need to take the snapshots.
Sudheer Shankac57729a2018-02-09 15:44:42 -080012000 if (!onBattery) {
Sudheer Shanka38383232017-07-25 09:55:03 -070012001 mKernelUidCpuTimeReader.readDelta(null);
12002 mKernelUidCpuFreqTimeReader.readDelta(null);
Mike Ma234d1822018-03-13 18:53:21 -070012003 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080012004 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
12005 mKernelUidCpuActiveTimeReader.readDelta(null);
12006 mKernelUidCpuClusterTimeReader.readDelta(null);
Mike Ma234d1822018-03-13 18:53:21 -070012007 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080012008 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012009 for (int cluster = mKernelCpuSpeedReaders.length - 1; cluster >= 0; --cluster) {
12010 mKernelCpuSpeedReaders[cluster].readDelta();
12011 }
12012 return;
12013 }
Adam Lesinski72478f02015-06-17 15:39:43 -070012014
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070012015 mUserInfoProvider.refreshUserIds();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012016 final SparseLongArray updatedUids = mKernelUidCpuFreqTimeReader.perClusterTimesAvailable()
12017 ? null : new SparseLongArray();
Sudheer Shankac57729a2018-02-09 15:44:42 -080012018 readKernelUidCpuTimesLocked(partialTimersToConsider, updatedUids, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012019 // updatedUids=null means /proc/uid_time_in_state provides snapshots of per-cluster cpu
12020 // freqs, so no need to approximate these values.
12021 if (updatedUids != null) {
Sudheer Shankac57729a2018-02-09 15:44:42 -080012022 updateClusterSpeedTimes(updatedUids, onBattery);
Sudheer Shanka671985f2017-05-19 11:33:42 -070012023 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080012024 readKernelUidCpuFreqTimesLocked(partialTimersToConsider, onBattery, onBatteryScreenOff);
Mike Ma234d1822018-03-13 18:53:21 -070012025 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080012026 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
Sudheer Shankac57729a2018-02-09 15:44:42 -080012027 readKernelUidCpuActiveTimesLocked(onBattery);
12028 readKernelUidCpuClusterTimesLocked(onBattery);
Mike Ma234d1822018-03-13 18:53:21 -070012029 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080012030 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012031 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012032
Sudheer Shanka38383232017-07-25 09:55:03 -070012033 /**
12034 * Mark the current partial timers as gone through a collection so that they will be
12035 * considered in the next cpu times distribution to wakelock holders.
12036 */
12037 @VisibleForTesting
12038 public void markPartialTimersAsEligible() {
12039 if (ArrayUtils.referenceEquals(mPartialTimers, mLastPartialTimers)) {
12040 // No difference, so each timer is now considered for the next collection.
12041 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
12042 mPartialTimers.get(i).mInList = true;
12043 }
12044 } else {
12045 // The lists are different, meaning we added (or removed a timer) since the last
12046 // collection.
12047 for (int i = mLastPartialTimers.size() - 1; i >= 0; --i) {
12048 mLastPartialTimers.get(i).mInList = false;
12049 }
12050 mLastPartialTimers.clear();
Adam Lesinski72478f02015-06-17 15:39:43 -070012051
Sudheer Shanka38383232017-07-25 09:55:03 -070012052 // Mark the current timers as gone through a collection.
12053 final int numPartialTimers = mPartialTimers.size();
12054 for (int i = 0; i < numPartialTimers; ++i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070012055 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070012056 timer.mInList = true;
12057 mLastPartialTimers.add(timer);
Adam Lesinski72478f02015-06-17 15:39:43 -070012058 }
12059 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012060 }
Adam Lesinski72478f02015-06-17 15:39:43 -070012061
Sudheer Shanka38383232017-07-25 09:55:03 -070012062 /**
12063 * Take snapshot of cpu times (aggregated over all uids) at different frequencies and
12064 * calculate cpu times spent by each uid at different frequencies.
12065 *
12066 * @param updatedUids The uids for which times spent at different frequencies are calculated.
12067 */
12068 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012069 public void updateClusterSpeedTimes(@NonNull SparseLongArray updatedUids, boolean onBattery) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070012070 long totalCpuClustersTimeMs = 0;
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012071 // Read the time spent for each cluster at various cpu frequencies.
Sudheer Shankaaf857412017-07-21 00:14:24 -070012072 final long[][] clusterSpeedTimesMs = new long[mKernelCpuSpeedReaders.length][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012073 for (int cluster = 0; cluster < mKernelCpuSpeedReaders.length; cluster++) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070012074 clusterSpeedTimesMs[cluster] = mKernelCpuSpeedReaders[cluster].readDelta();
12075 if (clusterSpeedTimesMs[cluster] != null) {
12076 for (int speed = clusterSpeedTimesMs[cluster].length - 1; speed >= 0; --speed) {
12077 totalCpuClustersTimeMs += clusterSpeedTimesMs[cluster][speed];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012078 }
12079 }
12080 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070012081 if (totalCpuClustersTimeMs != 0) {
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012082 // We have cpu times per freq aggregated over all uids but we need the times per uid.
12083 // So, we distribute total time spent by an uid to different cpu freqs based on the
12084 // amount of time cpu was running at that freq.
12085 final int updatedUidsCount = updatedUids.size();
12086 for (int i = 0; i < updatedUidsCount; ++i) {
12087 final Uid u = getUidStatsLocked(updatedUids.keyAt(i));
Sudheer Shankaaf857412017-07-21 00:14:24 -070012088 final long appCpuTimeUs = updatedUids.valueAt(i);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012089 // Add the cpu speeds to this UID.
12090 final int numClusters = mPowerProfile.getNumCpuClusters();
Sudheer Shanka38383232017-07-25 09:55:03 -070012091 if (u.mCpuClusterSpeedTimesUs == null ||
12092 u.mCpuClusterSpeedTimesUs.length != numClusters) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070012093 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012094 }
12095
Sudheer Shankaaf857412017-07-21 00:14:24 -070012096 for (int cluster = 0; cluster < clusterSpeedTimesMs.length; cluster++) {
12097 final int speedsInCluster = clusterSpeedTimesMs[cluster].length;
12098 if (u.mCpuClusterSpeedTimesUs[cluster] == null || speedsInCluster !=
12099 u.mCpuClusterSpeedTimesUs[cluster].length) {
12100 u.mCpuClusterSpeedTimesUs[cluster]
12101 = new LongSamplingCounter[speedsInCluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012102 }
12103
Sudheer Shankaaf857412017-07-21 00:14:24 -070012104 final LongSamplingCounter[] cpuSpeeds = u.mCpuClusterSpeedTimesUs[cluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012105 for (int speed = 0; speed < speedsInCluster; speed++) {
12106 if (cpuSpeeds[speed] == null) {
12107 cpuSpeeds[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
12108 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070012109 cpuSpeeds[speed].addCountLocked(appCpuTimeUs
12110 * clusterSpeedTimesMs[cluster][speed]
Sudheer Shankac57729a2018-02-09 15:44:42 -080012111 / totalCpuClustersTimeMs, onBattery);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012112 }
12113 }
12114 }
12115 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012116 }
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012117
Sudheer Shanka38383232017-07-25 09:55:03 -070012118 /**
12119 * Take a snapshot of the cpu times spent by each uid and update the corresponding counters.
12120 * If {@param partialTimers} is not null and empty, then we assign a portion of cpu times to
12121 * wakelock holders.
12122 *
12123 * @param partialTimers The wakelock holders among which the cpu times will be distributed.
12124 * @param updatedUids If not null, then the uids found in the snapshot will be added to this.
12125 */
12126 @VisibleForTesting
12127 public void readKernelUidCpuTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers,
Sudheer Shankac57729a2018-02-09 15:44:42 -080012128 @Nullable SparseLongArray updatedUids, boolean onBattery) {
Sudheer Shanka38383232017-07-25 09:55:03 -070012129 mTempTotalCpuUserTimeUs = mTempTotalCpuSystemTimeUs = 0;
12130 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
12131 final long startTimeMs = mClocks.uptimeMillis();
Adam Lesinski72478f02015-06-17 15:39:43 -070012132
Sudheer Shanka38383232017-07-25 09:55:03 -070012133 mKernelUidCpuTimeReader.readDelta((uid, userTimeUs, systemTimeUs) -> {
12134 uid = mapUid(uid);
12135 if (Process.isIsolated(uid)) {
12136 // This could happen if the isolated uid mapping was removed before that process
12137 // was actually killed.
12138 mKernelUidCpuTimeReader.removeUid(uid);
12139 Slog.d(TAG, "Got readings for an isolated uid with no mapping: " + uid);
12140 return;
12141 }
12142 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12143 Slog.d(TAG, "Got readings for an invalid user's uid " + uid);
12144 mKernelUidCpuTimeReader.removeUid(uid);
12145 return;
12146 }
12147 final Uid u = getUidStatsLocked(uid);
12148
12149 // Accumulate the total system and user time.
12150 mTempTotalCpuUserTimeUs += userTimeUs;
12151 mTempTotalCpuSystemTimeUs += systemTimeUs;
12152
12153 StringBuilder sb = null;
12154 if (DEBUG_ENERGY_CPU) {
12155 sb = new StringBuilder();
12156 sb.append(" got time for uid=").append(u.mUid).append(": u=");
12157 TimeUtils.formatDuration(userTimeUs / 1000, sb);
12158 sb.append(" s=");
12159 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
12160 sb.append("\n");
12161 }
12162
12163 if (numWakelocks > 0) {
12164 // We have wakelocks being held, so only give a portion of the
12165 // time to the process. The rest will be distributed among wakelock
12166 // holders.
12167 userTimeUs = (userTimeUs * WAKE_LOCK_WEIGHT) / 100;
12168 systemTimeUs = (systemTimeUs * WAKE_LOCK_WEIGHT) / 100;
12169 }
12170
12171 if (sb != null) {
12172 sb.append(" adding to uid=").append(u.mUid).append(": u=");
12173 TimeUtils.formatDuration(userTimeUs / 1000, sb);
12174 sb.append(" s=");
12175 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
12176 Slog.d(TAG, sb.toString());
12177 }
12178
Sudheer Shankac57729a2018-02-09 15:44:42 -080012179 u.mUserCpuTime.addCountLocked(userTimeUs, onBattery);
12180 u.mSystemCpuTime.addCountLocked(systemTimeUs, onBattery);
Sudheer Shanka38383232017-07-25 09:55:03 -070012181 if (updatedUids != null) {
12182 updatedUids.put(u.getUid(), userTimeUs + systemTimeUs);
12183 }
12184 });
12185
12186 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12187 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12188 Slog.d(TAG, "Reading cpu stats took " + elapsedTimeMs + "ms");
12189 }
12190
12191 if (numWakelocks > 0) {
12192 // Distribute a portion of the total cpu time to wakelock holders.
12193 mTempTotalCpuUserTimeUs = (mTempTotalCpuUserTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
12194 mTempTotalCpuSystemTimeUs =
12195 (mTempTotalCpuSystemTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
12196
12197 for (int i = 0; i < numWakelocks; ++i) {
12198 final StopwatchTimer timer = partialTimers.get(i);
12199 final int userTimeUs = (int) (mTempTotalCpuUserTimeUs / (numWakelocks - i));
12200 final int systemTimeUs = (int) (mTempTotalCpuSystemTimeUs / (numWakelocks - i));
12201
12202 if (DEBUG_ENERGY_CPU) {
12203 final StringBuilder sb = new StringBuilder();
12204 sb.append(" Distributing wakelock uid=").append(timer.mUid.mUid)
12205 .append(": u=");
12206 TimeUtils.formatDuration(userTimeUs / 1000, sb);
12207 sb.append(" s=");
12208 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
12209 Slog.d(TAG, sb.toString());
12210 }
12211
Sudheer Shankac57729a2018-02-09 15:44:42 -080012212 timer.mUid.mUserCpuTime.addCountLocked(userTimeUs, onBattery);
12213 timer.mUid.mSystemCpuTime.addCountLocked(systemTimeUs, onBattery);
Sudheer Shanka38383232017-07-25 09:55:03 -070012214 if (updatedUids != null) {
12215 final int uid = timer.mUid.getUid();
12216 updatedUids.put(uid, updatedUids.get(uid, 0) + userTimeUs + systemTimeUs);
12217 }
12218
12219 final Uid.Proc proc = timer.mUid.getProcessStatsLocked("*wakelock*");
Sudheer Shankac57729a2018-02-09 15:44:42 -080012220 proc.addCpuTimeLocked(userTimeUs / 1000, systemTimeUs / 1000, onBattery);
Sudheer Shanka38383232017-07-25 09:55:03 -070012221
12222 mTempTotalCpuUserTimeUs -= userTimeUs;
12223 mTempTotalCpuSystemTimeUs -= systemTimeUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070012224 }
12225 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070012226 }
12227
Sudheer Shanka38383232017-07-25 09:55:03 -070012228 /**
12229 * Take a snapshot of the cpu times spent by each uid in each freq and update the
12230 * corresponding counters.
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012231 *
12232 * @param partialTimers The wakelock holders among which the cpu freq times will be distributed.
Sudheer Shanka38383232017-07-25 09:55:03 -070012233 */
12234 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012235 public void readKernelUidCpuFreqTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers,
12236 boolean onBattery, boolean onBatteryScreenOff) {
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012237 final boolean perClusterTimesAvailable =
12238 mKernelUidCpuFreqTimeReader.perClusterTimesAvailable();
12239 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
12240 final int numClusters = mPowerProfile.getNumCpuClusters();
12241 mWakeLockAllocationsUs = null;
Sudheer Shankaac5b88f2017-12-11 15:36:35 -080012242 final long startTimeMs = mClocks.uptimeMillis();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012243 mKernelUidCpuFreqTimeReader.readDelta((uid, cpuFreqTimeMs) -> {
12244 uid = mapUid(uid);
12245 if (Process.isIsolated(uid)) {
12246 mKernelUidCpuFreqTimeReader.removeUid(uid);
12247 Slog.d(TAG, "Got freq readings for an isolated uid with no mapping: " + uid);
12248 return;
Sudheer Shanka38383232017-07-25 09:55:03 -070012249 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012250 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12251 Slog.d(TAG, "Got freq readings for an invalid user's uid " + uid);
12252 mKernelUidCpuFreqTimeReader.removeUid(uid);
12253 return;
12254 }
12255 final Uid u = getUidStatsLocked(uid);
12256 if (u.mCpuFreqTimeMs == null || u.mCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
12257 u.mCpuFreqTimeMs = new LongSamplingCounterArray(mOnBatteryTimeBase);
12258 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080012259 u.mCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012260 if (u.mScreenOffCpuFreqTimeMs == null ||
12261 u.mScreenOffCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
12262 u.mScreenOffCpuFreqTimeMs = new LongSamplingCounterArray(
12263 mOnBatteryScreenOffTimeBase);
12264 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080012265 u.mScreenOffCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs, onBatteryScreenOff);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012266
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012267 if (perClusterTimesAvailable) {
12268 if (u.mCpuClusterSpeedTimesUs == null ||
12269 u.mCpuClusterSpeedTimesUs.length != numClusters) {
12270 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070012271 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012272 if (numWakelocks > 0 && mWakeLockAllocationsUs == null) {
12273 mWakeLockAllocationsUs = new long[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070012274 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012275
12276 int freqIndex = 0;
12277 for (int cluster = 0; cluster < numClusters; ++cluster) {
12278 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
12279 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
12280 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
12281 u.mCpuClusterSpeedTimesUs[cluster]
12282 = new LongSamplingCounter[speedsInCluster];
12283 }
12284 if (numWakelocks > 0 && mWakeLockAllocationsUs[cluster] == null) {
12285 mWakeLockAllocationsUs[cluster] = new long[speedsInCluster];
12286 }
12287 final LongSamplingCounter[] cpuTimesUs = u.mCpuClusterSpeedTimesUs[cluster];
12288 for (int speed = 0; speed < speedsInCluster; ++speed) {
12289 if (cpuTimesUs[speed] == null) {
12290 cpuTimesUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
12291 }
12292 final long appAllocationUs;
12293 if (mWakeLockAllocationsUs != null) {
12294 appAllocationUs =
12295 (cpuFreqTimeMs[freqIndex] * 1000 * WAKE_LOCK_WEIGHT) / 100;
12296 mWakeLockAllocationsUs[cluster][speed] +=
12297 (cpuFreqTimeMs[freqIndex] * 1000 - appAllocationUs);
12298 } else {
12299 appAllocationUs = cpuFreqTimeMs[freqIndex] * 1000;
12300 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080012301 cpuTimesUs[speed].addCountLocked(appAllocationUs, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012302 freqIndex++;
12303 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012304 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012305 }
12306 });
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012307
Sudheer Shankaac5b88f2017-12-11 15:36:35 -080012308 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12309 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12310 Slog.d(TAG, "Reading cpu freq times took " + elapsedTimeMs + "ms");
12311 }
12312
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012313 if (mWakeLockAllocationsUs != null) {
12314 for (int i = 0; i < numWakelocks; ++i) {
12315 final Uid u = partialTimers.get(i).mUid;
12316 if (u.mCpuClusterSpeedTimesUs == null ||
12317 u.mCpuClusterSpeedTimesUs.length != numClusters) {
12318 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
12319 }
12320
12321 for (int cluster = 0; cluster < numClusters; ++cluster) {
12322 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
12323 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
12324 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
12325 u.mCpuClusterSpeedTimesUs[cluster]
12326 = new LongSamplingCounter[speedsInCluster];
12327 }
12328 final LongSamplingCounter[] cpuTimeUs = u.mCpuClusterSpeedTimesUs[cluster];
12329 for (int speed = 0; speed < speedsInCluster; ++speed) {
12330 if (cpuTimeUs[speed] == null) {
12331 cpuTimeUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
12332 }
12333 final long allocationUs =
12334 mWakeLockAllocationsUs[cluster][speed] / (numWakelocks - i);
Sudheer Shankac57729a2018-02-09 15:44:42 -080012335 cpuTimeUs[speed].addCountLocked(allocationUs, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012336 mWakeLockAllocationsUs[cluster][speed] -= allocationUs;
12337 }
12338 }
12339 }
12340 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012341 }
12342
Mike Ma3d422c32017-10-25 11:08:57 -070012343 /**
12344 * Take a snapshot of the cpu active times spent by each uid and update the corresponding
12345 * counters.
12346 */
12347 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012348 public void readKernelUidCpuActiveTimesLocked(boolean onBattery) {
Mike Ma3d422c32017-10-25 11:08:57 -070012349 final long startTimeMs = mClocks.uptimeMillis();
Mike Ma2ab01442018-02-13 14:22:47 -080012350 mKernelUidCpuActiveTimeReader.readDelta((uid, cpuActiveTimesMs) -> {
Mike Ma3d422c32017-10-25 11:08:57 -070012351 uid = mapUid(uid);
12352 if (Process.isIsolated(uid)) {
12353 mKernelUidCpuActiveTimeReader.removeUid(uid);
12354 Slog.w(TAG, "Got active times for an isolated uid with no mapping: " + uid);
12355 return;
12356 }
12357 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12358 Slog.w(TAG, "Got active times for an invalid user's uid " + uid);
12359 mKernelUidCpuActiveTimeReader.removeUid(uid);
12360 return;
12361 }
12362 final Uid u = getUidStatsLocked(uid);
Mike Ma2ab01442018-02-13 14:22:47 -080012363 u.mCpuActiveTimeMs.addCountLocked(cpuActiveTimesMs, onBattery);
Mike Ma3d422c32017-10-25 11:08:57 -070012364 });
12365
12366 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12367 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12368 Slog.d(TAG, "Reading cpu active times took " + elapsedTimeMs + "ms");
12369 }
12370 }
12371
12372 /**
12373 * Take a snapshot of the cpu cluster times spent by each uid and update the corresponding
12374 * counters.
12375 */
12376 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012377 public void readKernelUidCpuClusterTimesLocked(boolean onBattery) {
Mike Ma3d422c32017-10-25 11:08:57 -070012378 final long startTimeMs = mClocks.uptimeMillis();
Mike Ma2ab01442018-02-13 14:22:47 -080012379 mKernelUidCpuClusterTimeReader.readDelta((uid, cpuClusterTimesMs) -> {
Mike Ma3d422c32017-10-25 11:08:57 -070012380 uid = mapUid(uid);
12381 if (Process.isIsolated(uid)) {
12382 mKernelUidCpuClusterTimeReader.removeUid(uid);
12383 Slog.w(TAG, "Got cluster times for an isolated uid with no mapping: " + uid);
12384 return;
12385 }
12386 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12387 Slog.w(TAG, "Got cluster times for an invalid user's uid " + uid);
12388 mKernelUidCpuClusterTimeReader.removeUid(uid);
12389 return;
12390 }
12391 final Uid u = getUidStatsLocked(uid);
Mike Ma2ab01442018-02-13 14:22:47 -080012392 u.mCpuClusterTimesMs.addCountLocked(cpuClusterTimesMs, onBattery);
Mike Ma3d422c32017-10-25 11:08:57 -070012393 });
12394
12395 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12396 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12397 Slog.d(TAG, "Reading cpu cluster times took " + elapsedTimeMs + "ms");
12398 }
12399 }
12400
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012401 boolean setChargingLocked(boolean charging) {
12402 if (mCharging != charging) {
12403 mCharging = charging;
12404 if (charging) {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012405 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012406 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012407 mHistoryCur.states2 &= ~HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012408 }
12409 mHandler.sendEmptyMessage(MSG_REPORT_CHARGING);
12410 return true;
12411 }
12412 return false;
12413 }
12414
Andreas Gampe3f24e692018-02-05 13:24:28 -080012415 @GuardedBy("this")
Mike Mac2f518a2017-09-19 16:06:03 -070012416 protected void setOnBatteryLocked(final long mSecRealtime, final long mSecUptime,
12417 final boolean onBattery, final int oldStatus, final int level, final int chargeUAh) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012418 boolean doWrite = false;
12419 Message m = mHandler.obtainMessage(MSG_REPORT_POWER_CHANGE);
12420 m.arg1 = onBattery ? 1 : 0;
12421 mHandler.sendMessage(m);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012422
Dianne Hackborn40c87252014-03-19 16:55:40 -070012423 final long uptime = mSecUptime * 1000;
12424 final long realtime = mSecRealtime * 1000;
Mike Mac2f518a2017-09-19 16:06:03 -070012425 final int screenState = mScreenState;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012426 if (onBattery) {
12427 // We will reset our status if we are unplugging after the
12428 // battery was last full, or the level is at 100, or
12429 // we have gone through a significant charge (from a very low
12430 // level to a now very high level).
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080012431 boolean reset = false;
Dianne Hackborn9a755432014-05-15 17:05:22 -070012432 if (!mNoAutoReset && (oldStatus == BatteryManager.BATTERY_STATUS_FULL
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012433 || level >= 90
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070012434 || (mDischargeCurrentLevel < 20 && level >= 80)
12435 || (getHighDischargeAmountSinceCharge() >= 200
12436 && mHistoryBuffer.dataSize() >= MAX_HISTORY_BUFFER))) {
Dianne Hackborn73d6a822014-09-29 10:52:47 -070012437 Slog.i(TAG, "Resetting battery stats: level=" + level + " status=" + oldStatus
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070012438 + " dischargeLevel=" + mDischargeCurrentLevel
Dianne Hackborn73d6a822014-09-29 10:52:47 -070012439 + " lowAmount=" + getLowDischargeAmountSinceCharge()
12440 + " highAmount=" + getHighDischargeAmountSinceCharge());
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012441 // Before we write, collect a snapshot of the final aggregated
12442 // stats to be reported in the next checkin. Only do this if we have
12443 // a sufficient amount of data to make it interesting.
12444 if (getLowDischargeAmountSinceCharge() >= 20) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080012445 final long startTime = SystemClock.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012446 final Parcel parcel = Parcel.obtain();
12447 writeSummaryToParcel(parcel, true);
Dianne Hackborne17b4452018-01-10 13:15:40 -080012448 final long initialTime = SystemClock.uptimeMillis() - startTime;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012449 BackgroundThread.getHandler().post(new Runnable() {
12450 @Override public void run() {
12451 synchronized (mCheckinFile) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080012452 final long startTime2 = SystemClock.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012453 FileOutputStream stream = null;
12454 try {
12455 stream = mCheckinFile.startWrite();
12456 stream.write(parcel.marshall());
12457 stream.flush();
12458 FileUtils.sync(stream);
12459 stream.close();
12460 mCheckinFile.finishWrite(stream);
Dianne Hackborne17b4452018-01-10 13:15:40 -080012461 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
12462 "batterystats-checkin",
12463 initialTime + SystemClock.uptimeMillis() - startTime2);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012464 } catch (IOException e) {
12465 Slog.w("BatteryStats",
12466 "Error writing checkin battery statistics", e);
12467 mCheckinFile.failWrite(stream);
12468 } finally {
12469 parcel.recycle();
12470 }
12471 }
12472 }
12473 });
12474 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012475 doWrite = true;
12476 resetAllStatsLocked();
Ying Wai (Daniel) Fan442ab762017-01-31 22:00:10 -080012477 if (chargeUAh > 0 && level > 0) {
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012478 // Only use the reported coulomb charge value if it is supported and reported.
Ying Wai (Daniel) Fan9238b612017-01-18 15:50:19 -080012479 mEstimatedBatteryCapacity = (int) ((chargeUAh / 1000) / (level / 100.0));
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012480 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012481 mDischargeStartLevel = level;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080012482 reset = true;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012483 mDischargeStepTracker.init();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012484 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012485 if (mCharging) {
12486 setChargingLocked(false);
12487 }
12488 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080012489 mOnBattery = mOnBatteryInternal = true;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012490 mLastDischargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070012491 mMinDischargeStepLevel = level;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012492 mDischargeStepTracker.clearTime();
12493 mDailyDischargeStepTracker.clearTime();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012494 mInitStepMode = mCurStepMode;
12495 mModStepMode = 0;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012496 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012497 mHistoryCur.batteryLevel = (byte)level;
12498 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
12499 if (DEBUG_HISTORY) Slog.v(TAG, "Battery unplugged to: "
12500 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012501 if (reset) {
12502 mRecordingHistory = true;
12503 startRecordingHistory(mSecRealtime, mSecUptime, reset);
12504 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070012505 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012506 mDischargeCurrentLevel = mDischargeUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070012507 if (isScreenOn(screenState)) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012508 mDischargeScreenOnUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070012509 mDischargeScreenDozeUnplugLevel = 0;
12510 mDischargeScreenOffUnplugLevel = 0;
12511 } else if (isScreenDoze(screenState)) {
12512 mDischargeScreenOnUnplugLevel = 0;
12513 mDischargeScreenDozeUnplugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012514 mDischargeScreenOffUnplugLevel = 0;
12515 } else {
12516 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012517 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012518 mDischargeScreenOffUnplugLevel = level;
12519 }
12520 mDischargeAmountScreenOn = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012521 mDischargeAmountScreenDoze = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012522 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012523 updateTimeBasesLocked(true, screenState, uptime, realtime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012524 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012525 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080012526 mOnBattery = mOnBatteryInternal = false;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012527 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012528 mHistoryCur.batteryLevel = (byte)level;
12529 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
12530 if (DEBUG_HISTORY) Slog.v(TAG, "Battery plugged to: "
12531 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -070012532 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012533 mDischargeCurrentLevel = mDischargePlugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012534 if (level < mDischargeUnplugLevel) {
12535 mLowDischargeAmountSinceCharge += mDischargeUnplugLevel-level-1;
12536 mHighDischargeAmountSinceCharge += mDischargeUnplugLevel-level;
12537 }
Mike Mac2f518a2017-09-19 16:06:03 -070012538 updateDischargeScreenLevelsLocked(screenState, screenState);
12539 updateTimeBasesLocked(false, screenState, uptime, realtime);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012540 mChargeStepTracker.init();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012541 mLastChargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070012542 mMaxChargeStepLevel = level;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012543 mInitStepMode = mCurStepMode;
12544 mModStepMode = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012545 }
12546 if (doWrite || (mLastWriteTime + (60 * 1000)) < mSecRealtime) {
12547 if (mFile != null) {
12548 writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012549 }
12550 }
12551 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012552
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012553 private void startRecordingHistory(final long elapsedRealtimeMs, final long uptimeMs,
12554 boolean reset) {
12555 mRecordingHistory = true;
12556 mHistoryCur.currentTime = System.currentTimeMillis();
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012557 addHistoryBufferLocked(elapsedRealtimeMs,
Dianne Hackborn37de0982014-05-09 09:32:18 -070012558 reset ? HistoryItem.CMD_RESET : HistoryItem.CMD_CURRENT_TIME,
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012559 mHistoryCur);
12560 mHistoryCur.currentTime = 0;
12561 if (reset) {
12562 initActiveHistoryEventsLocked(elapsedRealtimeMs, uptimeMs);
12563 }
12564 }
12565
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012566 private void recordCurrentTimeChangeLocked(final long currentTime, final long elapsedRealtimeMs,
12567 final long uptimeMs) {
12568 if (mRecordingHistory) {
12569 mHistoryCur.currentTime = currentTime;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012570 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_CURRENT_TIME, mHistoryCur);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012571 mHistoryCur.currentTime = 0;
12572 }
12573 }
12574
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080012575 private void recordShutdownLocked(final long elapsedRealtimeMs, final long uptimeMs) {
12576 if (mRecordingHistory) {
12577 mHistoryCur.currentTime = System.currentTimeMillis();
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012578 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_SHUTDOWN, mHistoryCur);
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080012579 mHistoryCur.currentTime = 0;
12580 }
12581 }
12582
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012583 private void scheduleSyncExternalStatsLocked(String reason, int updateFlags) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012584 if (mExternalSync != null) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012585 mExternalSync.scheduleSync(reason, updateFlags);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070012586 }
12587 }
12588
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012589 // This should probably be exposed in the API, though it's not critical
Bookatz1a1b0462018-01-12 11:47:03 -080012590 public static final int BATTERY_PLUGGED_NONE = OsProtoEnums.BATTERY_PLUGGED_NONE; // = 0
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012591
Andreas Gampe3f24e692018-02-05 13:24:28 -080012592 @GuardedBy("this")
Bookatz8c6571b2017-10-24 15:04:41 -070012593 public void setBatteryStateLocked(final int status, final int health, final int plugType,
12594 final int level, /* not final */ int temp, final int volt, final int chargeUAh,
12595 final int chargeFullUAh) {
Adam Lesinski29ddfe52017-03-29 19:29:00 -070012596 // Temperature is encoded without the signed bit, so clamp any negative temperatures to 0.
12597 temp = Math.max(0, temp);
12598
Bookatz8c6571b2017-10-24 15:04:41 -070012599 reportChangesToStatsLog(mHaveBatteryLevel ? mHistoryCur : null,
Tej Singh40298312018-02-16 00:15:09 -080012600 status, plugType, level);
Bookatz8c6571b2017-10-24 15:04:41 -070012601
Sudheer Shankac57729a2018-02-09 15:44:42 -080012602 final boolean onBattery = isOnBattery(plugType, status);
Joe Onoratoabded112016-02-08 16:49:39 -080012603 final long uptime = mClocks.uptimeMillis();
12604 final long elapsedRealtime = mClocks.elapsedRealtime();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012605 if (!mHaveBatteryLevel) {
12606 mHaveBatteryLevel = true;
12607 // We start out assuming that the device is plugged in (not
12608 // on battery). If our first report is now that we are indeed
12609 // plugged in, then twiddle our state to correctly reflect that
12610 // since we won't be going through the full setOnBattery().
12611 if (onBattery == mOnBattery) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012612 if (onBattery) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012613 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012614 } else {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012615 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012616 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012617 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012618 // Always start out assuming charging, that will be updated later.
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012619 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012620 mHistoryCur.batteryStatus = (byte)status;
12621 mHistoryCur.batteryLevel = (byte)level;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012622 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012623 mMaxChargeStepLevel = mMinDischargeStepLevel =
12624 mLastChargeStepLevel = mLastDischargeStepLevel = level;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012625 mLastChargingStateLevel = level;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012626 } else if (mCurrentBatteryLevel != level || mOnBattery != onBattery) {
12627 recordDailyStatsIfNeededLocked(level >= 100 && onBattery);
12628 }
12629 int oldStatus = mHistoryCur.batteryStatus;
12630 if (onBattery) {
12631 mDischargeCurrentLevel = level;
12632 if (!mRecordingHistory) {
12633 mRecordingHistory = true;
12634 startRecordingHistory(elapsedRealtime, uptime, true);
12635 }
Todd Poynor1acf06a2017-12-07 19:19:35 -080012636 } else if (level < 96 &&
12637 status != BatteryManager.BATTERY_STATUS_UNKNOWN) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012638 if (!mRecordingHistory) {
12639 mRecordingHistory = true;
12640 startRecordingHistory(elapsedRealtime, uptime, true);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012641 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070012642 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012643 mCurrentBatteryLevel = level;
12644 if (mDischargePlugLevel < 0) {
12645 mDischargePlugLevel = level;
Marco Nelissend8593312009-04-30 14:45:06 -070012646 }
Adam Lesinski926969b2016-04-28 17:31:12 -070012647
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012648 if (onBattery != mOnBattery) {
12649 mHistoryCur.batteryLevel = (byte)level;
12650 mHistoryCur.batteryStatus = (byte)status;
12651 mHistoryCur.batteryHealth = (byte)health;
12652 mHistoryCur.batteryPlugType = (byte)plugType;
12653 mHistoryCur.batteryTemperature = (short)temp;
12654 mHistoryCur.batteryVoltage = (char)volt;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012655 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
12656 // Only record discharges
12657 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
12658 mDischargeCounter.addCountLocked(chargeDiff);
12659 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070012660 if (isScreenDoze(mScreenState)) {
12661 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
12662 }
Mike Ma15313c92017-11-15 17:58:21 -080012663 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
12664 mDischargeLightDozeCounter.addCountLocked(chargeDiff);
12665 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
12666 mDischargeDeepDozeCounter.addCountLocked(chargeDiff);
12667 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012668 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012669 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012670 setOnBatteryLocked(elapsedRealtime, uptime, onBattery, oldStatus, level, chargeUAh);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012671 } else {
12672 boolean changed = false;
12673 if (mHistoryCur.batteryLevel != level) {
12674 mHistoryCur.batteryLevel = (byte)level;
12675 changed = true;
Marco Nelissend8593312009-04-30 14:45:06 -070012676
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012677 // TODO(adamlesinski): Schedule the creation of a HistoryStepDetails record
12678 // which will pull external stats.
Sudheer Shanka0719c6a2018-04-24 11:12:11 -070012679 mExternalSync.scheduleSyncDueToBatteryLevelChange(
12680 mConstants.BATTERY_LEVEL_COLLECTION_DELAY_MS);
Evan Millarc64edde2009-04-18 12:26:32 -070012681 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012682 if (mHistoryCur.batteryStatus != status) {
12683 mHistoryCur.batteryStatus = (byte)status;
12684 changed = true;
12685 }
12686 if (mHistoryCur.batteryHealth != health) {
12687 mHistoryCur.batteryHealth = (byte)health;
12688 changed = true;
12689 }
12690 if (mHistoryCur.batteryPlugType != plugType) {
12691 mHistoryCur.batteryPlugType = (byte)plugType;
12692 changed = true;
12693 }
12694 if (temp >= (mHistoryCur.batteryTemperature+10)
12695 || temp <= (mHistoryCur.batteryTemperature-10)) {
12696 mHistoryCur.batteryTemperature = (short)temp;
12697 changed = true;
12698 }
12699 if (volt > (mHistoryCur.batteryVoltage+20)
12700 || volt < (mHistoryCur.batteryVoltage-20)) {
12701 mHistoryCur.batteryVoltage = (char)volt;
12702 changed = true;
12703 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012704 if (chargeUAh >= (mHistoryCur.batteryChargeUAh+10)
12705 || chargeUAh <= (mHistoryCur.batteryChargeUAh-10)) {
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012706 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
12707 // Only record discharges
12708 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
12709 mDischargeCounter.addCountLocked(chargeDiff);
12710 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070012711 if (isScreenDoze(mScreenState)) {
12712 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
12713 }
Mike Ma15313c92017-11-15 17:58:21 -080012714 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
12715 mDischargeLightDozeCounter.addCountLocked(chargeDiff);
12716 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
12717 mDischargeDeepDozeCounter.addCountLocked(chargeDiff);
12718 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012719 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012720 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski926969b2016-04-28 17:31:12 -070012721 changed = true;
12722 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012723 long modeBits = (((long)mInitStepMode) << STEP_LEVEL_INITIAL_MODE_SHIFT)
12724 | (((long)mModStepMode) << STEP_LEVEL_MODIFIED_MODE_SHIFT)
12725 | (((long)(level&0xff)) << STEP_LEVEL_LEVEL_SHIFT);
12726 if (onBattery) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012727 changed |= setChargingLocked(false);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012728 if (mLastDischargeStepLevel != level && mMinDischargeStepLevel > level) {
12729 mDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
12730 modeBits, elapsedRealtime);
12731 mDailyDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
12732 modeBits, elapsedRealtime);
12733 mLastDischargeStepLevel = level;
12734 mMinDischargeStepLevel = level;
12735 mInitStepMode = mCurStepMode;
12736 mModStepMode = 0;
12737 }
12738 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012739 if (level >= 90) {
12740 // If the battery level is at least 90%, always consider the device to be
12741 // charging even if it happens to go down a level.
12742 changed |= setChargingLocked(true);
12743 mLastChargeStepLevel = level;
12744 } if (!mCharging) {
12745 if (mLastChargeStepLevel < level) {
12746 // We have not reporting that we are charging, but the level has now
12747 // gone up, so consider the state to be charging.
12748 changed |= setChargingLocked(true);
12749 mLastChargeStepLevel = level;
12750 }
12751 } else {
12752 if (mLastChargeStepLevel > level) {
12753 // We had reported that the device was charging, but here we are with
12754 // power connected and the level going down. Looks like the current
12755 // power supplied isn't enough, so consider the device to now be
12756 // discharging.
12757 changed |= setChargingLocked(false);
12758 mLastChargeStepLevel = level;
12759 }
12760 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012761 if (mLastChargeStepLevel != level && mMaxChargeStepLevel < level) {
12762 mChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
12763 modeBits, elapsedRealtime);
12764 mDailyChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
12765 modeBits, elapsedRealtime);
12766 mLastChargeStepLevel = level;
12767 mMaxChargeStepLevel = level;
12768 mInitStepMode = mCurStepMode;
12769 mModStepMode = 0;
Evan Millarc64edde2009-04-18 12:26:32 -070012770 }
12771 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012772 if (changed) {
12773 addHistoryRecordLocked(elapsedRealtime, uptime);
12774 }
Evan Millarc64edde2009-04-18 12:26:32 -070012775 }
Todd Poynor1acf06a2017-12-07 19:19:35 -080012776 if (!onBattery &&
12777 (status == BatteryManager.BATTERY_STATUS_FULL ||
12778 status == BatteryManager.BATTERY_STATUS_UNKNOWN)) {
12779 // We don't record history while we are plugged in and fully charged
12780 // (or when battery is not present). The next time we are
12781 // unplugged, history will be cleared.
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012782 mRecordingHistory = DEBUG;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080012783 }
Adam Lesinski041d9172016-12-12 12:03:56 -080012784
Jocelyn Dangc627d102017-04-14 13:15:14 -070012785 if (mMinLearnedBatteryCapacity == -1) {
12786 mMinLearnedBatteryCapacity = chargeFullUAh;
12787 } else {
12788 Math.min(mMinLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski041d9172016-12-12 12:03:56 -080012789 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070012790 mMaxLearnedBatteryCapacity = Math.max(mMaxLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski33dac552015-03-09 15:24:48 -070012791 }
12792
Sudheer Shankac57729a2018-02-09 15:44:42 -080012793 public static boolean isOnBattery(int plugType, int status) {
12794 return plugType == BATTERY_PLUGGED_NONE && status != BatteryManager.BATTERY_STATUS_UNKNOWN;
12795 }
12796
Bookatz8c6571b2017-10-24 15:04:41 -070012797 // Inform StatsLog of setBatteryState changes.
12798 // If this is the first reporting, pass in recentPast == null.
12799 private void reportChangesToStatsLog(HistoryItem recentPast,
Tej Singh40298312018-02-16 00:15:09 -080012800 final int status, final int plugType, final int level) {
Bookatz8c6571b2017-10-24 15:04:41 -070012801
12802 if (recentPast == null || recentPast.batteryStatus != status) {
12803 StatsLog.write(StatsLog.CHARGING_STATE_CHANGED, status);
12804 }
12805 if (recentPast == null || recentPast.batteryPlugType != plugType) {
12806 StatsLog.write(StatsLog.PLUGGED_STATE_CHANGED, plugType);
12807 }
12808 if (recentPast == null || recentPast.batteryLevel != level) {
12809 StatsLog.write(StatsLog.BATTERY_LEVEL_CHANGED, level);
12810 }
Bookatz8c6571b2017-10-24 15:04:41 -070012811 }
12812
Mathew Inwoodc185f082018-08-20 14:28:54 +010012813 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012814 public long getAwakeTimeBattery() {
12815 return computeBatteryUptime(getBatteryUptimeLocked(), STATS_CURRENT);
12816 }
12817
Mathew Inwoodc185f082018-08-20 14:28:54 +010012818 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012819 public long getAwakeTimePlugged() {
Joe Onoratoabded112016-02-08 16:49:39 -080012820 return (mClocks.uptimeMillis() * 1000) - getAwakeTimeBattery();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012821 }
12822
12823 @Override
12824 public long computeUptime(long curTime, int which) {
12825 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012826 case STATS_SINCE_CHARGED: return mUptime + (curTime-mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012827 case STATS_CURRENT: return (curTime-mUptimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070012828 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getUptimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012829 }
12830 return 0;
12831 }
12832
12833 @Override
12834 public long computeRealtime(long curTime, int which) {
12835 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012836 case STATS_SINCE_CHARGED: return mRealtime + (curTime-mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012837 case STATS_CURRENT: return (curTime-mRealtimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070012838 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getRealtimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012839 }
12840 return 0;
12841 }
12842
12843 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +010012844 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012845 public long computeBatteryUptime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012846 return mOnBatteryTimeBase.computeUptime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012847 }
12848
12849 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +010012850 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012851 public long computeBatteryRealtime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012852 return mOnBatteryTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012853 }
12854
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012855 @Override
12856 public long computeBatteryScreenOffUptime(long curTime, int which) {
12857 return mOnBatteryScreenOffTimeBase.computeUptime(curTime, which);
12858 }
12859
12860 @Override
12861 public long computeBatteryScreenOffRealtime(long curTime, int which) {
12862 return mOnBatteryScreenOffTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012863 }
12864
Dianne Hackborn260c5022014-04-29 11:23:16 -070012865 private long computeTimePerLevel(long[] steps, int numSteps) {
12866 // For now we'll do a simple average across all steps.
12867 if (numSteps <= 0) {
12868 return -1;
12869 }
12870 long total = 0;
12871 for (int i=0; i<numSteps; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012872 total += steps[i] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012873 }
12874 return total / numSteps;
12875 /*
12876 long[] buckets = new long[numSteps];
12877 int numBuckets = 0;
12878 int numToAverage = 4;
12879 int i = 0;
12880 while (i < numSteps) {
12881 long totalTime = 0;
12882 int num = 0;
12883 for (int j=0; j<numToAverage && (i+j)<numSteps; j++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012884 totalTime += steps[i+j] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012885 num++;
12886 }
12887 buckets[numBuckets] = totalTime / num;
12888 numBuckets++;
12889 numToAverage *= 2;
12890 i += num;
12891 }
12892 if (numBuckets < 1) {
12893 return -1;
12894 }
12895 long averageTime = buckets[numBuckets-1];
12896 for (i=numBuckets-2; i>=0; i--) {
12897 averageTime = (averageTime + buckets[i]) / 2;
12898 }
12899 return averageTime;
12900 */
12901 }
12902
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012903 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +010012904 @UnsupportedAppUsage
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012905 public long computeBatteryTimeRemaining(long curTime) {
12906 if (!mOnBattery) {
12907 return -1;
12908 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070012909 /* Simple implementation just looks at the average discharge per level across the
12910 entire sample period.
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012911 int discharge = (getLowDischargeAmountSinceCharge()+getHighDischargeAmountSinceCharge())/2;
12912 if (discharge < 2) {
12913 return -1;
12914 }
12915 long duration = computeBatteryRealtime(curTime, STATS_SINCE_CHARGED);
12916 if (duration < 1000*1000) {
12917 return -1;
12918 }
12919 long usPerLevel = duration/discharge;
12920 return usPerLevel * mCurrentBatteryLevel;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012921 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012922 if (mDischargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012923 return -1;
12924 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012925 long msPerLevel = mDischargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012926 if (msPerLevel <= 0) {
12927 return -1;
12928 }
12929 return (msPerLevel * mCurrentBatteryLevel) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012930 }
12931
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012932 @Override
12933 public LevelStepTracker getDischargeLevelStepTracker() {
12934 return mDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012935 }
12936
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012937 @Override
12938 public LevelStepTracker getDailyDischargeLevelStepTracker() {
12939 return mDailyDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012940 }
12941
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012942 @Override
12943 public long computeChargeTimeRemaining(long curTime) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012944 if (mOnBattery) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012945 // Not yet working.
12946 return -1;
12947 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070012948 /* Broken
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012949 int curLevel = mCurrentBatteryLevel;
12950 int plugLevel = mDischargePlugLevel;
12951 if (plugLevel < 0 || curLevel < (plugLevel+1)) {
12952 return -1;
12953 }
12954 long duration = computeBatteryRealtime(curTime, STATS_SINCE_UNPLUGGED);
12955 if (duration < 1000*1000) {
12956 return -1;
12957 }
12958 long usPerLevel = duration/(curLevel-plugLevel);
12959 return usPerLevel * (100-curLevel);
Dianne Hackborn260c5022014-04-29 11:23:16 -070012960 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012961 if (mChargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012962 return -1;
12963 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012964 long msPerLevel = mChargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012965 if (msPerLevel <= 0) {
12966 return -1;
12967 }
12968 return (msPerLevel * (100-mCurrentBatteryLevel)) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012969 }
12970
Siddharth Raya1fd0572017-11-13 14:20:47 -080012971 /*@hide */
12972 public CellularBatteryStats getCellularBatteryStats() {
12973 CellularBatteryStats s = new CellularBatteryStats();
12974 final int which = STATS_SINCE_CHARGED;
12975 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12976 final ControllerActivityCounter counter = getModemControllerActivity();
Siddharth Rayed754702018-02-15 12:44:37 -080012977 final long sleepTimeMs = counter.getSleepTimeCounter().getCountLocked(which);
Siddharth Raya1fd0572017-11-13 14:20:47 -080012978 final long idleTimeMs = counter.getIdleTimeCounter().getCountLocked(which);
12979 final long rxTimeMs = counter.getRxTimeCounter().getCountLocked(which);
12980 final long energyConsumedMaMs = counter.getPowerCounter().getCountLocked(which);
12981 long[] timeInRatMs = new long[BatteryStats.NUM_DATA_CONNECTION_TYPES];
12982 for (int i = 0; i < timeInRatMs.length; i++) {
12983 timeInRatMs[i] = getPhoneDataConnectionTime(i, rawRealTime, which) / 1000;
12984 }
12985 long[] timeInRxSignalStrengthLevelMs = new long[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
12986 for (int i = 0; i < timeInRxSignalStrengthLevelMs.length; i++) {
12987 timeInRxSignalStrengthLevelMs[i]
12988 = getPhoneSignalStrengthTime(i, rawRealTime, which) / 1000;
12989 }
12990 long[] txTimeMs = new long[Math.min(ModemActivityInfo.TX_POWER_LEVELS,
12991 counter.getTxTimeCounters().length)];
12992 long totalTxTimeMs = 0;
12993 for (int i = 0; i < txTimeMs.length; i++) {
12994 txTimeMs[i] = counter.getTxTimeCounters()[i].getCountLocked(which);
12995 totalTxTimeMs += txTimeMs[i];
12996 }
Siddharth Raya1fd0572017-11-13 14:20:47 -080012997 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
12998 s.setKernelActiveTimeMs(getMobileRadioActiveTime(rawRealTime, which) / 1000);
12999 s.setNumPacketsTx(getNetworkActivityPackets(NETWORK_MOBILE_TX_DATA, which));
13000 s.setNumBytesTx(getNetworkActivityBytes(NETWORK_MOBILE_TX_DATA, which));
13001 s.setNumPacketsRx(getNetworkActivityPackets(NETWORK_MOBILE_RX_DATA, which));
13002 s.setNumBytesRx(getNetworkActivityBytes(NETWORK_MOBILE_RX_DATA, which));
13003 s.setSleepTimeMs(sleepTimeMs);
13004 s.setIdleTimeMs(idleTimeMs);
13005 s.setRxTimeMs(rxTimeMs);
13006 s.setEnergyConsumedMaMs(energyConsumedMaMs);
13007 s.setTimeInRatMs(timeInRatMs);
13008 s.setTimeInRxSignalStrengthLevelMs(timeInRxSignalStrengthLevelMs);
13009 s.setTxTimeMs(txTimeMs);
13010 return s;
13011 }
13012
Siddharth Rayb50a6842017-12-14 15:15:28 -080013013 /*@hide */
13014 public WifiBatteryStats getWifiBatteryStats() {
13015 WifiBatteryStats s = new WifiBatteryStats();
13016 final int which = STATS_SINCE_CHARGED;
13017 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
13018 final ControllerActivityCounter counter = getWifiControllerActivity();
13019 final long idleTimeMs = counter.getIdleTimeCounter().getCountLocked(which);
13020 final long scanTimeMs = counter.getScanTimeCounter().getCountLocked(which);
13021 final long rxTimeMs = counter.getRxTimeCounter().getCountLocked(which);
13022 final long txTimeMs = counter.getTxTimeCounters()[0].getCountLocked(which);
13023 final long totalControllerActivityTimeMs
13024 = computeBatteryRealtime(SystemClock.elapsedRealtime() * 1000, which) / 1000;
13025 final long sleepTimeMs
13026 = totalControllerActivityTimeMs - (idleTimeMs + rxTimeMs + txTimeMs);
13027 final long energyConsumedMaMs = counter.getPowerCounter().getCountLocked(which);
13028 long numAppScanRequest = 0;
13029 for (int i = 0; i < mUidStats.size(); i++) {
13030 numAppScanRequest += mUidStats.valueAt(i).mWifiScanTimer.getCountLocked(which);
13031 }
13032 long[] timeInStateMs = new long[NUM_WIFI_STATES];
13033 for (int i=0; i<NUM_WIFI_STATES; i++) {
13034 timeInStateMs[i] = getWifiStateTime(i, rawRealTime, which) / 1000;
13035 }
13036 long[] timeInSupplStateMs = new long[NUM_WIFI_SUPPL_STATES];
13037 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
13038 timeInSupplStateMs[i] = getWifiSupplStateTime(i, rawRealTime, which) / 1000;
13039 }
13040 long[] timeSignalStrengthTimeMs = new long[NUM_WIFI_SIGNAL_STRENGTH_BINS];
13041 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
13042 timeSignalStrengthTimeMs[i] = getWifiSignalStrengthTime(i, rawRealTime, which) / 1000;
13043 }
13044 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
13045 s.setKernelActiveTimeMs(getWifiActiveTime(rawRealTime, which) / 1000);
13046 s.setNumPacketsTx(getNetworkActivityPackets(NETWORK_WIFI_TX_DATA, which));
13047 s.setNumBytesTx(getNetworkActivityBytes(NETWORK_WIFI_TX_DATA, which));
13048 s.setNumPacketsRx(getNetworkActivityPackets(NETWORK_WIFI_RX_DATA, which));
13049 s.setNumBytesRx(getNetworkActivityBytes(NETWORK_WIFI_RX_DATA, which));
13050 s.setSleepTimeMs(sleepTimeMs);
13051 s.setIdleTimeMs(idleTimeMs);
13052 s.setRxTimeMs(rxTimeMs);
13053 s.setTxTimeMs(txTimeMs);
13054 s.setScanTimeMs(scanTimeMs);
13055 s.setEnergyConsumedMaMs(energyConsumedMaMs);
13056 s.setNumAppScanRequest(numAppScanRequest);
13057 s.setTimeInStateMs(timeInStateMs);
13058 s.setTimeInSupplicantStateMs(timeInSupplStateMs);
13059 s.setTimeInRxSignalStrengthLevelMs(timeSignalStrengthTimeMs);
13060 return s;
13061 }
13062
Siddharth Ray78ccaf52017-12-23 16:16:21 -080013063 /*@hide */
13064 public GpsBatteryStats getGpsBatteryStats() {
13065 GpsBatteryStats s = new GpsBatteryStats();
13066 final int which = STATS_SINCE_CHARGED;
13067 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
13068 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
13069 s.setEnergyConsumedMaMs(getGpsBatteryDrainMaMs());
13070 long[] time = new long[GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS];
13071 for (int i=0; i<time.length; i++) {
13072 time[i] = getGpsSignalQualityTime(i, rawRealTime, which) / 1000;
13073 }
13074 s.setTimeInGpsSignalQualityLevel(time);
13075 return s;
13076 }
13077
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013078 @Override
13079 public LevelStepTracker getChargeLevelStepTracker() {
13080 return mChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070013081 }
13082
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013083 @Override
13084 public LevelStepTracker getDailyChargeLevelStepTracker() {
13085 return mDailyChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070013086 }
13087
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013088 @Override
13089 public ArrayList<PackageChange> getDailyPackageChanges() {
13090 return mDailyPackageChanges;
13091 }
13092
Joe Onoratoe1acd632016-02-23 13:25:10 -080013093 protected long getBatteryUptimeLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080013094 return mOnBatteryTimeBase.getUptime(mClocks.uptimeMillis() * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013095 }
13096
13097 @Override
13098 public long getBatteryUptime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013099 return mOnBatteryTimeBase.getUptime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013100 }
13101
13102 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +010013103 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013104 public long getBatteryRealtime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013105 return mOnBatteryTimeBase.getRealtime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013106 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -070013107
The Android Open Source Project10592532009-03-18 17:39:46 -070013108 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +010013109 @UnsupportedAppUsage
Evan Millar633a1742009-04-02 16:36:33 -070013110 public int getDischargeStartLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070013111 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070013112 return getDischargeStartLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070013113 }
13114 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013115
Evan Millar633a1742009-04-02 16:36:33 -070013116 public int getDischargeStartLevelLocked() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013117 return mDischargeUnplugLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070013118 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013119
The Android Open Source Project10592532009-03-18 17:39:46 -070013120 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +010013121 @UnsupportedAppUsage
Evan Millar633a1742009-04-02 16:36:33 -070013122 public int getDischargeCurrentLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070013123 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070013124 return getDischargeCurrentLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070013125 }
13126 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013127
Evan Millar633a1742009-04-02 16:36:33 -070013128 public int getDischargeCurrentLevelLocked() {
Dianne Hackborne4a59512010-12-07 11:08:07 -080013129 return mDischargeCurrentLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070013130 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013131
Amith Yamasanie43530a2009-08-21 13:11:37 -070013132 @Override
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013133 public int getLowDischargeAmountSinceCharge() {
13134 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080013135 int val = mLowDischargeAmountSinceCharge;
13136 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
13137 val += mDischargeUnplugLevel-mDischargeCurrentLevel-1;
13138 }
13139 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013140 }
13141 }
13142
13143 @Override
13144 public int getHighDischargeAmountSinceCharge() {
13145 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080013146 int val = mHighDischargeAmountSinceCharge;
13147 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
13148 val += mDischargeUnplugLevel-mDischargeCurrentLevel;
13149 }
13150 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013151 }
13152 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070013153
13154 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +010013155 @UnsupportedAppUsage
Dianne Hackborn40c87252014-03-19 16:55:40 -070013156 public int getDischargeAmount(int which) {
13157 int dischargeAmount = which == STATS_SINCE_CHARGED
13158 ? getHighDischargeAmountSinceCharge()
13159 : (getDischargeStartLevel() - getDischargeCurrentLevel());
13160 if (dischargeAmount < 0) {
13161 dischargeAmount = 0;
13162 }
13163 return dischargeAmount;
13164 }
13165
Mike Mac2f518a2017-09-19 16:06:03 -070013166 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +010013167 @UnsupportedAppUsage
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013168 public int getDischargeAmountScreenOn() {
13169 synchronized(this) {
13170 int val = mDischargeAmountScreenOn;
Mike Mac2f518a2017-09-19 16:06:03 -070013171 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013172 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
13173 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
13174 }
13175 return val;
13176 }
13177 }
13178
Mike Mac2f518a2017-09-19 16:06:03 -070013179 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013180 public int getDischargeAmountScreenOnSinceCharge() {
13181 synchronized(this) {
13182 int val = mDischargeAmountScreenOnSinceCharge;
Mike Mac2f518a2017-09-19 16:06:03 -070013183 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013184 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
13185 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
13186 }
13187 return val;
13188 }
13189 }
13190
Mike Mac2f518a2017-09-19 16:06:03 -070013191 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +010013192 @UnsupportedAppUsage
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013193 public int getDischargeAmountScreenOff() {
13194 synchronized(this) {
13195 int val = mDischargeAmountScreenOff;
Mike Mac2f518a2017-09-19 16:06:03 -070013196 if (mOnBattery && isScreenOff(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013197 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
13198 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
13199 }
Mike Mac2f518a2017-09-19 16:06:03 -070013200 // For backward compatibility, doze discharge is counted into screen off.
13201 return val + getDischargeAmountScreenDoze();
13202 }
13203 }
13204
13205 @Override
13206 public int getDischargeAmountScreenOffSinceCharge() {
13207 synchronized(this) {
13208 int val = mDischargeAmountScreenOffSinceCharge;
13209 if (mOnBattery && isScreenOff(mScreenState)
13210 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
13211 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
13212 }
13213 // For backward compatibility, doze discharge is counted into screen off.
13214 return val + getDischargeAmountScreenDozeSinceCharge();
13215 }
13216 }
13217
13218 @Override
13219 public int getDischargeAmountScreenDoze() {
13220 synchronized(this) {
13221 int val = mDischargeAmountScreenDoze;
13222 if (mOnBattery && isScreenDoze(mScreenState)
13223 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
13224 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
13225 }
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013226 return val;
13227 }
13228 }
13229
Mike Mac2f518a2017-09-19 16:06:03 -070013230 @Override
13231 public int getDischargeAmountScreenDozeSinceCharge() {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013232 synchronized(this) {
Mike Mac2f518a2017-09-19 16:06:03 -070013233 int val = mDischargeAmountScreenDozeSinceCharge;
13234 if (mOnBattery && isScreenDoze(mScreenState)
13235 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
13236 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013237 }
13238 return val;
13239 }
13240 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013242 /**
13243 * Retrieve the statistics object for a particular uid, creating if needed.
13244 */
Mathew Inwoodc185f082018-08-20 14:28:54 +010013245 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013246 public Uid getUidStatsLocked(int uid) {
13247 Uid u = mUidStats.get(uid);
13248 if (u == null) {
Joe Onoratoabded112016-02-08 16:49:39 -080013249 u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013250 mUidStats.put(uid, u);
13251 }
13252 return u;
13253 }
13254
Sudheer Shankab2f83c12017-11-13 19:25:01 -080013255 /**
13256 * Retrieve the statistics object for a particular uid. Returns null if the object is not
13257 * available.
13258 */
13259 public Uid getAvailableUidStatsLocked(int uid) {
13260 Uid u = mUidStats.get(uid);
13261 return u;
13262 }
13263
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070013264 public void onCleanupUserLocked(int userId) {
13265 final int firstUidForUser = UserHandle.getUid(userId, 0);
13266 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
Mike Ma234d1822018-03-13 18:53:21 -070013267 mPendingRemovedUids.add(
13268 new UidToRemove(firstUidForUser, lastUidForUser, mClocks.elapsedRealtime()));
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070013269 }
13270
13271 public void onUserRemovedLocked(int userId) {
13272 final int firstUidForUser = UserHandle.getUid(userId, 0);
13273 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
13274 mUidStats.put(firstUidForUser, null);
13275 mUidStats.put(lastUidForUser, null);
13276 final int firstIndex = mUidStats.indexOfKey(firstUidForUser);
13277 final int lastIndex = mUidStats.indexOfKey(lastUidForUser);
13278 mUidStats.removeAtRange(firstIndex, lastIndex - firstIndex + 1);
13279 }
13280
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013281 /**
13282 * Remove the statistics object for a particular uid.
13283 */
Mathew Inwoodc185f082018-08-20 14:28:54 +010013284 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013285 public void removeUidStatsLocked(int uid) {
13286 mUidStats.remove(uid);
Mike Ma234d1822018-03-13 18:53:21 -070013287 mPendingRemovedUids.add(new UidToRemove(uid, mClocks.elapsedRealtime()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013288 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -070013289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013290 /**
13291 * Retrieve the statistics object for a particular process, creating
13292 * if needed.
13293 */
Mathew Inwoodc185f082018-08-20 14:28:54 +010013294 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013295 public Uid.Proc getProcessStatsLocked(int uid, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013296 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013297 Uid u = getUidStatsLocked(uid);
13298 return u.getProcessStatsLocked(name);
13299 }
13300
13301 /**
13302 * Retrieve the statistics object for a particular process, creating
13303 * if needed.
13304 */
Mathew Inwoodc185f082018-08-20 14:28:54 +010013305 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013306 public Uid.Pkg getPackageStatsLocked(int uid, String pkg) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013307 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013308 Uid u = getUidStatsLocked(uid);
13309 return u.getPackageStatsLocked(pkg);
13310 }
13311
13312 /**
13313 * Retrieve the statistics object for a particular service, creating
13314 * if needed.
13315 */
Mathew Inwoodc185f082018-08-20 14:28:54 +010013316 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013317 public Uid.Pkg.Serv getServiceStatsLocked(int uid, String pkg, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013318 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013319 Uid u = getUidStatsLocked(uid);
13320 return u.getServiceStatsLocked(pkg, name);
13321 }
13322
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013323 public void shutdownLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080013324 recordShutdownLocked(mClocks.elapsedRealtime(), mClocks.uptimeMillis());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013325 writeSyncLocked();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013326 mShuttingDown = true;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013327 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013328
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013329 public boolean trackPerProcStateCpuTimes() {
13330 return mConstants.TRACK_CPU_TIMES_BY_PROC_STATE && mPerProcStateCpuTimesAvailable;
13331 }
13332
13333 public void systemServicesReady(Context context) {
13334 mConstants.startObserving(context.getContentResolver());
Mike Mafbc01fc2018-04-02 10:28:28 -070013335 registerUsbStateReceiver(context);
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013336 }
13337
13338 @VisibleForTesting
13339 public final class Constants extends ContentObserver {
13340 public static final String KEY_TRACK_CPU_TIMES_BY_PROC_STATE
13341 = "track_cpu_times_by_proc_state";
Mike Mafae87da2018-01-19 20:07:20 -080013342 public static final String KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME
13343 = "track_cpu_active_cluster_time";
Sudheer Shankac20379e2018-02-15 00:06:21 -080013344 public static final String KEY_PROC_STATE_CPU_TIMES_READ_DELAY_MS
13345 = "proc_state_cpu_times_read_delay_ms";
Mike Ma2ab01442018-02-13 14:22:47 -080013346 public static final String KEY_KERNEL_UID_READERS_THROTTLE_TIME
13347 = "kernel_uid_readers_throttle_time";
Mike Ma234d1822018-03-13 18:53:21 -070013348 public static final String KEY_UID_REMOVE_DELAY_MS
13349 = "uid_remove_delay_ms";
Sudheer Shankae56013a2018-04-23 11:22:15 -070013350 public static final String KEY_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS
13351 = "external_stats_collection_rate_limit_ms";
Sudheer Shanka0719c6a2018-04-24 11:12:11 -070013352 public static final String KEY_BATTERY_LEVEL_COLLECTION_DELAY_MS
13353 = "battery_level_collection_delay_ms";
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013354
13355 private static final boolean DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE = true;
Mike Mafae87da2018-01-19 20:07:20 -080013356 private static final boolean DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME = true;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013357 private static final long DEFAULT_PROC_STATE_CPU_TIMES_READ_DELAY_MS = 5_000;
Mike Ma2ab01442018-02-13 14:22:47 -080013358 private static final long DEFAULT_KERNEL_UID_READERS_THROTTLE_TIME = 10_000;
Mike Ma234d1822018-03-13 18:53:21 -070013359 private static final long DEFAULT_UID_REMOVE_DELAY_MS = 5L * 60L * 1000L;
Sudheer Shankae56013a2018-04-23 11:22:15 -070013360 private static final long DEFAULT_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS = 600_000;
Sudheer Shanka0719c6a2018-04-24 11:12:11 -070013361 private static final long DEFAULT_BATTERY_LEVEL_COLLECTION_DELAY_MS = 300_000;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013362
13363 public boolean TRACK_CPU_TIMES_BY_PROC_STATE = DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE;
Mike Mafae87da2018-01-19 20:07:20 -080013364 public boolean TRACK_CPU_ACTIVE_CLUSTER_TIME = DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013365 public long PROC_STATE_CPU_TIMES_READ_DELAY_MS = DEFAULT_PROC_STATE_CPU_TIMES_READ_DELAY_MS;
Mike Ma2ab01442018-02-13 14:22:47 -080013366 public long KERNEL_UID_READERS_THROTTLE_TIME = DEFAULT_KERNEL_UID_READERS_THROTTLE_TIME;
Mike Ma234d1822018-03-13 18:53:21 -070013367 public long UID_REMOVE_DELAY_MS = DEFAULT_UID_REMOVE_DELAY_MS;
Sudheer Shankae56013a2018-04-23 11:22:15 -070013368 public long EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS
13369 = DEFAULT_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS;
Sudheer Shanka0719c6a2018-04-24 11:12:11 -070013370 public long BATTERY_LEVEL_COLLECTION_DELAY_MS
13371 = DEFAULT_BATTERY_LEVEL_COLLECTION_DELAY_MS;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013372
13373 private ContentResolver mResolver;
13374 private final KeyValueListParser mParser = new KeyValueListParser(',');
13375
13376 public Constants(Handler handler) {
13377 super(handler);
13378 }
13379
13380 public void startObserving(ContentResolver resolver) {
13381 mResolver = resolver;
13382 mResolver.registerContentObserver(
13383 Settings.Global.getUriFor(Settings.Global.BATTERY_STATS_CONSTANTS),
13384 false /* notifyForDescendants */, this);
13385 updateConstants();
13386 }
13387
13388 @Override
13389 public void onChange(boolean selfChange, Uri uri) {
13390 updateConstants();
13391 }
13392
13393 private void updateConstants() {
13394 synchronized (BatteryStatsImpl.this) {
13395 try {
13396 mParser.setString(Settings.Global.getString(mResolver,
13397 Settings.Global.BATTERY_STATS_CONSTANTS));
13398 } catch (IllegalArgumentException e) {
13399 // Failed to parse the settings string, log this and move on
13400 // with defaults.
13401 Slog.e(TAG, "Bad batterystats settings", e);
13402 }
13403
13404 updateTrackCpuTimesByProcStateLocked(TRACK_CPU_TIMES_BY_PROC_STATE,
13405 mParser.getBoolean(KEY_TRACK_CPU_TIMES_BY_PROC_STATE,
13406 DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE));
Mike Mafae87da2018-01-19 20:07:20 -080013407 TRACK_CPU_ACTIVE_CLUSTER_TIME = mParser.getBoolean(
13408 KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME, DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME);
Sudheer Shankac20379e2018-02-15 00:06:21 -080013409 updateProcStateCpuTimesReadDelayMs(PROC_STATE_CPU_TIMES_READ_DELAY_MS,
13410 mParser.getLong(KEY_PROC_STATE_CPU_TIMES_READ_DELAY_MS,
Mike Ma2ab01442018-02-13 14:22:47 -080013411 DEFAULT_PROC_STATE_CPU_TIMES_READ_DELAY_MS));
13412 updateKernelUidReadersThrottleTime(KERNEL_UID_READERS_THROTTLE_TIME,
13413 mParser.getLong(KEY_KERNEL_UID_READERS_THROTTLE_TIME,
13414 DEFAULT_KERNEL_UID_READERS_THROTTLE_TIME));
Mike Ma234d1822018-03-13 18:53:21 -070013415 updateUidRemoveDelay(
13416 mParser.getLong(KEY_UID_REMOVE_DELAY_MS, DEFAULT_UID_REMOVE_DELAY_MS));
Sudheer Shankae56013a2018-04-23 11:22:15 -070013417 EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS = mParser.getLong(
13418 KEY_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS,
13419 DEFAULT_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS);
Sudheer Shanka0719c6a2018-04-24 11:12:11 -070013420 BATTERY_LEVEL_COLLECTION_DELAY_MS = mParser.getLong(
13421 KEY_BATTERY_LEVEL_COLLECTION_DELAY_MS,
13422 DEFAULT_BATTERY_LEVEL_COLLECTION_DELAY_MS);
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013423 }
13424 }
13425
13426 private void updateTrackCpuTimesByProcStateLocked(boolean wasEnabled, boolean isEnabled) {
13427 TRACK_CPU_TIMES_BY_PROC_STATE = isEnabled;
13428 if (isEnabled && !wasEnabled) {
13429 mKernelSingleUidTimeReader.markDataAsStale(true);
13430 mExternalSync.scheduleCpuSyncDueToSettingChange();
Sudheer Shankac20379e2018-02-15 00:06:21 -080013431
Mike Ma234d1822018-03-13 18:53:21 -070013432 mNumSingleUidCpuTimeReads = 0;
13433 mNumBatchedSingleUidCpuTimeReads = 0;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013434 mCpuTimeReadsTrackingStartTime = mClocks.uptimeMillis();
13435 }
13436 }
13437
13438 private void updateProcStateCpuTimesReadDelayMs(long oldDelayMillis, long newDelayMillis) {
13439 PROC_STATE_CPU_TIMES_READ_DELAY_MS = newDelayMillis;
13440 if (oldDelayMillis != newDelayMillis) {
Mike Ma234d1822018-03-13 18:53:21 -070013441 mNumSingleUidCpuTimeReads = 0;
13442 mNumBatchedSingleUidCpuTimeReads = 0;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013443 mCpuTimeReadsTrackingStartTime = mClocks.uptimeMillis();
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013444 }
13445 }
13446
Mike Ma2ab01442018-02-13 14:22:47 -080013447 private void updateKernelUidReadersThrottleTime(long oldTimeMs, long newTimeMs) {
13448 KERNEL_UID_READERS_THROTTLE_TIME = newTimeMs;
13449 if (oldTimeMs != newTimeMs) {
Mike Ma69d8b3e2018-02-23 14:51:26 -080013450 mKernelUidCpuTimeReader.setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
Mike Ma2ab01442018-02-13 14:22:47 -080013451 mKernelUidCpuFreqTimeReader.setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
13452 mKernelUidCpuActiveTimeReader.setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
13453 mKernelUidCpuClusterTimeReader
13454 .setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
13455 }
13456 }
13457
Mike Ma234d1822018-03-13 18:53:21 -070013458 private void updateUidRemoveDelay(long newTimeMs) {
13459 UID_REMOVE_DELAY_MS = newTimeMs;
13460 clearPendingRemovedUids();
13461 }
13462
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013463 public void dumpLocked(PrintWriter pw) {
13464 pw.print(KEY_TRACK_CPU_TIMES_BY_PROC_STATE); pw.print("=");
13465 pw.println(TRACK_CPU_TIMES_BY_PROC_STATE);
Mike Mafae87da2018-01-19 20:07:20 -080013466 pw.print(KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME); pw.print("=");
13467 pw.println(TRACK_CPU_ACTIVE_CLUSTER_TIME);
Sudheer Shankac20379e2018-02-15 00:06:21 -080013468 pw.print(KEY_PROC_STATE_CPU_TIMES_READ_DELAY_MS); pw.print("=");
13469 pw.println(PROC_STATE_CPU_TIMES_READ_DELAY_MS);
Mike Ma2ab01442018-02-13 14:22:47 -080013470 pw.print(KEY_KERNEL_UID_READERS_THROTTLE_TIME); pw.print("=");
13471 pw.println(KERNEL_UID_READERS_THROTTLE_TIME);
Sudheer Shankae56013a2018-04-23 11:22:15 -070013472 pw.print(KEY_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS); pw.print("=");
13473 pw.println(EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS);
Sudheer Shanka0719c6a2018-04-24 11:12:11 -070013474 pw.print(KEY_BATTERY_LEVEL_COLLECTION_DELAY_MS); pw.print("=");
13475 pw.println(BATTERY_LEVEL_COLLECTION_DELAY_MS);
Sudheer Shankae56013a2018-04-23 11:22:15 -070013476 }
13477 }
13478
13479 public long getExternalStatsCollectionRateLimitMs() {
13480 synchronized (this) {
13481 return mConstants.EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013482 }
13483 }
13484
Andreas Gampe3f24e692018-02-05 13:24:28 -080013485 @GuardedBy("this")
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013486 public void dumpConstantsLocked(PrintWriter pw) {
13487 mConstants.dumpLocked(pw);
13488 }
13489
Mike Ma234d1822018-03-13 18:53:21 -070013490 @GuardedBy("this")
13491 public void dumpCpuStatsLocked(PrintWriter pw) {
13492 int size = mUidStats.size();
13493 pw.println("Per UID CPU user & system time in ms:");
13494 for (int i = 0; i < size; i++) {
13495 int u = mUidStats.keyAt(i);
13496 Uid uid = mUidStats.get(u);
13497 pw.print(" "); pw.print(u); pw.print(": ");
13498 pw.print(uid.getUserCpuTimeUs(STATS_SINCE_CHARGED) / 1000); pw.print(" ");
13499 pw.println(uid.getSystemCpuTimeUs(STATS_SINCE_CHARGED) / 1000);
13500 }
13501 pw.println("Per UID CPU active time in ms:");
13502 for (int i = 0; i < size; i++) {
13503 int u = mUidStats.keyAt(i);
13504 Uid uid = mUidStats.get(u);
13505 if (uid.getCpuActiveTime() > 0) {
13506 pw.print(" "); pw.print(u); pw.print(": "); pw.println(uid.getCpuActiveTime());
13507 }
13508 }
13509 pw.println("Per UID CPU cluster time in ms:");
13510 for (int i = 0; i < size; i++) {
13511 int u = mUidStats.keyAt(i);
13512 long[] times = mUidStats.get(u).getCpuClusterTimes();
13513 if (times != null) {
13514 pw.print(" "); pw.print(u); pw.print(": "); pw.println(Arrays.toString(times));
13515 }
13516 }
13517 pw.println("Per UID CPU frequency time in ms:");
13518 for (int i = 0; i < size; i++) {
13519 int u = mUidStats.keyAt(i);
13520 long[] times = mUidStats.get(u).getCpuFreqTimes(STATS_SINCE_CHARGED);
13521 if (times != null) {
13522 pw.print(" "); pw.print(u); pw.print(": "); pw.println(Arrays.toString(times));
13523 }
13524 }
13525 }
13526
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013527 Parcel mPendingWrite = null;
13528 final ReentrantLock mWriteLock = new ReentrantLock();
13529
13530 public void writeAsyncLocked() {
13531 writeLocked(false);
13532 }
13533
13534 public void writeSyncLocked() {
13535 writeLocked(true);
13536 }
13537
13538 void writeLocked(boolean sync) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013539 if (mFile == null) {
13540 Slog.w("BatteryStats", "writeLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013541 return;
13542 }
13543
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013544 if (mShuttingDown) {
13545 return;
13546 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013547
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013548 Parcel out = Parcel.obtain();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013549 writeSummaryToParcel(out, true);
Joe Onoratoabded112016-02-08 16:49:39 -080013550 mLastWriteTime = mClocks.elapsedRealtime();
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013551
13552 if (mPendingWrite != null) {
13553 mPendingWrite.recycle();
13554 }
13555 mPendingWrite = out;
13556
13557 if (sync) {
13558 commitPendingDataToDisk();
13559 } else {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013560 BackgroundThread.getHandler().post(new Runnable() {
13561 @Override public void run() {
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013562 commitPendingDataToDisk();
13563 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013564 });
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013565 }
13566 }
13567
Mathew Inwoodc185f082018-08-20 14:28:54 +010013568 @UnsupportedAppUsage
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013569 public void commitPendingDataToDisk() {
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070013570 final Parcel next;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013571 synchronized (this) {
13572 next = mPendingWrite;
13573 mPendingWrite = null;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070013574 if (next == null) {
13575 return;
13576 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013577 }
13578
Amith Yamasanid2450862017-02-07 15:58:24 -080013579 mWriteLock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013580 try {
Dianne Hackborne17b4452018-01-10 13:15:40 -080013581 final long startTime = SystemClock.uptimeMillis();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013582 FileOutputStream stream = new FileOutputStream(mFile.chooseForWrite());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013583 stream.write(next.marshall());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013584 stream.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070013585 FileUtils.sync(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013586 stream.close();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013587 mFile.commit();
Dianne Hackborne17b4452018-01-10 13:15:40 -080013588 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
13589 "batterystats", SystemClock.uptimeMillis() - startTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013590 } catch (IOException e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013591 Slog.w("BatteryStats", "Error writing battery statistics", e);
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013592 mFile.rollback();
13593 } finally {
13594 next.recycle();
13595 mWriteLock.unlock();
Suchi Amalapurapu8550f252009-09-29 15:20:32 -070013596 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013597 }
13598
Mathew Inwoodc185f082018-08-20 14:28:54 +010013599 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013600 public void readLocked() {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013601 if (mDailyFile != null) {
13602 readDailyStatsLocked();
13603 }
13604
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013605 if (mFile == null) {
13606 Slog.w("BatteryStats", "readLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013607 return;
13608 }
13609
13610 mUidStats.clear();
13611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013612 try {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013613 File file = mFile.chooseForRead();
13614 if (!file.exists()) {
13615 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013616 }
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013617 FileInputStream stream = new FileInputStream(file);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013618
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013619 byte[] raw = BatteryStatsHelper.readFully(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013620 Parcel in = Parcel.obtain();
13621 in.unmarshall(raw, 0, raw.length);
13622 in.setDataPosition(0);
13623 stream.close();
13624
13625 readSummaryFromParcel(in);
Dianne Hackborn00e25212014-02-19 10:49:24 -080013626 } catch(Exception e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013627 Slog.e("BatteryStats", "Error reading battery statistics", e);
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013628 resetAllStatsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013629 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013630
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013631 mEndPlatformVersion = Build.ID;
13632
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013633 if (mHistoryBuffer.dataPosition() > 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013634 mRecordingHistory = true;
Joe Onoratoabded112016-02-08 16:49:39 -080013635 final long elapsedRealtime = mClocks.elapsedRealtime();
13636 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013637 if (USE_OLD_HISTORY) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013638 addHistoryRecordLocked(elapsedRealtime, uptime, HistoryItem.CMD_START, mHistoryCur);
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013639 }
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000013640 addHistoryBufferLocked(elapsedRealtime, HistoryItem.CMD_START, mHistoryCur);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013641 startRecordingHistory(elapsedRealtime, uptime, false);
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013642 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013643
13644 recordDailyStatsIfNeededLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013645 }
13646
13647 public int describeContents() {
13648 return 0;
13649 }
13650
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013651 void readHistory(Parcel in, boolean andOldHistory) throws ParcelFormatException {
Dianne Hackbornae384452011-06-28 12:33:48 -070013652 final long historyBaseTime = in.readLong();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013653
13654 mHistoryBuffer.setDataSize(0);
13655 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013656 mHistoryTagPool.clear();
13657 mNextHistoryTagIdx = 0;
13658 mNumHistoryTagChars = 0;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013659
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013660 int numTags = in.readInt();
13661 for (int i=0; i<numTags; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080013662 int idx = in.readInt();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013663 String str = in.readString();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013664 if (str == null) {
13665 throw new ParcelFormatException("null history tag string");
13666 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013667 int uid = in.readInt();
13668 HistoryTag tag = new HistoryTag();
13669 tag.string = str;
13670 tag.uid = uid;
13671 tag.poolIdx = idx;
13672 mHistoryTagPool.put(tag, idx);
13673 if (idx >= mNextHistoryTagIdx) {
13674 mNextHistoryTagIdx = idx+1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013675 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013676 mNumHistoryTagChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013677 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013678
13679 int bufSize = in.readInt();
13680 int curPos = in.dataPosition();
13681 if (bufSize >= (MAX_MAX_HISTORY_BUFFER*3)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013682 throw new ParcelFormatException("File corrupt: history data buffer too large " +
13683 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013684 } else if ((bufSize&~3) != bufSize) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013685 throw new ParcelFormatException("File corrupt: history data buffer not aligned " +
13686 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013687 } else {
13688 if (DEBUG_HISTORY) Slog.i(TAG, "***************** READING NEW HISTORY: " + bufSize
13689 + " bytes at " + curPos);
13690 mHistoryBuffer.appendFrom(in, curPos, bufSize);
13691 in.setDataPosition(curPos + bufSize);
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013692 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013693
Dianne Hackbornae384452011-06-28 12:33:48 -070013694 if (andOldHistory) {
13695 readOldHistory(in);
13696 }
13697
13698 if (DEBUG_HISTORY) {
13699 StringBuilder sb = new StringBuilder(128);
13700 sb.append("****************** OLD mHistoryBaseTime: ");
13701 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13702 Slog.i(TAG, sb.toString());
13703 }
13704 mHistoryBaseTime = historyBaseTime;
13705 if (DEBUG_HISTORY) {
13706 StringBuilder sb = new StringBuilder(128);
13707 sb.append("****************** NEW mHistoryBaseTime: ");
13708 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13709 Slog.i(TAG, sb.toString());
13710 }
13711
13712 // We are just arbitrarily going to insert 1 minute from the sample of
13713 // the last run until samples in this run.
13714 if (mHistoryBaseTime > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -080013715 long oldnow = mClocks.elapsedRealtime();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013716 mHistoryBaseTime = mHistoryBaseTime - oldnow + 1;
Dianne Hackbornae384452011-06-28 12:33:48 -070013717 if (DEBUG_HISTORY) {
13718 StringBuilder sb = new StringBuilder(128);
13719 sb.append("****************** ADJUSTED mHistoryBaseTime: ");
13720 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13721 Slog.i(TAG, sb.toString());
13722 }
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -070013723 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013724 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013725
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013726 void readOldHistory(Parcel in) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013727 if (!USE_OLD_HISTORY) {
13728 return;
13729 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013730 mHistory = mHistoryEnd = mHistoryCache = null;
13731 long time;
Conley Owens5e3357f2011-05-02 09:59:30 -070013732 while (in.dataAvail() > 0 && (time=in.readLong()) >= 0) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013733 HistoryItem rec = new HistoryItem(time, in);
13734 addHistoryRecordLocked(rec);
13735 }
13736 }
13737
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013738 void writeHistory(Parcel out, boolean inclData, boolean andOldHistory) {
Dianne Hackbornae384452011-06-28 12:33:48 -070013739 if (DEBUG_HISTORY) {
13740 StringBuilder sb = new StringBuilder(128);
13741 sb.append("****************** WRITING mHistoryBaseTime: ");
13742 TimeUtils.formatDuration(mHistoryBaseTime, sb);
Dianne Hackborn40c87252014-03-19 16:55:40 -070013743 sb.append(" mLastHistoryElapsedRealtime: ");
13744 TimeUtils.formatDuration(mLastHistoryElapsedRealtime, sb);
Dianne Hackbornae384452011-06-28 12:33:48 -070013745 Slog.i(TAG, sb.toString());
13746 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070013747 out.writeLong(mHistoryBaseTime + mLastHistoryElapsedRealtime);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013748 if (!inclData) {
13749 out.writeInt(0);
13750 out.writeInt(0);
13751 return;
13752 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013753 out.writeInt(mHistoryTagPool.size());
13754 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
13755 HistoryTag tag = ent.getKey();
Dianne Hackborn099bc622014-01-22 13:39:16 -080013756 out.writeInt(ent.getValue());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013757 out.writeString(tag.string);
13758 out.writeInt(tag.uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -080013759 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013760 out.writeInt(mHistoryBuffer.dataSize());
13761 if (DEBUG_HISTORY) Slog.i(TAG, "***************** WRITING HISTORY: "
13762 + mHistoryBuffer.dataSize() + " bytes at " + out.dataPosition());
13763 out.appendFrom(mHistoryBuffer, 0, mHistoryBuffer.dataSize());
Dianne Hackbornae384452011-06-28 12:33:48 -070013764
13765 if (andOldHistory) {
13766 writeOldHistory(out);
13767 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013768 }
13769
13770 void writeOldHistory(Parcel out) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013771 if (!USE_OLD_HISTORY) {
13772 return;
13773 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013774 HistoryItem rec = mHistory;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013775 while (rec != null) {
13776 if (rec.time >= 0) rec.writeToParcel(out, 0);
13777 rec = rec.next;
13778 }
13779 out.writeLong(-1);
13780 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013781
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013782 public void readSummaryFromParcel(Parcel in) throws ParcelFormatException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013783 final int version = in.readInt();
13784 if (version != VERSION) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013785 Slog.w("BatteryStats", "readFromParcel: version got " + version
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013786 + ", expected " + VERSION + "; erasing old stats");
13787 return;
13788 }
13789
Dianne Hackbornae384452011-06-28 12:33:48 -070013790 readHistory(in, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013792 mStartCount = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013793 mUptime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013794 mRealtime = in.readLong();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080013795 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013796 mStartPlatformVersion = in.readString();
13797 mEndPlatformVersion = in.readString();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013798 mOnBatteryTimeBase.readSummaryFromParcel(in);
13799 mOnBatteryScreenOffTimeBase.readSummaryFromParcel(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013800 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013801 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070013802 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013803 mCurrentBatteryLevel = in.readInt();
Adam Lesinskif9b20a92016-06-17 17:30:01 -070013804 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070013805 mMinLearnedBatteryCapacity = in.readInt();
13806 mMaxLearnedBatteryCapacity = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013807 mLowDischargeAmountSinceCharge = in.readInt();
13808 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013809 mDischargeAmountScreenOnSinceCharge = in.readInt();
13810 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070013811 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013812 mDischargeStepTracker.readFromParcel(in);
13813 mChargeStepTracker.readFromParcel(in);
13814 mDailyDischargeStepTracker.readFromParcel(in);
13815 mDailyChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070013816 mDischargeCounter.readSummaryFromParcelLocked(in);
13817 mDischargeScreenOffCounter.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070013818 mDischargeScreenDozeCounter.readSummaryFromParcelLocked(in);
Mike Ma15313c92017-11-15 17:58:21 -080013819 mDischargeLightDozeCounter.readSummaryFromParcelLocked(in);
13820 mDischargeDeepDozeCounter.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013821 int NPKG = in.readInt();
13822 if (NPKG > 0) {
13823 mDailyPackageChanges = new ArrayList<>(NPKG);
13824 while (NPKG > 0) {
13825 NPKG--;
13826 PackageChange pc = new PackageChange();
13827 pc.mPackageName = in.readString();
13828 pc.mUpdate = in.readInt() != 0;
Dianne Hackborn3accca02013-09-20 09:32:11 -070013829 pc.mVersionCode = in.readLong();
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013830 mDailyPackageChanges.add(pc);
13831 }
13832 } else {
13833 mDailyPackageChanges = null;
13834 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013835 mDailyStartTime = in.readLong();
13836 mNextMinDailyDeadline = in.readLong();
13837 mNextMaxDailyDeadline = in.readLong();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013839 mStartCount++;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013840
Jeff Browne95c3cd2014-05-02 16:59:26 -070013841 mScreenState = Display.STATE_UNKNOWN;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013842 mScreenOnTimer.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070013843 mScreenDozeTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn617f8772009-03-31 15:04:46 -070013844 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
13845 mScreenBrightnessTimer[i].readSummaryFromParcelLocked(in);
13846 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070013847 mInteractive = false;
13848 mInteractiveTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013849 mPhoneOn = false;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070013850 mPowerSaveModeEnabledTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070013851 mLongestLightIdleTime = in.readLong();
13852 mLongestFullIdleTime = in.readLong();
13853 mDeviceIdleModeLightTimer.readSummaryFromParcelLocked(in);
13854 mDeviceIdleModeFullTimer.readSummaryFromParcelLocked(in);
13855 mDeviceLightIdlingTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013856 mDeviceIdlingTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013857 mPhoneOnTimer.readSummaryFromParcelLocked(in);
Wink Saville52840902011-02-18 12:40:47 -080013858 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn627bba72009-03-24 22:32:56 -070013859 mPhoneSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
13860 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070013861 mPhoneSignalScanningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013862 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
13863 mPhoneDataConnectionsTimer[i].readSummaryFromParcelLocked(in);
13864 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013865 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013866 mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
13867 mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013868 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013869 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborne13c4c02014-02-11 17:18:35 -080013870 mMobileRadioActiveTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080013871 mMobileRadioActivePerAppTimer.readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013872 mMobileRadioActiveAdjustedTime.readSummaryFromParcelLocked(in);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013873 mMobileRadioActiveUnknownTime.readSummaryFromParcelLocked(in);
13874 mMobileRadioActiveUnknownCount.readSummaryFromParcelLocked(in);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080013875 mWifiMulticastWakelockTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070013876 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
The Android Open Source Project10592532009-03-18 17:39:46 -070013877 mWifiOn = false;
13878 mWifiOnTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013879 mGlobalWifiRunning = false;
13880 mGlobalWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080013881 for (int i=0; i<NUM_WIFI_STATES; i++) {
13882 mWifiStateTimer[i].readSummaryFromParcelLocked(in);
13883 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070013884 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
13885 mWifiSupplStateTimer[i].readSummaryFromParcelLocked(in);
13886 }
13887 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
13888 mWifiSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
13889 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080013890 mWifiActiveTimer.readSummaryFromParcelLocked(in);
13891 mWifiActivity.readSummaryFromParcel(in);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080013892 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
13893 mGpsSignalQualityTimer[i].readSummaryFromParcelLocked(in);
13894 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080013895 mBluetoothActivity.readSummaryFromParcel(in);
13896 mModemActivity.readSummaryFromParcel(in);
13897 mHasWifiReporting = in.readInt() != 0;
13898 mHasBluetoothReporting = in.readInt() != 0;
13899 mHasModemReporting = in.readInt() != 0;
Adam Lesinski33dac552015-03-09 15:24:48 -070013900
Dianne Hackborn1e01d162014-12-04 17:46:42 -080013901 mNumConnectivityChange = mLoadedNumConnectivityChange = in.readInt();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013902 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -070013903 mFlashlightOnTimer.readSummaryFromParcelLocked(in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013904 mCameraOnNesting = 0;
13905 mCameraOnTimer.readSummaryFromParcelLocked(in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013906 mBluetoothScanNesting = 0;
13907 mBluetoothScanTimer.readSummaryFromParcelLocked(in);
Siddharth Rayf5e796a2018-01-22 18:18:17 -080013908 mIsCellularTxPowerHigh = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013909
Bookatz50df7112017-08-04 14:53:26 -070013910 int NRPMS = in.readInt();
13911 if (NRPMS > 10000) {
13912 throw new ParcelFormatException("File corrupt: too many rpm stats " + NRPMS);
13913 }
13914 for (int irpm = 0; irpm < NRPMS; irpm++) {
13915 if (in.readInt() != 0) {
13916 String rpmName = in.readString();
13917 getRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
13918 }
13919 }
13920 int NSORPMS = in.readInt();
13921 if (NSORPMS > 10000) {
13922 throw new ParcelFormatException("File corrupt: too many screen-off rpm stats " + NSORPMS);
13923 }
13924 for (int irpm = 0; irpm < NSORPMS; irpm++) {
13925 if (in.readInt() != 0) {
13926 String rpmName = in.readString();
13927 getScreenOffRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
13928 }
13929 }
13930
Evan Millarc64edde2009-04-18 12:26:32 -070013931 int NKW = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013932 if (NKW > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013933 throw new ParcelFormatException("File corrupt: too many kernel wake locks " + NKW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013934 }
Evan Millarc64edde2009-04-18 12:26:32 -070013935 for (int ikw = 0; ikw < NKW; ikw++) {
13936 if (in.readInt() != 0) {
13937 String kwltName = in.readString();
13938 getKernelWakelockTimerLocked(kwltName).readSummaryFromParcelLocked(in);
13939 }
13940 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070013941
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013942 int NWR = in.readInt();
13943 if (NWR > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013944 throw new ParcelFormatException("File corrupt: too many wakeup reasons " + NWR);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013945 }
13946 for (int iwr = 0; iwr < NWR; iwr++) {
13947 if (in.readInt() != 0) {
13948 String reasonName = in.readString();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070013949 getWakeupReasonTimerLocked(reasonName).readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013950 }
13951 }
13952
James Carr3a226052016-07-01 14:49:52 -070013953 int NMS = in.readInt();
13954 for (int ims = 0; ims < NMS; ims++) {
13955 if (in.readInt() != 0) {
13956 long kmstName = in.readLong();
13957 getKernelMemoryTimerLocked(kmstName).readSummaryFromParcelLocked(in);
13958 }
13959 }
13960
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013961 final int NU = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013962 if (NU > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013963 throw new ParcelFormatException("File corrupt: too many uids " + NU);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013964 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013965 for (int iu = 0; iu < NU; iu++) {
13966 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080013967 Uid u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013968 mUidStats.put(uid, u);
13969
Bookatz867c0d72017-03-07 18:23:42 -080013970 u.mOnBatteryBackgroundTimeBase.readSummaryFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -070013971 u.mOnBatteryScreenOffBackgroundTimeBase.readSummaryFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -080013972
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013973 u.mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013974 if (in.readInt() != 0) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013975 u.mWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013976 }
The Android Open Source Project10592532009-03-18 17:39:46 -070013977 u.mFullWifiLockOut = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013978 if (in.readInt() != 0) {
13979 u.mFullWifiLockTimer.readSummaryFromParcelLocked(in);
13980 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070013981 u.mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013982 if (in.readInt() != 0) {
Nick Pelly6ccaa542012-06-15 15:22:47 -070013983 u.mWifiScanTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013984 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070013985 u.mWifiBatchedScanBinStarted = Uid.NO_BATCHED_SCAN_STARTED;
13986 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
13987 if (in.readInt() != 0) {
13988 u.makeWifiBatchedScanBin(i, null);
13989 u.mWifiBatchedScanTimer[i].readSummaryFromParcelLocked(in);
13990 }
13991 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070013992 u.mWifiMulticastEnabled = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013993 if (in.readInt() != 0) {
13994 u.mWifiMulticastTimer.readSummaryFromParcelLocked(in);
13995 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013996 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013997 u.createAudioTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013998 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013999 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014000 u.createVideoTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
14001 }
14002 if (in.readInt() != 0) {
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014003 u.createFlashlightTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
14004 }
14005 if (in.readInt() != 0) {
14006 u.createCameraTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
14007 }
14008 if (in.readInt() != 0) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014009 u.createForegroundActivityTimerLocked().readSummaryFromParcelLocked(in);
14010 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014011 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070014012 u.createForegroundServiceTimerLocked().readSummaryFromParcelLocked(in);
14013 }
14014 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -070014015 u.createAggregatedPartialWakelockTimerLocked().readSummaryFromParcelLocked(in);
14016 }
14017 if (in.readInt() != 0) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014018 u.createBluetoothScanTimerLocked().readSummaryFromParcelLocked(in);
14019 }
Bookatz956f36bf2017-04-28 09:48:17 -070014020 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -070014021 u.createBluetoothUnoptimizedScanTimerLocked().readSummaryFromParcelLocked(in);
14022 }
14023 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -070014024 u.createBluetoothScanResultCounterLocked().readSummaryFromParcelLocked(in);
14025 }
Bookatzb1f04f32017-05-19 13:57:32 -070014026 if (in.readInt() != 0) {
14027 u.createBluetoothScanResultBgCounterLocked().readSummaryFromParcelLocked(in);
14028 }
Dianne Hackborna8d10942015-11-19 17:55:19 -080014029 u.mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -070014030 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
14031 if (in.readInt() != 0) {
14032 u.makeProcessState(i, null);
14033 u.mProcessStateTimer[i].readSummaryFromParcelLocked(in);
14034 }
14035 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014036 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014037 u.createVibratorOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014038 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070014039
Dianne Hackborn617f8772009-03-31 15:04:46 -070014040 if (in.readInt() != 0) {
14041 if (u.mUserActivityCounters == null) {
14042 u.initUserActivityLocked();
14043 }
14044 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
14045 u.mUserActivityCounters[i].readSummaryFromParcelLocked(in);
14046 }
14047 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014048
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014049 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014050 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014051 u.initNetworkActivityLocked();
14052 }
14053 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014054 u.mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
14055 u.mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014056 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080014057 u.mMobileRadioActiveTime.readSummaryFromParcelLocked(in);
14058 u.mMobileRadioActiveCount.readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014059 }
14060
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014061 u.mUserCpuTime.readSummaryFromParcelLocked(in);
14062 u.mSystemCpuTime.readSummaryFromParcelLocked(in);
14063
Adam Lesinski6832f392015-09-05 18:05:40 -070014064 if (in.readInt() != 0) {
14065 final int numClusters = in.readInt();
14066 if (mPowerProfile != null && mPowerProfile.getNumCpuClusters() != numClusters) {
14067 throw new ParcelFormatException("Incompatible cpu cluster arrangement");
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014068 }
Adam Lesinski6832f392015-09-05 18:05:40 -070014069
Sudheer Shankaaf857412017-07-21 00:14:24 -070014070 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -070014071 for (int cluster = 0; cluster < numClusters; cluster++) {
Adam Lesinski6832f392015-09-05 18:05:40 -070014072 if (in.readInt() != 0) {
Adam Lesinskia57a5402015-09-28 10:21:33 -070014073 final int NSB = in.readInt();
14074 if (mPowerProfile != null &&
14075 mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != NSB) {
14076 throw new ParcelFormatException("File corrupt: too many speed bins " +
14077 NSB);
14078 }
14079
Sudheer Shankaaf857412017-07-21 00:14:24 -070014080 u.mCpuClusterSpeedTimesUs[cluster] = new LongSamplingCounter[NSB];
Adam Lesinski6832f392015-09-05 18:05:40 -070014081 for (int speed = 0; speed < NSB; speed++) {
14082 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070014083 u.mCpuClusterSpeedTimesUs[cluster][speed] = new LongSamplingCounter(
Adam Lesinski6832f392015-09-05 18:05:40 -070014084 mOnBatteryTimeBase);
Sudheer Shankaaf857412017-07-21 00:14:24 -070014085 u.mCpuClusterSpeedTimesUs[cluster][speed].readSummaryFromParcelLocked(in);
Adam Lesinski6832f392015-09-05 18:05:40 -070014086 }
14087 }
Adam Lesinskia57a5402015-09-28 10:21:33 -070014088 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070014089 u.mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -070014090 }
14091 }
14092 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070014093 u.mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014094 }
14095
Sudheer Shanka59f5c002017-05-15 10:57:15 -070014096 u.mCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
14097 in, mOnBatteryTimeBase);
14098 u.mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
14099 in, mOnBatteryScreenOffTimeBase);
Mike Ma3d422c32017-10-25 11:08:57 -070014100
14101 u.mCpuActiveTimeMs.readSummaryFromParcelLocked(in);
14102 u.mCpuClusterTimesMs.readSummaryFromParcelLocked(in);
14103
Sudheer Shankab2f83c12017-11-13 19:25:01 -080014104 int length = in.readInt();
14105 if (length == Uid.NUM_PROCESS_STATE) {
14106 u.mProcStateTimeMs = new LongSamplingCounterArray[length];
14107 for (int procState = 0; procState < length; ++procState) {
14108 u.mProcStateTimeMs[procState]
14109 = LongSamplingCounterArray.readSummaryFromParcelLocked(
14110 in, mOnBatteryTimeBase);
14111 }
14112 } else {
14113 u.mProcStateTimeMs = null;
14114 }
14115 length = in.readInt();
14116 if (length == Uid.NUM_PROCESS_STATE) {
14117 u.mProcStateScreenOffTimeMs = new LongSamplingCounterArray[length];
14118 for (int procState = 0; procState < length; ++procState) {
14119 u.mProcStateScreenOffTimeMs[procState]
14120 = LongSamplingCounterArray.readSummaryFromParcelLocked(
14121 in, mOnBatteryScreenOffTimeBase);
14122 }
14123 } else {
14124 u.mProcStateScreenOffTimeMs = null;
14125 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070014126
14127 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -070014128 u.mMobileRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
14129 u.mMobileRadioApWakeupCount.readSummaryFromParcelLocked(in);
14130 } else {
14131 u.mMobileRadioApWakeupCount = null;
14132 }
14133
14134 if (in.readInt() != 0) {
14135 u.mWifiRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
14136 u.mWifiRadioApWakeupCount.readSummaryFromParcelLocked(in);
14137 } else {
14138 u.mWifiRadioApWakeupCount = null;
14139 }
14140
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014141 int NW = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070014142 if (NW > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014143 throw new ParcelFormatException("File corrupt: too many wake locks " + NW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014144 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014145 for (int iw = 0; iw < NW; iw++) {
14146 String wlName = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014147 u.readWakeSummaryFromParcelLocked(wlName, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014148 }
14149
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014150 int NS = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070014151 if (NS > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014152 throw new ParcelFormatException("File corrupt: too many syncs " + NS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014153 }
14154 for (int is = 0; is < NS; is++) {
14155 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014156 u.readSyncSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014157 }
14158
14159 int NJ = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070014160 if (NJ > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014161 throw new ParcelFormatException("File corrupt: too many job timers " + NJ);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014162 }
14163 for (int ij = 0; ij < NJ; ij++) {
14164 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014165 u.readJobSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014166 }
14167
Dianne Hackborn94326cb2017-06-28 16:17:20 -070014168 u.readJobCompletionsFromParcelLocked(in);
14169
Amith Yamasani977e11f2018-02-16 11:29:54 -080014170 u.mJobsDeferredEventCount.readSummaryFromParcelLocked(in);
14171 u.mJobsDeferredCount.readSummaryFromParcelLocked(in);
14172 u.mJobsFreshnessTimeMs.readSummaryFromParcelLocked(in);
14173 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
14174 if (in.readInt() != 0) {
14175 u.mJobsFreshnessBuckets[i] = new Counter(u.mBsi.mOnBatteryTimeBase);
14176 u.mJobsFreshnessBuckets[i].readSummaryFromParcelLocked(in);
14177 }
14178 }
14179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014180 int NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014181 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014182 throw new ParcelFormatException("File corrupt: too many sensors " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014183 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014184 for (int is = 0; is < NP; is++) {
14185 int seNumber = in.readInt();
14186 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -080014187 u.getSensorTimerLocked(seNumber, true).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014188 }
14189 }
14190
14191 NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014192 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014193 throw new ParcelFormatException("File corrupt: too many processes " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014194 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014195 for (int ip = 0; ip < NP; ip++) {
14196 String procName = in.readString();
14197 Uid.Proc p = u.getProcessStatsLocked(procName);
14198 p.mUserTime = p.mLoadedUserTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014199 p.mSystemTime = p.mLoadedSystemTime = in.readLong();
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014200 p.mForegroundTime = p.mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014201 p.mStarts = p.mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014202 p.mNumCrashes = p.mLoadedNumCrashes = in.readInt();
14203 p.mNumAnrs = p.mLoadedNumAnrs = in.readInt();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014204 p.readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014205 }
14206
14207 NP = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014208 if (NP > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014209 throw new ParcelFormatException("File corrupt: too many packages " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014210 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014211 for (int ip = 0; ip < NP; ip++) {
14212 String pkgName = in.readString();
14213 Uid.Pkg p = u.getPackageStatsLocked(pkgName);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014214 final int NWA = in.readInt();
14215 if (NWA > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014216 throw new ParcelFormatException("File corrupt: too many wakeup alarms " + NWA);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014217 }
14218 p.mWakeupAlarms.clear();
14219 for (int iwa=0; iwa<NWA; iwa++) {
14220 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -070014221 Counter c = new Counter(mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014222 c.readSummaryFromParcelLocked(in);
14223 p.mWakeupAlarms.put(tag, c);
14224 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014225 NS = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014226 if (NS > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014227 throw new ParcelFormatException("File corrupt: too many services " + NS);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014228 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014229 for (int is = 0; is < NS; is++) {
14230 String servName = in.readString();
14231 Uid.Pkg.Serv s = u.getServiceStatsLocked(pkgName, servName);
14232 s.mStartTime = s.mLoadedStartTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014233 s.mStarts = s.mLoadedStarts = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014234 s.mLaunches = s.mLoadedLaunches = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014235 }
14236 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014237 }
14238 }
14239
14240 /**
14241 * Writes a summary of the statistics to a Parcel, in a format suitable to be written to
14242 * disk. This format does not allow a lossless round-trip.
14243 *
14244 * @param out the Parcel to be written to.
14245 */
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070014246 public void writeSummaryToParcel(Parcel out, boolean inclHistory) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080014247 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014248
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014249 // Pull the clock time. This may update the time and make a new history entry
14250 // if we had originally pulled a time before the RTC was set.
14251 long startClockTime = getStartClockTime();
14252
Joe Onoratoabded112016-02-08 16:49:39 -080014253 final long NOW_SYS = mClocks.uptimeMillis() * 1000;
14254 final long NOWREAL_SYS = mClocks.elapsedRealtime() * 1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014255
14256 out.writeInt(VERSION);
14257
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070014258 writeHistory(out, inclHistory, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014259
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014260 out.writeInt(mStartCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014261 out.writeLong(computeUptime(NOW_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014262 out.writeLong(computeRealtime(NOWREAL_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014263 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014264 out.writeString(mStartPlatformVersion);
14265 out.writeString(mEndPlatformVersion);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014266 mOnBatteryTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
14267 mOnBatteryScreenOffTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014268 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014269 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070014270 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014271 out.writeInt(mCurrentBatteryLevel);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014272 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070014273 out.writeInt(mMinLearnedBatteryCapacity);
14274 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborne4a59512010-12-07 11:08:07 -080014275 out.writeInt(getLowDischargeAmountSinceCharge());
14276 out.writeInt(getHighDischargeAmountSinceCharge());
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014277 out.writeInt(getDischargeAmountScreenOnSinceCharge());
14278 out.writeInt(getDischargeAmountScreenOffSinceCharge());
Mike Mac2f518a2017-09-19 16:06:03 -070014279 out.writeInt(getDischargeAmountScreenDozeSinceCharge());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014280 mDischargeStepTracker.writeToParcel(out);
14281 mChargeStepTracker.writeToParcel(out);
14282 mDailyDischargeStepTracker.writeToParcel(out);
14283 mDailyChargeStepTracker.writeToParcel(out);
Adam Lesinski67c134f2016-06-10 15:15:08 -070014284 mDischargeCounter.writeSummaryFromParcelLocked(out);
14285 mDischargeScreenOffCounter.writeSummaryFromParcelLocked(out);
Mike Mac2f518a2017-09-19 16:06:03 -070014286 mDischargeScreenDozeCounter.writeSummaryFromParcelLocked(out);
Mike Ma15313c92017-11-15 17:58:21 -080014287 mDischargeLightDozeCounter.writeSummaryFromParcelLocked(out);
14288 mDischargeDeepDozeCounter.writeSummaryFromParcelLocked(out);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014289 if (mDailyPackageChanges != null) {
14290 final int NPKG = mDailyPackageChanges.size();
14291 out.writeInt(NPKG);
14292 for (int i=0; i<NPKG; i++) {
14293 PackageChange pc = mDailyPackageChanges.get(i);
14294 out.writeString(pc.mPackageName);
14295 out.writeInt(pc.mUpdate ? 1 : 0);
Dianne Hackborn3accca02013-09-20 09:32:11 -070014296 out.writeLong(pc.mVersionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014297 }
14298 } else {
14299 out.writeInt(0);
14300 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014301 out.writeLong(mDailyStartTime);
14302 out.writeLong(mNextMinDailyDeadline);
14303 out.writeLong(mNextMaxDailyDeadline);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014304
14305 mScreenOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Mike Mac2f518a2017-09-19 16:06:03 -070014306 mScreenDozeTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070014307 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014308 mScreenBrightnessTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070014309 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070014310 mInteractiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070014311 mPowerSaveModeEnabledTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014312 out.writeLong(mLongestLightIdleTime);
14313 out.writeLong(mLongestFullIdleTime);
14314 mDeviceIdleModeLightTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14315 mDeviceIdleModeFullTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14316 mDeviceLightIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014317 mDeviceIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014318 mPhoneOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Wink Saville52840902011-02-18 12:40:47 -080014319 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014320 mPhoneSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070014321 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014322 mPhoneSignalScanningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070014323 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014324 mPhoneDataConnectionsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070014325 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014326 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014327 mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
14328 mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014329 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014330 mMobileRadioActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14331 mMobileRadioActivePerAppTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014332 mMobileRadioActiveAdjustedTime.writeSummaryFromParcelLocked(out);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080014333 mMobileRadioActiveUnknownTime.writeSummaryFromParcelLocked(out);
14334 mMobileRadioActiveUnknownCount.writeSummaryFromParcelLocked(out);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014335 mWifiMulticastWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014336 mWifiOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14337 mGlobalWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080014338 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014339 mWifiStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080014340 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014341 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
14342 mWifiSupplStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14343 }
14344 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
14345 mWifiSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14346 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014347 mWifiActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14348 mWifiActivity.writeSummaryToParcel(out);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014349 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14350 mGpsSignalQualityTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14351 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014352 mBluetoothActivity.writeSummaryToParcel(out);
14353 mModemActivity.writeSummaryToParcel(out);
14354 out.writeInt(mHasWifiReporting ? 1 : 0);
14355 out.writeInt(mHasBluetoothReporting ? 1 : 0);
14356 out.writeInt(mHasModemReporting ? 1 : 0);
14357
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014358 out.writeInt(mNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070014359 mFlashlightOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014360 mCameraOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014361 mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014362
Bookatz50df7112017-08-04 14:53:26 -070014363 out.writeInt(mRpmStats.size());
14364 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
14365 Timer rpmt = ent.getValue();
14366 if (rpmt != null) {
14367 out.writeInt(1);
14368 out.writeString(ent.getKey());
14369 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14370 } else {
14371 out.writeInt(0);
14372 }
14373 }
14374 out.writeInt(mScreenOffRpmStats.size());
14375 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
14376 Timer rpmt = ent.getValue();
14377 if (rpmt != null) {
14378 out.writeInt(1);
14379 out.writeString(ent.getKey());
14380 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14381 } else {
14382 out.writeInt(0);
14383 }
14384 }
14385
Evan Millarc64edde2009-04-18 12:26:32 -070014386 out.writeInt(mKernelWakelockStats.size());
14387 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
14388 Timer kwlt = ent.getValue();
14389 if (kwlt != null) {
14390 out.writeInt(1);
14391 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014392 kwlt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14393 } else {
14394 out.writeInt(0);
14395 }
14396 }
14397
14398 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014399 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
14400 SamplingTimer timer = ent.getValue();
14401 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014402 out.writeInt(1);
14403 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014404 timer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Evan Millarc64edde2009-04-18 12:26:32 -070014405 } else {
14406 out.writeInt(0);
14407 }
14408 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014409
James Carr3a226052016-07-01 14:49:52 -070014410 out.writeInt(mKernelMemoryStats.size());
14411 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
14412 Timer kmt = mKernelMemoryStats.valueAt(i);
14413 if (kmt != null) {
14414 out.writeInt(1);
14415 out.writeLong(mKernelMemoryStats.keyAt(i));
14416 kmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14417 } else {
14418 out.writeInt(0);
14419 }
14420 }
14421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014422 final int NU = mUidStats.size();
14423 out.writeInt(NU);
14424 for (int iu = 0; iu < NU; iu++) {
14425 out.writeInt(mUidStats.keyAt(iu));
14426 Uid u = mUidStats.valueAt(iu);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014427
Bookatz867c0d72017-03-07 18:23:42 -080014428 u.mOnBatteryBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatzc8c44962017-05-11 12:12:54 -070014429 u.mOnBatteryScreenOffBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatz867c0d72017-03-07 18:23:42 -080014430
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014431 if (u.mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014432 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014433 u.mWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014434 } else {
14435 out.writeInt(0);
14436 }
14437 if (u.mFullWifiLockTimer != null) {
14438 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014439 u.mFullWifiLockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014440 } else {
14441 out.writeInt(0);
14442 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070014443 if (u.mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014444 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014445 u.mWifiScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014446 } else {
14447 out.writeInt(0);
14448 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070014449 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
14450 if (u.mWifiBatchedScanTimer[i] != null) {
14451 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014452 u.mWifiBatchedScanTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Robert Greenwalta029ea12013-09-25 16:38:12 -070014453 } else {
14454 out.writeInt(0);
14455 }
14456 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014457 if (u.mWifiMulticastTimer != null) {
14458 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014459 u.mWifiMulticastTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014460 } else {
14461 out.writeInt(0);
14462 }
14463 if (u.mAudioTurnedOnTimer != null) {
14464 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014465 u.mAudioTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014466 } else {
14467 out.writeInt(0);
14468 }
14469 if (u.mVideoTurnedOnTimer != null) {
14470 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014471 u.mVideoTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014472 } else {
14473 out.writeInt(0);
14474 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014475 if (u.mFlashlightTurnedOnTimer != null) {
14476 out.writeInt(1);
14477 u.mFlashlightTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14478 } else {
14479 out.writeInt(0);
14480 }
14481 if (u.mCameraTurnedOnTimer != null) {
14482 out.writeInt(1);
14483 u.mCameraTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14484 } else {
14485 out.writeInt(0);
14486 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014487 if (u.mForegroundActivityTimer != null) {
14488 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014489 u.mForegroundActivityTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014490 } else {
14491 out.writeInt(0);
14492 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070014493 if (u.mForegroundServiceTimer != null) {
14494 out.writeInt(1);
14495 u.mForegroundServiceTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14496 } else {
14497 out.writeInt(0);
14498 }
Bookatzc8c44962017-05-11 12:12:54 -070014499 if (u.mAggregatedPartialWakelockTimer != null) {
14500 out.writeInt(1);
14501 u.mAggregatedPartialWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14502 } else {
14503 out.writeInt(0);
14504 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014505 if (u.mBluetoothScanTimer != null) {
14506 out.writeInt(1);
14507 u.mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14508 } else {
14509 out.writeInt(0);
14510 }
Bookatzb1f04f32017-05-19 13:57:32 -070014511 if (u.mBluetoothUnoptimizedScanTimer != null) {
14512 out.writeInt(1);
14513 u.mBluetoothUnoptimizedScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14514 } else {
14515 out.writeInt(0);
14516 }
Bookatz956f36bf2017-04-28 09:48:17 -070014517 if (u.mBluetoothScanResultCounter != null) {
14518 out.writeInt(1);
14519 u.mBluetoothScanResultCounter.writeSummaryFromParcelLocked(out);
14520 } else {
14521 out.writeInt(0);
14522 }
Bookatzb1f04f32017-05-19 13:57:32 -070014523 if (u.mBluetoothScanResultBgCounter != null) {
14524 out.writeInt(1);
14525 u.mBluetoothScanResultBgCounter.writeSummaryFromParcelLocked(out);
14526 } else {
14527 out.writeInt(0);
14528 }
Dianne Hackborn61659e52014-07-09 16:13:01 -070014529 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
14530 if (u.mProcessStateTimer[i] != null) {
14531 out.writeInt(1);
14532 u.mProcessStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14533 } else {
14534 out.writeInt(0);
14535 }
14536 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014537 if (u.mVibratorOnTimer != null) {
14538 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014539 u.mVibratorOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014540 } else {
14541 out.writeInt(0);
14542 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014543
Dianne Hackborn617f8772009-03-31 15:04:46 -070014544 if (u.mUserActivityCounters == null) {
14545 out.writeInt(0);
14546 } else {
14547 out.writeInt(1);
14548 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
14549 u.mUserActivityCounters[i].writeSummaryFromParcelLocked(out);
14550 }
14551 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014552
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014553 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014554 out.writeInt(0);
14555 } else {
14556 out.writeInt(1);
14557 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014558 u.mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
14559 u.mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014560 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080014561 u.mMobileRadioActiveTime.writeSummaryFromParcelLocked(out);
14562 u.mMobileRadioActiveCount.writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014563 }
14564
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014565 u.mUserCpuTime.writeSummaryFromParcelLocked(out);
14566 u.mSystemCpuTime.writeSummaryFromParcelLocked(out);
14567
Sudheer Shankaaf857412017-07-21 00:14:24 -070014568 if (u.mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -070014569 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -070014570 out.writeInt(u.mCpuClusterSpeedTimesUs.length);
14571 for (LongSamplingCounter[] cpuSpeeds : u.mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -070014572 if (cpuSpeeds != null) {
14573 out.writeInt(1);
14574 out.writeInt(cpuSpeeds.length);
14575 for (LongSamplingCounter c : cpuSpeeds) {
14576 if (c != null) {
14577 out.writeInt(1);
14578 c.writeSummaryFromParcelLocked(out);
14579 } else {
14580 out.writeInt(0);
14581 }
14582 }
14583 } else {
14584 out.writeInt(0);
14585 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014586 }
Adam Lesinski6832f392015-09-05 18:05:40 -070014587 } else {
14588 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014589 }
14590
Sudheer Shanka59f5c002017-05-15 10:57:15 -070014591 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mCpuFreqTimeMs);
14592 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mScreenOffCpuFreqTimeMs);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070014593
Mike Ma3d422c32017-10-25 11:08:57 -070014594 u.mCpuActiveTimeMs.writeSummaryFromParcelLocked(out);
14595 u.mCpuClusterTimesMs.writeSummaryToParcelLocked(out);
14596
Sudheer Shankab2f83c12017-11-13 19:25:01 -080014597 if (u.mProcStateTimeMs != null) {
14598 out.writeInt(u.mProcStateTimeMs.length);
14599 for (LongSamplingCounterArray counters : u.mProcStateTimeMs) {
14600 LongSamplingCounterArray.writeSummaryToParcelLocked(out, counters);
14601 }
14602 } else {
14603 out.writeInt(0);
14604 }
14605 if (u.mProcStateScreenOffTimeMs != null) {
14606 out.writeInt(u.mProcStateScreenOffTimeMs.length);
14607 for (LongSamplingCounterArray counters : u.mProcStateScreenOffTimeMs) {
14608 LongSamplingCounterArray.writeSummaryToParcelLocked(out, counters);
14609 }
14610 } else {
14611 out.writeInt(0);
14612 }
14613
Adam Lesinski5f056f62016-07-14 16:56:08 -070014614 if (u.mMobileRadioApWakeupCount != null) {
14615 out.writeInt(1);
14616 u.mMobileRadioApWakeupCount.writeSummaryFromParcelLocked(out);
14617 } else {
14618 out.writeInt(0);
14619 }
14620
14621 if (u.mWifiRadioApWakeupCount != null) {
14622 out.writeInt(1);
14623 u.mWifiRadioApWakeupCount.writeSummaryFromParcelLocked(out);
14624 } else {
14625 out.writeInt(0);
14626 }
14627
Dianne Hackbornd953c532014-08-16 18:17:38 -070014628 final ArrayMap<String, Uid.Wakelock> wakeStats = u.mWakelockStats.getMap();
14629 int NW = wakeStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014630 out.writeInt(NW);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014631 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014632 out.writeString(wakeStats.keyAt(iw));
14633 Uid.Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014634 if (wl.mTimerFull != null) {
14635 out.writeInt(1);
14636 wl.mTimerFull.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14637 } else {
14638 out.writeInt(0);
14639 }
14640 if (wl.mTimerPartial != null) {
14641 out.writeInt(1);
14642 wl.mTimerPartial.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14643 } else {
14644 out.writeInt(0);
14645 }
14646 if (wl.mTimerWindow != null) {
14647 out.writeInt(1);
14648 wl.mTimerWindow.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14649 } else {
14650 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014651 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070014652 if (wl.mTimerDraw != null) {
Adam Lesinski9425fe22015-06-19 12:02:13 -070014653 out.writeInt(1);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070014654 wl.mTimerDraw.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9425fe22015-06-19 12:02:13 -070014655 } else {
14656 out.writeInt(0);
14657 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014658 }
14659
Bookatz2bffb5b2017-04-13 11:59:33 -070014660 final ArrayMap<String, DualTimer> syncStats = u.mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014661 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014662 out.writeInt(NS);
14663 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014664 out.writeString(syncStats.keyAt(is));
14665 syncStats.valueAt(is).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014666 }
14667
Bookatzaa4594a2017-03-24 12:39:56 -070014668 final ArrayMap<String, DualTimer> jobStats = u.mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014669 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014670 out.writeInt(NJ);
14671 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014672 out.writeString(jobStats.keyAt(ij));
14673 jobStats.valueAt(ij).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014674 }
14675
Dianne Hackborn94326cb2017-06-28 16:17:20 -070014676 u.writeJobCompletionsToParcelLocked(out);
14677
Amith Yamasani977e11f2018-02-16 11:29:54 -080014678 u.mJobsDeferredEventCount.writeSummaryFromParcelLocked(out);
14679 u.mJobsDeferredCount.writeSummaryFromParcelLocked(out);
14680 u.mJobsFreshnessTimeMs.writeSummaryFromParcelLocked(out);
14681 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
14682 if (u.mJobsFreshnessBuckets[i] != null) {
Adam Lesinski14082082018-02-23 12:35:55 -080014683 out.writeInt(1);
Amith Yamasani977e11f2018-02-16 11:29:54 -080014684 u.mJobsFreshnessBuckets[i].writeSummaryFromParcelLocked(out);
14685 } else {
14686 out.writeInt(0);
14687 }
14688 }
14689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014690 int NSE = u.mSensorStats.size();
14691 out.writeInt(NSE);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014692 for (int ise=0; ise<NSE; ise++) {
14693 out.writeInt(u.mSensorStats.keyAt(ise));
14694 Uid.Sensor se = u.mSensorStats.valueAt(ise);
14695 if (se.mTimer != null) {
14696 out.writeInt(1);
14697 se.mTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14698 } else {
14699 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014700 }
14701 }
14702
14703 int NP = u.mProcessStats.size();
14704 out.writeInt(NP);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014705 for (int ip=0; ip<NP; ip++) {
14706 out.writeString(u.mProcessStats.keyAt(ip));
14707 Uid.Proc ps = u.mProcessStats.valueAt(ip);
14708 out.writeLong(ps.mUserTime);
14709 out.writeLong(ps.mSystemTime);
14710 out.writeLong(ps.mForegroundTime);
14711 out.writeInt(ps.mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014712 out.writeInt(ps.mNumCrashes);
14713 out.writeInt(ps.mNumAnrs);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014714 ps.writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014715 }
14716
14717 NP = u.mPackageStats.size();
14718 out.writeInt(NP);
14719 if (NP > 0) {
14720 for (Map.Entry<String, BatteryStatsImpl.Uid.Pkg> ent
14721 : u.mPackageStats.entrySet()) {
14722 out.writeString(ent.getKey());
14723 Uid.Pkg ps = ent.getValue();
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014724 final int NWA = ps.mWakeupAlarms.size();
14725 out.writeInt(NWA);
14726 for (int iwa=0; iwa<NWA; iwa++) {
14727 out.writeString(ps.mWakeupAlarms.keyAt(iwa));
14728 ps.mWakeupAlarms.valueAt(iwa).writeSummaryFromParcelLocked(out);
14729 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014730 NS = ps.mServiceStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014731 out.writeInt(NS);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014732 for (int is=0; is<NS; is++) {
14733 out.writeString(ps.mServiceStats.keyAt(is));
14734 BatteryStatsImpl.Uid.Pkg.Serv ss = ps.mServiceStats.valueAt(is);
14735 long time = ss.getStartTimeToNowLocked(
14736 mOnBatteryTimeBase.getUptime(NOW_SYS));
14737 out.writeLong(time);
14738 out.writeInt(ss.mStarts);
14739 out.writeInt(ss.mLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014740 }
14741 }
14742 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014743 }
14744 }
14745
14746 public void readFromParcel(Parcel in) {
14747 readFromParcelLocked(in);
14748 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014750 void readFromParcelLocked(Parcel in) {
14751 int magic = in.readInt();
14752 if (magic != MAGIC) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014753 throw new ParcelFormatException("Bad magic number: #" + Integer.toHexString(magic));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014754 }
14755
Dianne Hackbornae384452011-06-28 12:33:48 -070014756 readHistory(in, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014758 mStartCount = in.readInt();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080014759 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014760 mStartPlatformVersion = in.readString();
14761 mEndPlatformVersion = in.readString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014762 mUptime = in.readLong();
14763 mUptimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014764 mRealtime = in.readLong();
14765 mRealtimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014766 mOnBattery = in.readInt() != 0;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014767 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070014768 mMinLearnedBatteryCapacity = in.readInt();
14769 mMaxLearnedBatteryCapacity = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014770 mOnBatteryInternal = false; // we are no longer really running.
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014771 mOnBatteryTimeBase.readFromParcel(in);
14772 mOnBatteryScreenOffTimeBase.readFromParcel(in);
14773
Jeff Browne95c3cd2014-05-02 16:59:26 -070014774 mScreenState = Display.STATE_UNKNOWN;
Joe Onoratoabded112016-02-08 16:49:39 -080014775 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070014776 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014777 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014778 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
14779 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014780 }
Dianne Hackborn29325132014-05-21 15:01:03 -070014781 mInteractive = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014782 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014783 mPhoneOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014784 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
14785 mOnBatteryTimeBase, in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014786 mLongestLightIdleTime = in.readLong();
14787 mLongestFullIdleTime = in.readLong();
Joe Onoratoabded112016-02-08 16:49:39 -080014788 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -14, null,
14789 mOnBatteryTimeBase, in);
14790 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -11, null,
14791 mOnBatteryTimeBase, in);
14792 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null,
14793 mOnBatteryTimeBase, in);
14794 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase, in);
14795 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014796 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014797 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014798 null, mOnBatteryTimeBase, in);
14799 }
Joe Onoratoabded112016-02-08 16:49:39 -080014800 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
14801 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014802 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014803 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014804 null, mOnBatteryTimeBase, in);
14805 }
14806 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
14807 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
14808 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
14809 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014810 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Joe Onoratoabded112016-02-08 16:49:39 -080014811 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null,
14812 mOnBatteryTimeBase, in);
Kweku Adams87b19ec2017-10-09 12:40:03 -070014813 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
Joe Onoratoabded112016-02-08 16:49:39 -080014814 mOnBatteryTimeBase, in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014815 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014816 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
14817 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase, in);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014818 mWifiMulticastWakelockTimer = new StopwatchTimer(mClocks, null, -4, null,
14819 mOnBatteryTimeBase, in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070014820 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014821 mWifiOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014822 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014823 mGlobalWifiRunning = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014824 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null,
14825 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014826 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014827 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014828 null, mOnBatteryTimeBase, in);
14829 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014830 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014831 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070014832 null, mOnBatteryTimeBase, in);
14833 }
14834 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014835 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070014836 null, mOnBatteryTimeBase, in);
14837 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014838 mWifiActiveTimer = new StopwatchTimer(mClocks, null, -900, null,
14839 mOnBatteryTimeBase, in);
14840 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14841 NUM_WIFI_TX_LEVELS, in);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014842 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14843 mGpsSignalQualityTimer[i] = new StopwatchTimer(mClocks, null, -1000-i,
14844 null, mOnBatteryTimeBase, in);
14845 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014846 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14847 NUM_BT_TX_LEVELS, in);
14848 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14849 ModemActivityInfo.TX_POWER_LEVELS, in);
14850 mHasWifiReporting = in.readInt() != 0;
14851 mHasBluetoothReporting = in.readInt() != 0;
14852 mHasModemReporting = in.readInt() != 0;
14853
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014854 mNumConnectivityChange = in.readInt();
14855 mLoadedNumConnectivityChange = in.readInt();
14856 mUnpluggedNumConnectivityChange = in.readInt();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014857 mAudioOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014858 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014859 mVideoOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014860 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014861 mFlashlightOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014862 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014863 mCameraOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014864 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014865 mBluetoothScanNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014866 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase, in);
Siddharth Rayf5e796a2018-01-22 18:18:17 -080014867 mIsCellularTxPowerHigh = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014868 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014869 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070014870 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014871 mCurrentBatteryLevel = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014872 mLowDischargeAmountSinceCharge = in.readInt();
14873 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014874 mDischargeAmountScreenOn = in.readInt();
14875 mDischargeAmountScreenOnSinceCharge = in.readInt();
14876 mDischargeAmountScreenOff = in.readInt();
14877 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070014878 mDischargeAmountScreenDoze = in.readInt();
14879 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014880 mDischargeStepTracker.readFromParcel(in);
14881 mChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070014882 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070014883 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase, in);
14884 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Ma15313c92017-11-15 17:58:21 -080014885 mDischargeLightDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
14886 mDischargeDeepDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014887 mLastWriteTime = in.readLong();
14888
Bookatz50df7112017-08-04 14:53:26 -070014889 mRpmStats.clear();
14890 int NRPMS = in.readInt();
14891 for (int irpm = 0; irpm < NRPMS; irpm++) {
14892 if (in.readInt() != 0) {
14893 String rpmName = in.readString();
14894 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
14895 mRpmStats.put(rpmName, rpmt);
14896 }
14897 }
14898 mScreenOffRpmStats.clear();
14899 int NSORPMS = in.readInt();
14900 for (int irpm = 0; irpm < NSORPMS; irpm++) {
14901 if (in.readInt() != 0) {
14902 String rpmName = in.readString();
14903 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
14904 mScreenOffRpmStats.put(rpmName, rpmt);
14905 }
14906 }
14907
Evan Millarc64edde2009-04-18 12:26:32 -070014908 mKernelWakelockStats.clear();
14909 int NKW = in.readInt();
14910 for (int ikw = 0; ikw < NKW; ikw++) {
14911 if (in.readInt() != 0) {
14912 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080014913 SamplingTimer kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -070014914 mKernelWakelockStats.put(wakelockName, kwlt);
14915 }
14916 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014917
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014918 mWakeupReasonStats.clear();
14919 int NWR = in.readInt();
14920 for (int iwr = 0; iwr < NWR; iwr++) {
14921 if (in.readInt() != 0) {
14922 String reasonName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080014923 SamplingTimer timer = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014924 mWakeupReasonStats.put(reasonName, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014925 }
14926 }
14927
James Carr3a226052016-07-01 14:49:52 -070014928 mKernelMemoryStats.clear();
14929 int nmt = in.readInt();
14930 for (int imt = 0; imt < nmt; imt++) {
14931 if (in.readInt() != 0) {
14932 Long bucket = in.readLong();
14933 SamplingTimer kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
14934 mKernelMemoryStats.put(bucket, kmt);
14935 }
14936 }
14937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014938 mPartialTimers.clear();
14939 mFullTimers.clear();
14940 mWindowTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014941 mWifiRunningTimers.clear();
14942 mFullWifiLockTimers.clear();
Nick Pelly6ccaa542012-06-15 15:22:47 -070014943 mWifiScanTimers.clear();
Robert Greenwalta029ea12013-09-25 16:38:12 -070014944 mWifiBatchedScanTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014945 mWifiMulticastTimers.clear();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014946 mAudioTurnedOnTimers.clear();
14947 mVideoTurnedOnTimers.clear();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014948 mFlashlightTurnedOnTimers.clear();
14949 mCameraTurnedOnTimers.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014950
14951 int numUids = in.readInt();
14952 mUidStats.clear();
14953 for (int i = 0; i < numUids; i++) {
14954 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080014955 Uid u = new Uid(this, uid);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014956 u.readFromParcelLocked(mOnBatteryTimeBase, mOnBatteryScreenOffTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014957 mUidStats.append(uid, u);
14958 }
14959 }
14960
14961 public void writeToParcel(Parcel out, int flags) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014962 writeToParcelLocked(out, true, flags);
14963 }
14964
14965 public void writeToParcelWithoutUids(Parcel out, int flags) {
14966 writeToParcelLocked(out, false, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014967 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014968
14969 @SuppressWarnings("unused")
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014970 void writeToParcelLocked(Parcel out, boolean inclUids, int flags) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014971 // Need to update with current kernel wake lock counts.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080014972 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014973
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014974 // Pull the clock time. This may update the time and make a new history entry
14975 // if we had originally pulled a time before the RTC was set.
14976 long startClockTime = getStartClockTime();
14977
Joe Onoratoabded112016-02-08 16:49:39 -080014978 final long uSecUptime = mClocks.uptimeMillis() * 1000;
14979 final long uSecRealtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014980 final long batteryRealtime = mOnBatteryTimeBase.getRealtime(uSecRealtime);
14981 final long batteryScreenOffRealtime = mOnBatteryScreenOffTimeBase.getRealtime(uSecRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014982
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014983 out.writeInt(MAGIC);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014984
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070014985 writeHistory(out, true, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014986
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014987 out.writeInt(mStartCount);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014988 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014989 out.writeString(mStartPlatformVersion);
14990 out.writeString(mEndPlatformVersion);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014991 out.writeLong(mUptime);
14992 out.writeLong(mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014993 out.writeLong(mRealtime);
14994 out.writeLong(mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014995 out.writeInt(mOnBattery ? 1 : 0);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014996 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070014997 out.writeInt(mMinLearnedBatteryCapacity);
14998 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014999 mOnBatteryTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
15000 mOnBatteryScreenOffTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
15001
15002 mScreenOnTimer.writeToParcel(out, uSecRealtime);
Mike Mac2f518a2017-09-19 16:06:03 -070015003 mScreenDozeTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080015004 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
15005 mScreenBrightnessTimer[i].writeToParcel(out, uSecRealtime);
15006 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070015007 mInteractiveTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070015008 mPowerSaveModeEnabledTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070015009 out.writeLong(mLongestLightIdleTime);
15010 out.writeLong(mLongestFullIdleTime);
15011 mDeviceIdleModeLightTimer.writeToParcel(out, uSecRealtime);
15012 mDeviceIdleModeFullTimer.writeToParcel(out, uSecRealtime);
15013 mDeviceLightIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070015014 mDeviceIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080015015 mPhoneOnTimer.writeToParcel(out, uSecRealtime);
15016 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
15017 mPhoneSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
15018 }
15019 mPhoneSignalScanningTimer.writeToParcel(out, uSecRealtime);
15020 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
15021 mPhoneDataConnectionsTimer[i].writeToParcel(out, uSecRealtime);
15022 }
15023 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
15024 mNetworkByteActivityCounters[i].writeToParcel(out);
15025 mNetworkPacketActivityCounters[i].writeToParcel(out);
15026 }
15027 mMobileRadioActiveTimer.writeToParcel(out, uSecRealtime);
15028 mMobileRadioActivePerAppTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070015029 mMobileRadioActiveAdjustedTime.writeToParcel(out);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080015030 mMobileRadioActiveUnknownTime.writeToParcel(out);
15031 mMobileRadioActiveUnknownCount.writeToParcel(out);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080015032 mWifiMulticastWakelockTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080015033 mWifiOnTimer.writeToParcel(out, uSecRealtime);
15034 mGlobalWifiRunningTimer.writeToParcel(out, uSecRealtime);
15035 for (int i=0; i<NUM_WIFI_STATES; i++) {
15036 mWifiStateTimer[i].writeToParcel(out, uSecRealtime);
15037 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070015038 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
15039 mWifiSupplStateTimer[i].writeToParcel(out, uSecRealtime);
15040 }
15041 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
15042 mWifiSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
15043 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080015044 mWifiActiveTimer.writeToParcel(out, uSecRealtime);
15045 mWifiActivity.writeToParcel(out, 0);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080015046 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
15047 mGpsSignalQualityTimer[i].writeToParcel(out, uSecRealtime);
15048 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080015049 mBluetoothActivity.writeToParcel(out, 0);
15050 mModemActivity.writeToParcel(out, 0);
15051 out.writeInt(mHasWifiReporting ? 1 : 0);
15052 out.writeInt(mHasBluetoothReporting ? 1 : 0);
15053 out.writeInt(mHasModemReporting ? 1 : 0);
15054
Dianne Hackborn1e01d162014-12-04 17:46:42 -080015055 out.writeInt(mNumConnectivityChange);
15056 out.writeInt(mLoadedNumConnectivityChange);
15057 out.writeInt(mUnpluggedNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070015058 mFlashlightOnTimer.writeToParcel(out, uSecRealtime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070015059 mCameraOnTimer.writeToParcel(out, uSecRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080015060 mBluetoothScanTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070015061 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070015062 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070015063 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070015064 out.writeInt(mCurrentBatteryLevel);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015065 out.writeInt(mLowDischargeAmountSinceCharge);
15066 out.writeInt(mHighDischargeAmountSinceCharge);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080015067 out.writeInt(mDischargeAmountScreenOn);
15068 out.writeInt(mDischargeAmountScreenOnSinceCharge);
15069 out.writeInt(mDischargeAmountScreenOff);
15070 out.writeInt(mDischargeAmountScreenOffSinceCharge);
Mike Mac2f518a2017-09-19 16:06:03 -070015071 out.writeInt(mDischargeAmountScreenDoze);
15072 out.writeInt(mDischargeAmountScreenDozeSinceCharge);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080015073 mDischargeStepTracker.writeToParcel(out);
15074 mChargeStepTracker.writeToParcel(out);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070015075 mDischargeCounter.writeToParcel(out);
15076 mDischargeScreenOffCounter.writeToParcel(out);
Mike Mac2f518a2017-09-19 16:06:03 -070015077 mDischargeScreenDozeCounter.writeToParcel(out);
Mike Ma15313c92017-11-15 17:58:21 -080015078 mDischargeLightDozeCounter.writeToParcel(out);
15079 mDischargeDeepDozeCounter.writeToParcel(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015080 out.writeLong(mLastWriteTime);
15081
Bookatz50df7112017-08-04 14:53:26 -070015082 out.writeInt(mRpmStats.size());
15083 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
15084 SamplingTimer rpmt = ent.getValue();
15085 if (rpmt != null) {
15086 out.writeInt(1);
15087 out.writeString(ent.getKey());
15088 rpmt.writeToParcel(out, uSecRealtime);
15089 } else {
15090 out.writeInt(0);
15091 }
15092 }
15093 out.writeInt(mScreenOffRpmStats.size());
15094 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
15095 SamplingTimer rpmt = ent.getValue();
15096 if (rpmt != null) {
15097 out.writeInt(1);
15098 out.writeString(ent.getKey());
15099 rpmt.writeToParcel(out, uSecRealtime);
15100 } else {
15101 out.writeInt(0);
15102 }
15103 }
15104
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015105 if (inclUids) {
15106 out.writeInt(mKernelWakelockStats.size());
15107 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
15108 SamplingTimer kwlt = ent.getValue();
15109 if (kwlt != null) {
15110 out.writeInt(1);
15111 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070015112 kwlt.writeToParcel(out, uSecRealtime);
15113 } else {
15114 out.writeInt(0);
15115 }
15116 }
15117 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070015118 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
15119 SamplingTimer timer = ent.getValue();
15120 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070015121 out.writeInt(1);
15122 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070015123 timer.writeToParcel(out, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015124 } else {
15125 out.writeInt(0);
15126 }
Evan Millarc64edde2009-04-18 12:26:32 -070015127 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015128 } else {
Bookatzba78b2b2017-10-10 11:06:33 -070015129 out.writeInt(0);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015130 out.writeInt(0);
Evan Millarc64edde2009-04-18 12:26:32 -070015131 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070015132
James Carr3a226052016-07-01 14:49:52 -070015133 out.writeInt(mKernelMemoryStats.size());
15134 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
15135 SamplingTimer kmt = mKernelMemoryStats.valueAt(i);
15136 if (kmt != null) {
15137 out.writeInt(1);
15138 out.writeLong(mKernelMemoryStats.keyAt(i));
15139 kmt.writeToParcel(out, uSecRealtime);
15140 } else {
15141 out.writeInt(0);
15142 }
15143 }
15144
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015145 if (inclUids) {
15146 int size = mUidStats.size();
15147 out.writeInt(size);
15148 for (int i = 0; i < size; i++) {
15149 out.writeInt(mUidStats.keyAt(i));
15150 Uid uid = mUidStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015151
Bookatz867c0d72017-03-07 18:23:42 -080015152 uid.writeToParcelLocked(out, uSecUptime, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015153 }
15154 } else {
15155 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015156 }
15157 }
15158
Mathew Inwoodc185f082018-08-20 14:28:54 +010015159 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015160 public static final Parcelable.Creator<BatteryStatsImpl> CREATOR =
15161 new Parcelable.Creator<BatteryStatsImpl>() {
15162 public BatteryStatsImpl createFromParcel(Parcel in) {
15163 return new BatteryStatsImpl(in);
15164 }
15165
15166 public BatteryStatsImpl[] newArray(int size) {
15167 return new BatteryStatsImpl[size];
15168 }
15169 };
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070015170
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070015171 public void prepareForDumpLocked() {
15172 // Need to retrieve current kernel wake lock stats before printing.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080015173 pullPendingStateUpdatesLocked();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070015174
15175 // Pull the clock time. This may update the time and make a new history entry
15176 // if we had originally pulled a time before the RTC was set.
15177 getStartClockTime();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070015178 }
15179
Dianne Hackbornc51cf032014-03-02 19:08:15 -080015180 public void dumpLocked(Context context, PrintWriter pw, int flags, int reqUid, long histStart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015181 if (DEBUG) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080015182 pw.println("mOnBatteryTimeBase:");
15183 mOnBatteryTimeBase.dump(pw, " ");
15184 pw.println("mOnBatteryScreenOffTimeBase:");
15185 mOnBatteryScreenOffTimeBase.dump(pw, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015186 Printer pr = new PrintWriterPrinter(pw);
Mike Mac2f518a2017-09-19 16:06:03 -070015187 pr.println("*** Screen on timer:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015188 mScreenOnTimer.logState(pr, " ");
Mike Mac2f518a2017-09-19 16:06:03 -070015189 pr.println("*** Screen doze timer:");
15190 mScreenDozeTimer.logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070015191 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015192 pr.println("*** Screen brightness #" + i + ":");
15193 mScreenBrightnessTimer[i].logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070015194 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070015195 pr.println("*** Interactive timer:");
15196 mInteractiveTimer.logState(pr, " ");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070015197 pr.println("*** Power save mode timer:");
15198 mPowerSaveModeEnabledTimer.logState(pr, " ");
Dianne Hackborn08c47a52015-10-15 12:38:14 -070015199 pr.println("*** Device idle mode light timer:");
15200 mDeviceIdleModeLightTimer.logState(pr, " ");
15201 pr.println("*** Device idle mode full timer:");
15202 mDeviceIdleModeFullTimer.logState(pr, " ");
15203 pr.println("*** Device light idling timer:");
15204 mDeviceLightIdlingTimer.logState(pr, " ");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070015205 pr.println("*** Device idling timer:");
15206 mDeviceIdlingTimer.logState(pr, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015207 pr.println("*** Phone timer:");
15208 mPhoneOnTimer.logState(pr, " ");
Wink Saville52840902011-02-18 12:40:47 -080015209 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3251b902014-06-20 14:40:53 -070015210 pr.println("*** Phone signal strength #" + i + ":");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015211 mPhoneSignalStrengthsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070015212 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070015213 pr.println("*** Signal scanning :");
15214 mPhoneSignalScanningTimer.logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070015215 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015216 pr.println("*** Data connection type #" + i + ":");
15217 mPhoneDataConnectionsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070015218 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070015219 pr.println("*** mMobileRadioPowerState=" + mMobileRadioPowerState);
Dianne Hackborne13c4c02014-02-11 17:18:35 -080015220 pr.println("*** Mobile network active timer:");
15221 mMobileRadioActiveTimer.logState(pr, " ");
Dianne Hackborna1bd7922014-03-21 11:07:11 -070015222 pr.println("*** Mobile network active adjusted timer:");
15223 mMobileRadioActiveAdjustedTime.logState(pr, " ");
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080015224 pr.println("*** Wifi Multicast WakeLock Timer:");
15225 mWifiMulticastWakelockTimer.logState(pr, " ");
Dianne Hackborn0c820db2015-04-14 17:47:34 -070015226 pr.println("*** mWifiRadioPowerState=" + mWifiRadioPowerState);
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015227 pr.println("*** Wifi timer:");
15228 mWifiOnTimer.logState(pr, " ");
15229 pr.println("*** WifiRunning timer:");
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070015230 mGlobalWifiRunningTimer.logState(pr, " ");
Dianne Hackbornca1bf212014-02-14 14:18:36 -080015231 for (int i=0; i<NUM_WIFI_STATES; i++) {
15232 pr.println("*** Wifi state #" + i + ":");
15233 mWifiStateTimer[i].logState(pr, " ");
15234 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070015235 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
15236 pr.println("*** Wifi suppl state #" + i + ":");
15237 mWifiSupplStateTimer[i].logState(pr, " ");
15238 }
15239 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
15240 pr.println("*** Wifi signal strength #" + i + ":");
15241 mWifiSignalStrengthsTimer[i].logState(pr, " ");
15242 }
Siddharth Ray78ccaf52017-12-23 16:16:21 -080015243 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
15244 pr.println("*** GPS signal quality #" + i + ":");
15245 mGpsSignalQualityTimer[i].logState(pr, " ");
15246 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -070015247 pr.println("*** Flashlight timer:");
15248 mFlashlightOnTimer.logState(pr, " ");
Ruben Brunk6d2c3632015-05-26 17:32:16 -070015249 pr.println("*** Camera timer:");
15250 mCameraOnTimer.logState(pr, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015251 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -080015252 super.dumpLocked(context, pw, flags, reqUid, histStart);
Sudheer Shankac20379e2018-02-15 00:06:21 -080015253 pw.print("Total cpu time reads: ");
Mike Ma234d1822018-03-13 18:53:21 -070015254 pw.println(mNumSingleUidCpuTimeReads);
Sudheer Shankac20379e2018-02-15 00:06:21 -080015255 pw.print("Batched cpu time reads: ");
Mike Ma234d1822018-03-13 18:53:21 -070015256 pw.println(mNumBatchedSingleUidCpuTimeReads);
Sudheer Shankac20379e2018-02-15 00:06:21 -080015257 pw.print("Batching Duration (min): ");
15258 pw.println((mClocks.uptimeMillis() - mCpuTimeReadsTrackingStartTime) / (60 * 1000));
Mike Ma234d1822018-03-13 18:53:21 -070015259 pw.print("All UID cpu time reads since the later of device start or stats reset: ");
15260 pw.println(mNumAllUidCpuTimeReads);
15261 pw.print("UIDs removed since the later of device start or stats reset: ");
15262 pw.println(mNumUidsRemoved);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015263 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015264}