blob: 486c836279ced1a2d07e803a4e4ed8b87a8ba495 [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);
Yangster4ccebea2018-10-09 17:09:02 -07005372 StatsLog.write(StatsLog.PHONE_SERVICE_STATE_CHANGED, state, simState, strengthBin);
Amith Yamasanif37447b2009-10-08 18:28:01 -07005373 }
5374 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005375
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005376 if (!scanning) {
5377 // If we are no longer scanning, then stop the scanning timer.
5378 if (mPhoneSignalScanningTimer.isRunningLocked()) {
5379 mHistoryCur.states &= ~HistoryItem.STATE_PHONE_SCANNING_FLAG;
5380 if (DEBUG_HISTORY) Slog.v(TAG, "Phone stopped scanning to: "
5381 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08005382 newHistory = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005383 mPhoneSignalScanningTimer.stopRunningLocked(elapsedRealtime);
Yangster4ccebea2018-10-09 17:09:02 -07005384 StatsLog.write(StatsLog.PHONE_SERVICE_STATE_CHANGED, state, simState, strengthBin);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005385 }
5386 }
5387
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005388 if (mPhoneServiceState != state) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005389 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_STATE_MASK)
5390 | (state << HistoryItem.STATE_PHONE_STATE_SHIFT);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005391 if (DEBUG_HISTORY) Slog.v(TAG, "Phone state " + state + " to: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005392 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08005393 newHistory = true;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005394 mPhoneServiceState = state;
5395 }
Dianne Hackborne4a59512010-12-07 11:08:07 -08005396
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005397 if (mPhoneSignalStrengthBin != strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005398 if (mPhoneSignalStrengthBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005399 mPhoneSignalStrengthsTimer[mPhoneSignalStrengthBin].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005400 elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005401 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005402 if (strengthBin >= 0) {
5403 if (!mPhoneSignalStrengthsTimer[strengthBin].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005404 mPhoneSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005405 }
Dianne Hackborn3251b902014-06-20 14:40:53 -07005406 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_MASK)
5407 | (strengthBin << HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_SHIFT);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005408 if (DEBUG_HISTORY) Slog.v(TAG, "Signal strength " + strengthBin + " to: "
Dianne Hackborne4a59512010-12-07 11:08:07 -08005409 + Integer.toHexString(mHistoryCur.states));
5410 newHistory = true;
Bookatze5885242017-10-24 20:10:31 -07005411 StatsLog.write(StatsLog.PHONE_SIGNAL_STRENGTH_CHANGED, strengthBin);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005412 } else {
Dianne Hackborn3251b902014-06-20 14:40:53 -07005413 stopAllPhoneSignalStrengthTimersLocked(-1);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005414 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005415 mPhoneSignalStrengthBin = strengthBin;
Dianne Hackborne4a59512010-12-07 11:08:07 -08005416 }
5417
5418 if (newHistory) {
Dianne Hackborn40c87252014-03-19 16:55:40 -07005419 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005420 }
5421 }
5422
5423 /**
5424 * Telephony stack updates the phone state.
5425 * @param state phone state from ServiceState.getState()
5426 */
5427 public void notePhoneStateLocked(int state, int simState) {
5428 updateAllPhoneStateLocked(state, simState, mPhoneSignalStrengthBinRaw);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07005429 }
5430
Mathew Inwoodc185f082018-08-20 14:28:54 +01005431 @UnsupportedAppUsage
Wink Savillee9b06d72009-05-18 21:47:50 -07005432 public void notePhoneSignalStrengthLocked(SignalStrength signalStrength) {
Dianne Hackborn627bba72009-03-24 22:32:56 -07005433 // Bin the strength.
Wink Saville52840902011-02-18 12:40:47 -08005434 int bin = signalStrength.getLevel();
Dianne Hackborne4a59512010-12-07 11:08:07 -08005435 updateAllPhoneStateLocked(mPhoneServiceStateRaw, mPhoneSimStateRaw, bin);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005436 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005437
Mathew Inwoodc185f082018-08-20 14:28:54 +01005438 @UnsupportedAppUsage
Dianne Hackborn627bba72009-03-24 22:32:56 -07005439 public void notePhoneDataConnectionStateLocked(int dataType, boolean hasData) {
Tej Singheee317b2018-03-07 19:28:05 -08005440 // BatteryStats uses 0 to represent no network type.
5441 // Telephony does not have a concept of no network type, and uses 0 to represent unknown.
5442 // Unknown is included in DATA_CONNECTION_OTHER.
Dianne Hackborn627bba72009-03-24 22:32:56 -07005443 int bin = DATA_CONNECTION_NONE;
5444 if (hasData) {
Tej Singheee317b2018-03-07 19:28:05 -08005445 if (dataType > 0 && dataType <= TelephonyManager.MAX_NETWORK_TYPE) {
5446 bin = dataType;
5447 } else {
5448 bin = DATA_CONNECTION_OTHER;
Dianne Hackborn627bba72009-03-24 22:32:56 -07005449 }
5450 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07005451 if (DEBUG) Log.i(TAG, "Phone Data Connection -> " + dataType + " = " + hasData);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005452 if (mPhoneDataConnectionType != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005453 final long elapsedRealtime = mClocks.elapsedRealtime();
5454 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005455 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_DATA_CONNECTION_MASK)
5456 | (bin << HistoryItem.STATE_DATA_CONNECTION_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005457 if (DEBUG_HISTORY) Slog.v(TAG, "Data connection " + bin + " to: "
5458 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005459 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005460 if (mPhoneDataConnectionType >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005461 mPhoneDataConnectionsTimer[mPhoneDataConnectionType].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005462 elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005463 }
5464 mPhoneDataConnectionType = bin;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005465 mPhoneDataConnectionsTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005466 }
5467 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005468
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005469 public void noteWifiOnLocked() {
The Android Open Source Project10592532009-03-18 17:39:46 -07005470 if (!mWifiOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005471 final long elapsedRealtime = mClocks.elapsedRealtime();
5472 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005473 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005474 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI on to: "
5475 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005476 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005477 mWifiOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005478 mWifiOnTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005479 scheduleSyncExternalStatsLocked("wifi-off", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07005480 }
5481 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005482
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005483 public void noteWifiOffLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08005484 final long elapsedRealtime = mClocks.elapsedRealtime();
5485 final long uptime = mClocks.uptimeMillis();
The Android Open Source Project10592532009-03-18 17:39:46 -07005486 if (mWifiOn) {
Dianne Hackborn3251b902014-06-20 14:40:53 -07005487 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005488 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI off to: "
5489 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005490 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005491 mWifiOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005492 mWifiOnTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005493 scheduleSyncExternalStatsLocked("wifi-on", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07005494 }
5495 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005496
Mathew Inwoodc185f082018-08-20 14:28:54 +01005497 @UnsupportedAppUsage
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005498 public void noteAudioOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005499 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005500 final long elapsedRealtime = mClocks.elapsedRealtime();
5501 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005502 if (mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005503 mHistoryCur.states |= HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005504 if (DEBUG_HISTORY) Slog.v(TAG, "Audio on to: "
5505 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005506 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005507 mAudioOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005508 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005509 mAudioOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005510 getUidStatsLocked(uid).noteAudioTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005511 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005512
Mathew Inwoodc185f082018-08-20 14:28:54 +01005513 @UnsupportedAppUsage
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005514 public void noteAudioOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005515 if (mAudioOnNesting == 0) {
5516 return;
5517 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08005518 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005519 final long elapsedRealtime = mClocks.elapsedRealtime();
5520 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005521 if (--mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005522 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005523 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
5524 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005525 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005526 mAudioOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005527 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005528 getUidStatsLocked(uid).noteAudioTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005529 }
5530
Mathew Inwoodc185f082018-08-20 14:28:54 +01005531 @UnsupportedAppUsage
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005532 public void noteVideoOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005533 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005534 final long elapsedRealtime = mClocks.elapsedRealtime();
5535 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005536 if (mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005537 mHistoryCur.states2 |= HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005538 if (DEBUG_HISTORY) Slog.v(TAG, "Video on to: "
5539 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005540 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005541 mVideoOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005542 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005543 mVideoOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005544 getUidStatsLocked(uid).noteVideoTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005545 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005546
Mathew Inwoodc185f082018-08-20 14:28:54 +01005547 @UnsupportedAppUsage
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005548 public void noteVideoOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005549 if (mVideoOnNesting == 0) {
5550 return;
5551 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08005552 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005553 final long elapsedRealtime = mClocks.elapsedRealtime();
5554 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005555 if (--mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005556 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005557 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
5558 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005559 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005560 mVideoOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005561 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005562 getUidStatsLocked(uid).noteVideoTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005563 }
5564
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005565 public void noteResetAudioLocked() {
5566 if (mAudioOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005567 final long elapsedRealtime = mClocks.elapsedRealtime();
5568 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005569 mAudioOnNesting = 0;
5570 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
5571 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
5572 + Integer.toHexString(mHistoryCur.states));
5573 addHistoryRecordLocked(elapsedRealtime, uptime);
5574 mAudioOnTimer.stopAllRunningLocked(elapsedRealtime);
5575 for (int i=0; i<mUidStats.size(); i++) {
5576 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5577 uid.noteResetAudioLocked(elapsedRealtime);
5578 }
5579 }
5580 }
5581
5582 public void noteResetVideoLocked() {
5583 if (mVideoOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005584 final long elapsedRealtime = mClocks.elapsedRealtime();
5585 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005586 mAudioOnNesting = 0;
5587 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
5588 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
5589 + Integer.toHexString(mHistoryCur.states));
5590 addHistoryRecordLocked(elapsedRealtime, uptime);
5591 mVideoOnTimer.stopAllRunningLocked(elapsedRealtime);
5592 for (int i=0; i<mUidStats.size(); i++) {
5593 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5594 uid.noteResetVideoLocked(elapsedRealtime);
5595 }
5596 }
5597 }
5598
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005599 public void noteActivityResumedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005600 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005601 getUidStatsLocked(uid).noteActivityResumedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005602 }
5603
5604 public void noteActivityPausedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005605 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005606 getUidStatsLocked(uid).noteActivityPausedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005607 }
5608
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005609 public void noteVibratorOnLocked(int uid, long durationMillis) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005610 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005611 getUidStatsLocked(uid).noteVibratorOnLocked(durationMillis);
5612 }
5613
5614 public void noteVibratorOffLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005615 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005616 getUidStatsLocked(uid).noteVibratorOffLocked();
5617 }
5618
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005619 public void noteFlashlightOnLocked(int uid) {
5620 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005621 final long elapsedRealtime = mClocks.elapsedRealtime();
5622 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005623 if (mFlashlightOnNesting++ == 0) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005624 mHistoryCur.states2 |= HistoryItem.STATE2_FLASHLIGHT_FLAG;
5625 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight on to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005626 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005627 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005628 mFlashlightOnTimer.startRunningLocked(elapsedRealtime);
5629 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005630 getUidStatsLocked(uid).noteFlashlightTurnedOnLocked(elapsedRealtime);
5631 }
5632
5633 public void noteFlashlightOffLocked(int uid) {
5634 if (mFlashlightOnNesting == 0) {
5635 return;
5636 }
5637 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005638 final long elapsedRealtime = mClocks.elapsedRealtime();
5639 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005640 if (--mFlashlightOnNesting == 0) {
5641 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
5642 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
5643 + Integer.toHexString(mHistoryCur.states2));
5644 addHistoryRecordLocked(elapsedRealtime, uptime);
5645 mFlashlightOnTimer.stopRunningLocked(elapsedRealtime);
5646 }
5647 getUidStatsLocked(uid).noteFlashlightTurnedOffLocked(elapsedRealtime);
5648 }
5649
5650 public void noteCameraOnLocked(int uid) {
5651 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005652 final long elapsedRealtime = mClocks.elapsedRealtime();
5653 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005654 if (mCameraOnNesting++ == 0) {
5655 mHistoryCur.states2 |= HistoryItem.STATE2_CAMERA_FLAG;
5656 if (DEBUG_HISTORY) Slog.v(TAG, "Camera on to: "
5657 + Integer.toHexString(mHistoryCur.states2));
5658 addHistoryRecordLocked(elapsedRealtime, uptime);
5659 mCameraOnTimer.startRunningLocked(elapsedRealtime);
5660 }
5661 getUidStatsLocked(uid).noteCameraTurnedOnLocked(elapsedRealtime);
5662 }
5663
5664 public void noteCameraOffLocked(int uid) {
5665 if (mCameraOnNesting == 0) {
5666 return;
5667 }
5668 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005669 final long elapsedRealtime = mClocks.elapsedRealtime();
5670 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005671 if (--mCameraOnNesting == 0) {
5672 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
5673 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
5674 + Integer.toHexString(mHistoryCur.states2));
5675 addHistoryRecordLocked(elapsedRealtime, uptime);
5676 mCameraOnTimer.stopRunningLocked(elapsedRealtime);
5677 }
5678 getUidStatsLocked(uid).noteCameraTurnedOffLocked(elapsedRealtime);
5679 }
5680
5681 public void noteResetCameraLocked() {
5682 if (mCameraOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005683 final long elapsedRealtime = mClocks.elapsedRealtime();
5684 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005685 mCameraOnNesting = 0;
5686 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
5687 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
5688 + Integer.toHexString(mHistoryCur.states2));
5689 addHistoryRecordLocked(elapsedRealtime, uptime);
5690 mCameraOnTimer.stopAllRunningLocked(elapsedRealtime);
5691 for (int i=0; i<mUidStats.size(); i++) {
5692 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5693 uid.noteResetCameraLocked(elapsedRealtime);
5694 }
5695 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005696 }
5697
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005698 public void noteResetFlashlightLocked() {
5699 if (mFlashlightOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005700 final long elapsedRealtime = mClocks.elapsedRealtime();
5701 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005702 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005703 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
5704 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005705 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005706 addHistoryRecordLocked(elapsedRealtime, uptime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005707 mFlashlightOnTimer.stopAllRunningLocked(elapsedRealtime);
5708 for (int i=0; i<mUidStats.size(); i++) {
5709 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5710 uid.noteResetFlashlightLocked(elapsedRealtime);
5711 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005712 }
5713 }
5714
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005715 private void noteBluetoothScanStartedLocked(WorkChain workChain, int uid,
5716 boolean isUnoptimized) {
5717 uid = getAttributionUid(uid, workChain);
Bookatz867c0d72017-03-07 18:23:42 -08005718 final long elapsedRealtime = mClocks.elapsedRealtime();
5719 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005720 if (mBluetoothScanNesting == 0) {
5721 mHistoryCur.states2 |= HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5722 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan started for: "
5723 + Integer.toHexString(mHistoryCur.states2));
5724 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005725 mBluetoothScanTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005726 }
5727 mBluetoothScanNesting++;
Bookatzb1f04f32017-05-19 13:57:32 -07005728 getUidStatsLocked(uid).noteBluetoothScanStartedLocked(elapsedRealtime, isUnoptimized);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005729 }
5730
Bookatzb1f04f32017-05-19 13:57:32 -07005731 public void noteBluetoothScanStartedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005732 final int N = ws.size();
5733 for (int i = 0; i < N; i++) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005734 noteBluetoothScanStartedLocked(null, ws.get(i), isUnoptimized);
5735 }
5736
5737 final List<WorkChain> workChains = ws.getWorkChains();
5738 if (workChains != null) {
5739 for (int i = 0; i < workChains.size(); ++i) {
5740 noteBluetoothScanStartedLocked(workChains.get(i), -1, isUnoptimized);
5741 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005742 }
5743 }
5744
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005745 private void noteBluetoothScanStoppedLocked(WorkChain workChain, int uid,
5746 boolean isUnoptimized) {
5747 uid = getAttributionUid(uid, workChain);
Bookatz867c0d72017-03-07 18:23:42 -08005748 final long elapsedRealtime = mClocks.elapsedRealtime();
5749 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005750 mBluetoothScanNesting--;
5751 if (mBluetoothScanNesting == 0) {
5752 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5753 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan stopped for: "
5754 + Integer.toHexString(mHistoryCur.states2));
5755 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005756 mBluetoothScanTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005757 }
Bookatz94c5a312017-07-11 16:49:17 -07005758 getUidStatsLocked(uid).noteBluetoothScanStoppedLocked(elapsedRealtime, isUnoptimized);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005759 }
5760
5761 private int getAttributionUid(int uid, WorkChain workChain) {
5762 if (workChain != null) {
5763 return mapUid(workChain.getAttributionUid());
5764 }
5765
5766 return mapUid(uid);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005767 }
5768
Bookatz94c5a312017-07-11 16:49:17 -07005769 public void noteBluetoothScanStoppedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005770 final int N = ws.size();
5771 for (int i = 0; i < N; i++) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005772 noteBluetoothScanStoppedLocked(null, ws.get(i), isUnoptimized);
5773 }
5774
5775 final List<WorkChain> workChains = ws.getWorkChains();
5776 if (workChains != null) {
5777 for (int i = 0; i < workChains.size(); ++i) {
5778 noteBluetoothScanStoppedLocked(workChains.get(i), -1, isUnoptimized);
5779 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005780 }
5781 }
5782
5783 public void noteResetBluetoothScanLocked() {
5784 if (mBluetoothScanNesting > 0) {
Bookatz867c0d72017-03-07 18:23:42 -08005785 final long elapsedRealtime = mClocks.elapsedRealtime();
5786 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005787 mBluetoothScanNesting = 0;
5788 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5789 if (DEBUG_HISTORY) Slog.v(TAG, "BLE can stopped for: "
5790 + Integer.toHexString(mHistoryCur.states2));
5791 addHistoryRecordLocked(elapsedRealtime, uptime);
5792 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtime);
5793 for (int i=0; i<mUidStats.size(); i++) {
5794 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5795 uid.noteResetBluetoothScanLocked(elapsedRealtime);
5796 }
5797 }
5798 }
5799
Bookatz4ebc0642017-05-11 12:21:19 -07005800 public void noteBluetoothScanResultsFromSourceLocked(WorkSource ws, int numNewResults) {
Bookatz956f36bf2017-04-28 09:48:17 -07005801 final int N = ws.size();
5802 for (int i = 0; i < N; i++) {
5803 int uid = mapUid(ws.get(i));
Bookatz4ebc0642017-05-11 12:21:19 -07005804 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005805 }
5806
5807 final List<WorkChain> workChains = ws.getWorkChains();
5808 if (workChains != null) {
5809 for (int i = 0; i < workChains.size(); ++i) {
5810 final WorkChain wc = workChains.get(i);
5811 int uid = mapUid(wc.getAttributionUid());
5812 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005813 }
Bookatz956f36bf2017-04-28 09:48:17 -07005814 }
5815 }
5816
Adam Lesinski5f056f62016-07-14 16:56:08 -07005817 private void noteWifiRadioApWakeupLocked(final long elapsedRealtimeMillis,
5818 final long uptimeMillis, int uid) {
5819 uid = mapUid(uid);
5820 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
5821 uid);
5822 getUidStatsLocked(uid).noteWifiRadioApWakeupLocked();
5823 }
5824
5825 public void noteWifiRadioPowerState(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005826 final long elapsedRealtime = mClocks.elapsedRealtime();
5827 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005828 if (mWifiRadioPowerState != powerState) {
5829 final boolean active =
5830 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
5831 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
5832 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07005833 if (uid > 0) {
5834 noteWifiRadioApWakeupLocked(elapsedRealtime, uptime, uid);
5835 }
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005836 mHistoryCur.states |= HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
Siddharth Rayb50a6842017-12-14 15:15:28 -08005837 mWifiActiveTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005838 } else {
5839 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
Siddharth Rayb50a6842017-12-14 15:15:28 -08005840 mWifiActiveTimer.stopRunningLocked(
5841 timestampNs / (1000 * 1000));
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005842 }
5843 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi network active " + active + " to: "
5844 + Integer.toHexString(mHistoryCur.states));
5845 addHistoryRecordLocked(elapsedRealtime, uptime);
5846 mWifiRadioPowerState = powerState;
Yangster-mac4c7255f2018-05-07 13:41:47 -07005847 StatsLog.write_non_chained(StatsLog.WIFI_RADIO_POWER_STATE_CHANGED, uid, null,
5848 powerState);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005849 }
5850 }
5851
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005852 public void noteWifiRunningLocked(WorkSource ws) {
5853 if (!mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005854 final long elapsedRealtime = mClocks.elapsedRealtime();
5855 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005856 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005857 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI running to: "
5858 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005859 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005860 mGlobalWifiRunning = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005861 mGlobalWifiRunningTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005862 int N = ws.size();
5863 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005864 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005865 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005866 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005867
5868 List<WorkChain> workChains = ws.getWorkChains();
5869 if (workChains != null) {
5870 for (int i = 0; i < workChains.size(); ++i) {
5871 int uid = mapUid(workChains.get(i).getAttributionUid());
5872 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
5873 }
5874 }
5875
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005876 scheduleSyncExternalStatsLocked("wifi-running", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005877 } else {
5878 Log.w(TAG, "noteWifiRunningLocked -- called while WIFI running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005879 }
5880 }
5881
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005882 public void noteWifiRunningChangedLocked(WorkSource oldWs, WorkSource newWs) {
5883 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005884 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005885 int N = oldWs.size();
5886 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005887 int uid = mapUid(oldWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005888 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005889 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005890
5891 List<WorkChain> workChains = oldWs.getWorkChains();
5892 if (workChains != null) {
5893 for (int i = 0; i < workChains.size(); ++i) {
5894 int uid = mapUid(workChains.get(i).getAttributionUid());
5895 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
5896 }
5897 }
5898
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005899 N = newWs.size();
5900 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005901 int uid = mapUid(newWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005902 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005903 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005904
5905 workChains = newWs.getWorkChains();
5906 if (workChains != null) {
5907 for (int i = 0; i < workChains.size(); ++i) {
5908 int uid = mapUid(workChains.get(i).getAttributionUid());
5909 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
5910 }
5911 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005912 } else {
5913 Log.w(TAG, "noteWifiRunningChangedLocked -- called while WIFI not running");
5914 }
5915 }
5916
5917 public void noteWifiStoppedLocked(WorkSource ws) {
5918 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005919 final long elapsedRealtime = mClocks.elapsedRealtime();
5920 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005921 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005922 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI stopped to: "
5923 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005924 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005925 mGlobalWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005926 mGlobalWifiRunningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005927 int N = ws.size();
5928 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005929 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005930 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005931 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005932
5933 List<WorkChain> workChains = ws.getWorkChains();
5934 if (workChains != null) {
5935 for (int i = 0; i < workChains.size(); ++i) {
5936 int uid = mapUid(workChains.get(i).getAttributionUid());
5937 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
5938 }
5939 }
5940
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005941 scheduleSyncExternalStatsLocked("wifi-stopped", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005942 } else {
5943 Log.w(TAG, "noteWifiStoppedLocked -- called while WIFI not running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005944 }
5945 }
5946
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005947 public void noteWifiStateLocked(int wifiState, String accessPoint) {
5948 if (DEBUG) Log.i(TAG, "WiFi state -> " + wifiState);
5949 if (mWifiState != wifiState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005950 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005951 if (mWifiState >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005952 mWifiStateTimer[mWifiState].stopRunningLocked(elapsedRealtime);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005953 }
5954 mWifiState = wifiState;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005955 mWifiStateTimer[wifiState].startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005956 scheduleSyncExternalStatsLocked("wifi-state", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005957 }
5958 }
5959
Dianne Hackborn3251b902014-06-20 14:40:53 -07005960 public void noteWifiSupplicantStateChangedLocked(int supplState, boolean failedAuth) {
5961 if (DEBUG) Log.i(TAG, "WiFi suppl state -> " + supplState);
5962 if (mWifiSupplState != supplState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005963 final long elapsedRealtime = mClocks.elapsedRealtime();
5964 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005965 if (mWifiSupplState >= 0) {
5966 mWifiSupplStateTimer[mWifiSupplState].stopRunningLocked(elapsedRealtime);
5967 }
5968 mWifiSupplState = supplState;
5969 mWifiSupplStateTimer[supplState].startRunningLocked(elapsedRealtime);
5970 mHistoryCur.states2 =
5971 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SUPPL_STATE_MASK)
5972 | (supplState << HistoryItem.STATE2_WIFI_SUPPL_STATE_SHIFT);
5973 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi suppl state " + supplState + " to: "
5974 + Integer.toHexString(mHistoryCur.states2));
5975 addHistoryRecordLocked(elapsedRealtime, uptime);
5976 }
5977 }
5978
5979 void stopAllWifiSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005980 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005981 for (int i = 0; i < NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
5982 if (i == except) {
5983 continue;
5984 }
5985 while (mWifiSignalStrengthsTimer[i].isRunningLocked()) {
5986 mWifiSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
5987 }
5988 }
5989 }
5990
5991 public void noteWifiRssiChangedLocked(int newRssi) {
5992 int strengthBin = WifiManager.calculateSignalLevel(newRssi, NUM_WIFI_SIGNAL_STRENGTH_BINS);
5993 if (DEBUG) Log.i(TAG, "WiFi rssi -> " + newRssi + " bin=" + strengthBin);
5994 if (mWifiSignalStrengthBin != strengthBin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005995 final long elapsedRealtime = mClocks.elapsedRealtime();
5996 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005997 if (mWifiSignalStrengthBin >= 0) {
5998 mWifiSignalStrengthsTimer[mWifiSignalStrengthBin].stopRunningLocked(
5999 elapsedRealtime);
6000 }
6001 if (strengthBin >= 0) {
6002 if (!mWifiSignalStrengthsTimer[strengthBin].isRunningLocked()) {
6003 mWifiSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
6004 }
6005 mHistoryCur.states2 =
6006 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_MASK)
6007 | (strengthBin << HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_SHIFT);
6008 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi signal strength " + strengthBin + " to: "
6009 + Integer.toHexString(mHistoryCur.states2));
6010 addHistoryRecordLocked(elapsedRealtime, uptime);
6011 } else {
6012 stopAllWifiSignalStrengthTimersLocked(-1);
6013 }
Bookatz235343d2018-03-26 13:03:50 -07006014 StatsLog.write(StatsLog.WIFI_SIGNAL_STRENGTH_CHANGED, strengthBin);
Dianne Hackborn3251b902014-06-20 14:40:53 -07006015 mWifiSignalStrengthBin = strengthBin;
6016 }
6017 }
6018
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006019 int mWifiFullLockNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006020
Mathew Inwoodc185f082018-08-20 14:28:54 +01006021 @UnsupportedAppUsage
The Android Open Source Project10592532009-03-18 17:39:46 -07006022 public void noteFullWifiLockAcquiredLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006023 final long elapsedRealtime = mClocks.elapsedRealtime();
6024 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006025 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006026 mHistoryCur.states |= HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006027 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock on to: "
6028 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006029 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006030 }
6031 mWifiFullLockNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006032 getUidStatsLocked(uid).noteFullWifiLockAcquiredLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006033 }
6034
Mathew Inwoodc185f082018-08-20 14:28:54 +01006035 @UnsupportedAppUsage
The Android Open Source Project10592532009-03-18 17:39:46 -07006036 public void noteFullWifiLockReleasedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006037 final long elapsedRealtime = mClocks.elapsedRealtime();
6038 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006039 mWifiFullLockNesting--;
6040 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006041 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006042 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock off to: "
6043 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006044 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006045 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006046 getUidStatsLocked(uid).noteFullWifiLockReleasedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006047 }
6048
Nick Pelly6ccaa542012-06-15 15:22:47 -07006049 int mWifiScanNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006050
Nick Pelly6ccaa542012-06-15 15:22:47 -07006051 public void noteWifiScanStartedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006052 final long elapsedRealtime = mClocks.elapsedRealtime();
6053 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07006054 if (mWifiScanNesting == 0) {
6055 mHistoryCur.states |= HistoryItem.STATE_WIFI_SCAN_FLAG;
6056 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan started for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006057 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006058 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006059 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07006060 mWifiScanNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006061 getUidStatsLocked(uid).noteWifiScanStartedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006062 }
6063
Nick Pelly6ccaa542012-06-15 15:22:47 -07006064 public void noteWifiScanStoppedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006065 final long elapsedRealtime = mClocks.elapsedRealtime();
6066 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07006067 mWifiScanNesting--;
6068 if (mWifiScanNesting == 0) {
6069 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_SCAN_FLAG;
6070 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan stopped for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006071 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006072 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006073 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006074 getUidStatsLocked(uid).noteWifiScanStoppedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006075 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006076
Robert Greenwalta029ea12013-09-25 16:38:12 -07006077 public void noteWifiBatchedScanStartedLocked(int uid, int csph) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006078 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006079 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006080 getUidStatsLocked(uid).noteWifiBatchedScanStartedLocked(csph, elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006081 }
6082
6083 public void noteWifiBatchedScanStoppedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006084 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006085 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006086 getUidStatsLocked(uid).noteWifiBatchedScanStoppedLocked(elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006087 }
6088
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006089 int mWifiMulticastNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006090
Mathew Inwoodc185f082018-08-20 14:28:54 +01006091 @UnsupportedAppUsage
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006092 public void noteWifiMulticastEnabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006093 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006094 final long elapsedRealtime = mClocks.elapsedRealtime();
6095 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006096 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006097 mHistoryCur.states |= HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006098 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast on to: "
6099 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006100 addHistoryRecordLocked(elapsedRealtime, uptime);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006101
6102 // Start Wifi Multicast overall timer
6103 if (!mWifiMulticastWakelockTimer.isRunningLocked()) {
6104 if (DEBUG_HISTORY) Slog.v(TAG, "WiFi Multicast Overall Timer Started");
6105 mWifiMulticastWakelockTimer.startRunningLocked(elapsedRealtime);
6106 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006107 }
6108 mWifiMulticastNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006109 getUidStatsLocked(uid).noteWifiMulticastEnabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006110 }
6111
Mathew Inwoodc185f082018-08-20 14:28:54 +01006112 @UnsupportedAppUsage
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006113 public void noteWifiMulticastDisabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006114 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006115 final long elapsedRealtime = mClocks.elapsedRealtime();
6116 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006117 mWifiMulticastNesting--;
6118 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006119 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006120 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast off to: "
6121 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006122 addHistoryRecordLocked(elapsedRealtime, uptime);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006123
6124 // Stop Wifi Multicast overall timer
6125 if (mWifiMulticastWakelockTimer.isRunningLocked()) {
6126 if (DEBUG_HISTORY) Slog.v(TAG, "Multicast Overall Timer Stopped");
6127 mWifiMulticastWakelockTimer.stopRunningLocked(elapsedRealtime);
6128 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006129 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006130 getUidStatsLocked(uid).noteWifiMulticastDisabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006131 }
6132
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006133 public void noteFullWifiLockAcquiredFromSourceLocked(WorkSource ws) {
6134 int N = ws.size();
6135 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006136 final int uid = mapUid(ws.get(i));
6137 noteFullWifiLockAcquiredLocked(uid);
Bookatz90867622018-01-31 15:05:57 -08006138 StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, ws.get(i), ws.getName(i),
6139 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006140 }
6141
6142 final List<WorkChain> workChains = ws.getWorkChains();
6143 if (workChains != null) {
6144 for (int i = 0; i < workChains.size(); ++i) {
6145 final WorkChain workChain = workChains.get(i);
6146 final int uid = mapUid(workChain.getAttributionUid());
6147 noteFullWifiLockAcquiredLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006148 StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006149 workChain.getUids(), workChain.getTags(),
6150 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006151 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006152 }
6153 }
6154
6155 public void noteFullWifiLockReleasedFromSourceLocked(WorkSource ws) {
6156 int N = ws.size();
6157 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006158 final int uid = mapUid(ws.get(i));
6159 noteFullWifiLockReleasedLocked(uid);
Bookatz90867622018-01-31 15:05:57 -08006160 StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, ws.get(i), ws.getName(i),
6161 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006162 }
6163
6164 final List<WorkChain> workChains = ws.getWorkChains();
6165 if (workChains != null) {
6166 for (int i = 0; i < workChains.size(); ++i) {
6167 final WorkChain workChain = workChains.get(i);
6168 final int uid = mapUid(workChain.getAttributionUid());
6169 noteFullWifiLockReleasedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006170 StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006171 workChain.getUids(), workChain.getTags(),
6172 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006173 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006174 }
6175 }
6176
Nick Pelly6ccaa542012-06-15 15:22:47 -07006177 public void noteWifiScanStartedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006178 int N = ws.size();
6179 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006180 final int uid = mapUid(ws.get(i));
6181 noteWifiScanStartedLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08006182 StatsLog.write_non_chained(StatsLog.WIFI_SCAN_STATE_CHANGED, ws.get(i), ws.getName(i),
Bookatz90867622018-01-31 15:05:57 -08006183 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006184 }
6185
6186 final List<WorkChain> workChains = ws.getWorkChains();
6187 if (workChains != null) {
6188 for (int i = 0; i < workChains.size(); ++i) {
6189 final WorkChain workChain = workChains.get(i);
6190 final int uid = mapUid(workChain.getAttributionUid());
6191 noteWifiScanStartedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006192 StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED, workChain.getUids(),
Bookatz90867622018-01-31 15:05:57 -08006193 workChain.getTags(), StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006194 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006195 }
6196 }
6197
Nick Pelly6ccaa542012-06-15 15:22:47 -07006198 public void noteWifiScanStoppedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006199 int N = ws.size();
6200 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006201 final int uid = mapUid(ws.get(i));
6202 noteWifiScanStoppedLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08006203 StatsLog.write_non_chained(StatsLog.WIFI_SCAN_STATE_CHANGED, ws.get(i), ws.getName(i),
Bookatz90867622018-01-31 15:05:57 -08006204 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006205 }
6206
6207 final List<WorkChain> workChains = ws.getWorkChains();
6208 if (workChains != null) {
6209 for (int i = 0; i < workChains.size(); ++i) {
6210 final WorkChain workChain = workChains.get(i);
6211 final int uid = mapUid(workChain.getAttributionUid());
6212 noteWifiScanStoppedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006213 StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006214 workChain.getUids(), workChain.getTags(),
6215 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006216 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006217 }
6218 }
6219
Robert Greenwalta029ea12013-09-25 16:38:12 -07006220 public void noteWifiBatchedScanStartedFromSourceLocked(WorkSource ws, int csph) {
6221 int N = ws.size();
6222 for (int i=0; i<N; i++) {
6223 noteWifiBatchedScanStartedLocked(ws.get(i), csph);
6224 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00006225
6226 final List<WorkChain> workChains = ws.getWorkChains();
6227 if (workChains != null) {
6228 for (int i = 0; i < workChains.size(); ++i) {
6229 noteWifiBatchedScanStartedLocked(workChains.get(i).getAttributionUid(), csph);
6230 }
6231 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006232 }
6233
6234 public void noteWifiBatchedScanStoppedFromSourceLocked(WorkSource ws) {
6235 int N = ws.size();
6236 for (int i=0; i<N; i++) {
6237 noteWifiBatchedScanStoppedLocked(ws.get(i));
6238 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00006239
6240 final List<WorkChain> workChains = ws.getWorkChains();
6241 if (workChains != null) {
6242 for (int i = 0; i < workChains.size(); ++i) {
6243 noteWifiBatchedScanStoppedLocked(workChains.get(i).getAttributionUid());
6244 }
6245 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006246 }
6247
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08006248 private static String[] includeInStringArray(String[] array, String str) {
6249 if (ArrayUtils.indexOf(array, str) >= 0) {
6250 return array;
6251 }
6252 String[] newArray = new String[array.length+1];
6253 System.arraycopy(array, 0, newArray, 0, array.length);
6254 newArray[array.length] = str;
6255 return newArray;
6256 }
6257
6258 private static String[] excludeFromStringArray(String[] array, String str) {
6259 int index = ArrayUtils.indexOf(array, str);
6260 if (index >= 0) {
6261 String[] newArray = new String[array.length-1];
6262 if (index > 0) {
6263 System.arraycopy(array, 0, newArray, 0, index);
6264 }
6265 if (index < array.length-1) {
6266 System.arraycopy(array, index+1, newArray, index, array.length-index-1);
6267 }
6268 return newArray;
6269 }
6270 return array;
6271 }
6272
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07006273 public void noteNetworkInterfaceTypeLocked(String iface, int networkType) {
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07006274 if (TextUtils.isEmpty(iface)) return;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006275
Adam Lesinski14ae39a2017-05-26 11:50:40 -07006276 synchronized (mModemNetworkLock) {
6277 if (ConnectivityManager.isNetworkTypeMobile(networkType)) {
6278 mModemIfaces = includeInStringArray(mModemIfaces, iface);
6279 if (DEBUG) Slog.d(TAG, "Note mobile iface " + iface + ": " + mModemIfaces);
6280 } else {
6281 mModemIfaces = excludeFromStringArray(mModemIfaces, iface);
6282 if (DEBUG) Slog.d(TAG, "Note non-mobile iface " + iface + ": " + mModemIfaces);
6283 }
6284 }
6285
6286 synchronized (mWifiNetworkLock) {
6287 if (ConnectivityManager.isNetworkTypeWifi(networkType)) {
6288 mWifiIfaces = includeInStringArray(mWifiIfaces, iface);
6289 if (DEBUG) Slog.d(TAG, "Note wifi iface " + iface + ": " + mWifiIfaces);
6290 } else {
6291 mWifiIfaces = excludeFromStringArray(mWifiIfaces, iface);
6292 if (DEBUG) Slog.d(TAG, "Note non-wifi iface " + iface + ": " + mWifiIfaces);
6293 }
6294 }
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07006295 }
6296
David Chenc8a43242017-10-17 16:23:28 -07006297 public String[] getWifiIfaces() {
6298 synchronized (mWifiNetworkLock) {
6299 return mWifiIfaces;
6300 }
6301 }
6302
6303 public String[] getMobileIfaces() {
6304 synchronized (mModemNetworkLock) {
6305 return mModemIfaces;
6306 }
6307 }
6308
Mathew Inwoodc185f082018-08-20 14:28:54 +01006309 @UnsupportedAppUsage
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006310 @Override public long getScreenOnTime(long elapsedRealtimeUs, int which) {
6311 return mScreenOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006312 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006313
Dianne Hackborn77b987f2014-02-26 16:20:52 -08006314 @Override public int getScreenOnCount(int which) {
6315 return mScreenOnTimer.getCountLocked(which);
6316 }
6317
Mike Mac2f518a2017-09-19 16:06:03 -07006318 @Override public long getScreenDozeTime(long elapsedRealtimeUs, int which) {
6319 return mScreenDozeTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6320 }
6321
6322 @Override public int getScreenDozeCount(int which) {
6323 return mScreenDozeTimer.getCountLocked(which);
6324 }
6325
Mathew Inwoodc185f082018-08-20 14:28:54 +01006326 @UnsupportedAppUsage
Dianne Hackborn617f8772009-03-31 15:04:46 -07006327 @Override public long getScreenBrightnessTime(int brightnessBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006328 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006329 return mScreenBrightnessTimer[brightnessBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006330 elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006331 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006332
Kweku Adams87b19ec2017-10-09 12:40:03 -07006333 @Override public Timer getScreenBrightnessTimer(int brightnessBin) {
6334 return mScreenBrightnessTimer[brightnessBin];
6335 }
6336
Jeff Browne95c3cd2014-05-02 16:59:26 -07006337 @Override public long getInteractiveTime(long elapsedRealtimeUs, int which) {
6338 return mInteractiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006339 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006340
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006341 @Override public long getPowerSaveModeEnabledTime(long elapsedRealtimeUs, int which) {
6342 return mPowerSaveModeEnabledTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07006343 }
6344
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006345 @Override public int getPowerSaveModeEnabledCount(int which) {
6346 return mPowerSaveModeEnabledTimer.getCountLocked(which);
6347 }
6348
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006349 @Override public long getDeviceIdleModeTime(int mode, long elapsedRealtimeUs,
6350 int which) {
6351 switch (mode) {
6352 case DEVICE_IDLE_MODE_LIGHT:
6353 return mDeviceIdleModeLightTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006354 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006355 return mDeviceIdleModeFullTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6356 }
6357 return 0;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006358 }
6359
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006360 @Override public int getDeviceIdleModeCount(int mode, int which) {
6361 switch (mode) {
6362 case DEVICE_IDLE_MODE_LIGHT:
6363 return mDeviceIdleModeLightTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006364 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006365 return mDeviceIdleModeFullTimer.getCountLocked(which);
6366 }
6367 return 0;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07006368 }
6369
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006370 @Override public long getLongestDeviceIdleModeTime(int mode) {
6371 switch (mode) {
6372 case DEVICE_IDLE_MODE_LIGHT:
6373 return mLongestLightIdleTime;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006374 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006375 return mLongestFullIdleTime;
6376 }
6377 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07006378 }
6379
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006380 @Override public long getDeviceIdlingTime(int mode, long elapsedRealtimeUs, int which) {
6381 switch (mode) {
6382 case DEVICE_IDLE_MODE_LIGHT:
6383 return mDeviceLightIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006384 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006385 return mDeviceIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6386 }
6387 return 0;
6388 }
6389
6390 @Override public int getDeviceIdlingCount(int mode, int which) {
6391 switch (mode) {
6392 case DEVICE_IDLE_MODE_LIGHT:
6393 return mDeviceLightIdlingTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006394 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006395 return mDeviceIdlingTimer.getCountLocked(which);
6396 }
6397 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07006398 }
6399
Dianne Hackborn1e01d162014-12-04 17:46:42 -08006400 @Override public int getNumConnectivityChange(int which) {
6401 int val = mNumConnectivityChange;
6402 if (which == STATS_CURRENT) {
6403 val -= mLoadedNumConnectivityChange;
6404 } else if (which == STATS_SINCE_UNPLUGGED) {
6405 val -= mUnpluggedNumConnectivityChange;
6406 }
6407 return val;
6408 }
6409
Siddharth Ray78ccaf52017-12-23 16:16:21 -08006410 @Override public long getGpsSignalQualityTime(int strengthBin,
6411 long elapsedRealtimeUs, int which) {
6412 if (strengthBin < 0 || strengthBin >= GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS) {
6413 return 0;
6414 }
6415 return mGpsSignalQualityTimer[strengthBin].getTotalTimeLocked(
6416 elapsedRealtimeUs, which);
6417 }
6418
6419 @Override public long getGpsBatteryDrainMaMs() {
Siddharth Ray0ed2e952018-01-22 11:32:14 -08006420 final double opVolt = mPowerProfile.getAveragePower(
6421 PowerProfile.POWER_GPS_OPERATING_VOLTAGE) / 1000.0;
6422 if (opVolt == 0) {
6423 return 0;
6424 }
6425 double energyUsedMaMs = 0.0;
6426 final int which = STATS_SINCE_CHARGED;
6427 final long rawRealtime = SystemClock.elapsedRealtime() * 1000;
6428 for(int i=0; i < GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
6429 energyUsedMaMs
6430 += mPowerProfile.getAveragePower(PowerProfile.POWER_GPS_SIGNAL_QUALITY_BASED, i)
6431 * (getGpsSignalQualityTime(i, rawRealtime, which) / 1000);
6432 }
6433 return (long) energyUsedMaMs;
Siddharth Ray78ccaf52017-12-23 16:16:21 -08006434 }
6435
Mathew Inwoodc185f082018-08-20 14:28:54 +01006436 @UnsupportedAppUsage
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006437 @Override public long getPhoneOnTime(long elapsedRealtimeUs, int which) {
6438 return mPhoneOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006439 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006440
Dianne Hackborn77b987f2014-02-26 16:20:52 -08006441 @Override public int getPhoneOnCount(int which) {
6442 return mPhoneOnTimer.getCountLocked(which);
6443 }
6444
Mathew Inwoodc185f082018-08-20 14:28:54 +01006445 @UnsupportedAppUsage
Dianne Hackborn627bba72009-03-24 22:32:56 -07006446 @Override public long getPhoneSignalStrengthTime(int strengthBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006447 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006448 return mPhoneSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006449 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07006450 }
Amith Yamasanif37447b2009-10-08 18:28:01 -07006451
Mathew Inwoodc185f082018-08-20 14:28:54 +01006452 @UnsupportedAppUsage
Amith Yamasanif37447b2009-10-08 18:28:01 -07006453 @Override public long getPhoneSignalScanningTime(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006454 long elapsedRealtimeUs, int which) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07006455 return mPhoneSignalScanningTimer.getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006456 elapsedRealtimeUs, which);
Amith Yamasanif37447b2009-10-08 18:28:01 -07006457 }
6458
Kweku Adams87b19ec2017-10-09 12:40:03 -07006459 @Override public Timer getPhoneSignalScanningTimer() {
6460 return mPhoneSignalScanningTimer;
6461 }
6462
Mathew Inwoodc185f082018-08-20 14:28:54 +01006463 @UnsupportedAppUsage
Catherine Liufb900812012-07-17 14:12:56 -05006464 @Override public int getPhoneSignalStrengthCount(int strengthBin, int which) {
6465 return mPhoneSignalStrengthsTimer[strengthBin].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006466 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006467
Kweku Adams87b19ec2017-10-09 12:40:03 -07006468 @Override public Timer getPhoneSignalStrengthTimer(int strengthBin) {
6469 return mPhoneSignalStrengthsTimer[strengthBin];
6470 }
6471
Mathew Inwoodc185f082018-08-20 14:28:54 +01006472 @UnsupportedAppUsage
Dianne Hackborn627bba72009-03-24 22:32:56 -07006473 @Override public long getPhoneDataConnectionTime(int dataType,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006474 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006475 return mPhoneDataConnectionsTimer[dataType].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006476 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07006477 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006478
Mathew Inwoodc185f082018-08-20 14:28:54 +01006479 @UnsupportedAppUsage
Dianne Hackborn617f8772009-03-31 15:04:46 -07006480 @Override public int getPhoneDataConnectionCount(int dataType, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006481 return mPhoneDataConnectionsTimer[dataType].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006482 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006483
Kweku Adams87b19ec2017-10-09 12:40:03 -07006484 @Override public Timer getPhoneDataConnectionTimer(int dataType) {
6485 return mPhoneDataConnectionsTimer[dataType];
6486 }
6487
Mathew Inwoodc185f082018-08-20 14:28:54 +01006488 @UnsupportedAppUsage
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006489 @Override public long getMobileRadioActiveTime(long elapsedRealtimeUs, int which) {
6490 return mMobileRadioActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborne13c4c02014-02-11 17:18:35 -08006491 }
6492
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006493 @Override public int getMobileRadioActiveCount(int which) {
6494 return mMobileRadioActiveTimer.getCountLocked(which);
6495 }
6496
Dianne Hackborna1bd7922014-03-21 11:07:11 -07006497 @Override public long getMobileRadioActiveAdjustedTime(int which) {
6498 return mMobileRadioActiveAdjustedTime.getCountLocked(which);
6499 }
6500
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006501 @Override public long getMobileRadioActiveUnknownTime(int which) {
6502 return mMobileRadioActiveUnknownTime.getCountLocked(which);
6503 }
6504
6505 @Override public int getMobileRadioActiveUnknownCount(int which) {
6506 return (int)mMobileRadioActiveUnknownCount.getCountLocked(which);
6507 }
6508
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006509 @Override public long getWifiMulticastWakelockTime(
6510 long elapsedRealtimeUs, int which) {
6511 return mWifiMulticastWakelockTimer.getTotalTimeLocked(
6512 elapsedRealtimeUs, which);
6513 }
6514
6515 @Override public int getWifiMulticastWakelockCount(int which) {
6516 return mWifiMulticastWakelockTimer.getCountLocked(which);
6517 }
6518
Mathew Inwoodc185f082018-08-20 14:28:54 +01006519 @UnsupportedAppUsage
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006520 @Override public long getWifiOnTime(long elapsedRealtimeUs, int which) {
6521 return mWifiOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07006522 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006523
Siddharth Rayb50a6842017-12-14 15:15:28 -08006524 @Override public long getWifiActiveTime(long elapsedRealtimeUs, int which) {
6525 return mWifiActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6526 }
6527
Mathew Inwoodc185f082018-08-20 14:28:54 +01006528 @UnsupportedAppUsage
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006529 @Override public long getGlobalWifiRunningTime(long elapsedRealtimeUs, int which) {
6530 return mGlobalWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07006531 }
6532
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006533 @Override public long getWifiStateTime(int wifiState,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006534 long elapsedRealtimeUs, int which) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006535 return mWifiStateTimer[wifiState].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006536 elapsedRealtimeUs, which);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006537 }
6538
6539 @Override public int getWifiStateCount(int wifiState, int which) {
6540 return mWifiStateTimer[wifiState].getCountLocked(which);
6541 }
6542
Kweku Adams87b19ec2017-10-09 12:40:03 -07006543 @Override public Timer getWifiStateTimer(int wifiState) {
6544 return mWifiStateTimer[wifiState];
6545 }
6546
Dianne Hackborn3251b902014-06-20 14:40:53 -07006547 @Override public long getWifiSupplStateTime(int state,
6548 long elapsedRealtimeUs, int which) {
6549 return mWifiSupplStateTimer[state].getTotalTimeLocked(
6550 elapsedRealtimeUs, which);
6551 }
6552
6553 @Override public int getWifiSupplStateCount(int state, int which) {
6554 return mWifiSupplStateTimer[state].getCountLocked(which);
6555 }
6556
Kweku Adams87b19ec2017-10-09 12:40:03 -07006557 @Override public Timer getWifiSupplStateTimer(int state) {
6558 return mWifiSupplStateTimer[state];
6559 }
6560
Dianne Hackborn3251b902014-06-20 14:40:53 -07006561 @Override public long getWifiSignalStrengthTime(int strengthBin,
6562 long elapsedRealtimeUs, int which) {
6563 return mWifiSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
6564 elapsedRealtimeUs, which);
6565 }
6566
6567 @Override public int getWifiSignalStrengthCount(int strengthBin, int which) {
6568 return mWifiSignalStrengthsTimer[strengthBin].getCountLocked(which);
6569 }
6570
Kweku Adams87b19ec2017-10-09 12:40:03 -07006571 @Override public Timer getWifiSignalStrengthTimer(int strengthBin) {
6572 return mWifiSignalStrengthsTimer[strengthBin];
6573 }
6574
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006575 @Override
6576 public ControllerActivityCounter getBluetoothControllerActivity() {
6577 return mBluetoothActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07006578 }
6579
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006580 @Override
6581 public ControllerActivityCounter getWifiControllerActivity() {
6582 return mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -07006583 }
6584
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006585 @Override
6586 public ControllerActivityCounter getModemControllerActivity() {
6587 return mModemActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07006588 }
6589
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006590 @Override
6591 public boolean hasBluetoothActivityReporting() {
6592 return mHasBluetoothReporting;
6593 }
6594
6595 @Override
6596 public boolean hasWifiActivityReporting() {
6597 return mHasWifiReporting;
6598 }
6599
6600 @Override
6601 public boolean hasModemActivityReporting() {
6602 return mHasModemReporting;
Adam Lesinski33dac552015-03-09 15:24:48 -07006603 }
6604
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006605 @Override
6606 public long getFlashlightOnTime(long elapsedRealtimeUs, int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07006607 return mFlashlightOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6608 }
6609
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006610 @Override
6611 public long getFlashlightOnCount(int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07006612 return mFlashlightOnTimer.getCountLocked(which);
6613 }
6614
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006615 @Override
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006616 public long getCameraOnTime(long elapsedRealtimeUs, int which) {
6617 return mCameraOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6618 }
6619
6620 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006621 public long getBluetoothScanTime(long elapsedRealtimeUs, int which) {
6622 return mBluetoothScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6623 }
6624
6625 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01006626 @UnsupportedAppUsage
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006627 public long getNetworkActivityBytes(int type, int which) {
6628 if (type >= 0 && type < mNetworkByteActivityCounters.length) {
6629 return mNetworkByteActivityCounters[type].getCountLocked(which);
6630 } else {
6631 return 0;
6632 }
6633 }
6634
6635 @Override
6636 public long getNetworkActivityPackets(int type, int which) {
6637 if (type >= 0 && type < mNetworkPacketActivityCounters.length) {
6638 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006639 } else {
6640 return 0;
6641 }
6642 }
6643
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08006644 @Override public long getStartClockTime() {
Dianne Hackbornd48954f2015-07-22 17:20:33 -07006645 final long currentTime = System.currentTimeMillis();
6646 if (ensureStartClockTime(currentTime)) {
Joe Onoratoabded112016-02-08 16:49:39 -08006647 recordCurrentTimeChangeLocked(currentTime, mClocks.elapsedRealtime(),
6648 mClocks.uptimeMillis());
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07006649 }
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08006650 return mStartClockTime;
6651 }
6652
Dianne Hackborncd0e3352014-08-07 17:08:09 -07006653 @Override public String getStartPlatformVersion() {
6654 return mStartPlatformVersion;
6655 }
6656
6657 @Override public String getEndPlatformVersion() {
6658 return mEndPlatformVersion;
6659 }
6660
6661 @Override public int getParcelVersion() {
6662 return VERSION;
6663 }
6664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006665 @Override public boolean getIsOnBattery() {
6666 return mOnBattery;
6667 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006668
Mathew Inwoodc185f082018-08-20 14:28:54 +01006669 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006670 @Override public SparseArray<? extends BatteryStats.Uid> getUidStats() {
6671 return mUidStats;
6672 }
6673
Adam Lesinski5f056f62016-07-14 16:56:08 -07006674 private static void detachTimerIfNotNull(BatteryStatsImpl.Timer timer) {
6675 if (timer != null) {
6676 timer.detach();
6677 }
6678 }
6679
6680 private static boolean resetTimerIfNotNull(BatteryStatsImpl.Timer timer,
6681 boolean detachIfReset) {
6682 if (timer != null) {
6683 return timer.reset(detachIfReset);
6684 }
6685 return true;
6686 }
6687
Bookatz867c0d72017-03-07 18:23:42 -08006688 private static boolean resetTimerIfNotNull(DualTimer timer, boolean detachIfReset) {
6689 if (timer != null) {
6690 return timer.reset(detachIfReset);
6691 }
6692 return true;
6693 }
6694
Adam Lesinski5f056f62016-07-14 16:56:08 -07006695 private static void detachLongCounterIfNotNull(LongSamplingCounter counter) {
6696 if (counter != null) {
6697 counter.detach();
6698 }
6699 }
6700
6701 private static void resetLongCounterIfNotNull(LongSamplingCounter counter,
6702 boolean detachIfReset) {
6703 if (counter != null) {
6704 counter.reset(detachIfReset);
6705 }
6706 }
6707
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006708 /**
6709 * The statistics associated with a particular uid.
6710 */
Joe Onoratoabded112016-02-08 16:49:39 -08006711 public static class Uid extends BatteryStats.Uid {
6712 /**
6713 * BatteryStatsImpl that we are associated with.
6714 */
6715 protected BatteryStatsImpl mBsi;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006717 final int mUid;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006718
Bookatz867c0d72017-03-07 18:23:42 -08006719 /** TimeBase for when uid is in background and device is on battery. */
6720 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6721 public final TimeBase mOnBatteryBackgroundTimeBase;
Bookatzc8c44962017-05-11 12:12:54 -07006722 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6723 public final TimeBase mOnBatteryScreenOffBackgroundTimeBase;
Bookatz867c0d72017-03-07 18:23:42 -08006724
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006725 boolean mWifiRunning;
6726 StopwatchTimer mWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006727
The Android Open Source Project10592532009-03-18 17:39:46 -07006728 boolean mFullWifiLockOut;
Evan Millarc64edde2009-04-18 12:26:32 -07006729 StopwatchTimer mFullWifiLockTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006730
Nick Pelly6ccaa542012-06-15 15:22:47 -07006731 boolean mWifiScanStarted;
Bookatz867c0d72017-03-07 18:23:42 -08006732 DualTimer mWifiScanTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006733
Dianne Hackborn61659e52014-07-09 16:13:01 -07006734 static final int NO_BATCHED_SCAN_STARTED = -1;
Robert Greenwalta029ea12013-09-25 16:38:12 -07006735 int mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
6736 StopwatchTimer[] mWifiBatchedScanTimer;
6737
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006738 boolean mWifiMulticastEnabled;
6739 StopwatchTimer mWifiMulticastTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006740
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006741 StopwatchTimer mAudioTurnedOnTimer;
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006742 StopwatchTimer mVideoTurnedOnTimer;
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006743 StopwatchTimer mFlashlightTurnedOnTimer;
6744 StopwatchTimer mCameraTurnedOnTimer;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006745 StopwatchTimer mForegroundActivityTimer;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006746 StopwatchTimer mForegroundServiceTimer;
Bookatzc8c44962017-05-11 12:12:54 -07006747 /** Total time spent by the uid holding any partial wakelocks. */
6748 DualTimer mAggregatedPartialWakelockTimer;
Bookatz867c0d72017-03-07 18:23:42 -08006749 DualTimer mBluetoothScanTimer;
Bookatzb1f04f32017-05-19 13:57:32 -07006750 DualTimer mBluetoothUnoptimizedScanTimer;
Bookatz956f36bf2017-04-28 09:48:17 -07006751 Counter mBluetoothScanResultCounter;
Bookatzb1f04f32017-05-19 13:57:32 -07006752 Counter mBluetoothScanResultBgCounter;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006753
Dianne Hackborna8d10942015-11-19 17:55:19 -08006754 int mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07006755 StopwatchTimer[] mProcessStateTimer;
6756
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006757 boolean mInForegroundService = false;
6758
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006759 BatchTimer mVibratorOnTimer;
6760
Dianne Hackborn617f8772009-03-31 15:04:46 -07006761 Counter[] mUserActivityCounters;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006762
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006763 LongSamplingCounter[] mNetworkByteActivityCounters;
6764 LongSamplingCounter[] mNetworkPacketActivityCounters;
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006765 LongSamplingCounter mMobileRadioActiveTime;
6766 LongSamplingCounter mMobileRadioActiveCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006768 /**
Adam Lesinski5f056f62016-07-14 16:56:08 -07006769 * How many times this UID woke up the Application Processor due to a Mobile radio packet.
6770 */
6771 private LongSamplingCounter mMobileRadioApWakeupCount;
6772
6773 /**
6774 * How many times this UID woke up the Application Processor due to a Wifi packet.
6775 */
6776 private LongSamplingCounter mWifiRadioApWakeupCount;
6777
6778 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07006779 * The amount of time this uid has kept the WiFi controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006780 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07006781 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006782 private ControllerActivityCounterImpl mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006783
6784 /**
6785 * The amount of time this uid has kept the Bluetooth controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006786 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07006787 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006788 private ControllerActivityCounterImpl mBluetoothControllerActivity;
6789
6790 /**
6791 * The amount of time this uid has kept the Modem controller in idle, tx, and rx mode.
6792 * Can be null if the UID has had no such activity.
6793 */
6794 private ControllerActivityCounterImpl mModemControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006795
6796 /**
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006797 * The CPU times we had at the last history details update.
6798 */
6799 long mLastStepUserTime;
6800 long mLastStepSystemTime;
6801 long mCurStepUserTime;
6802 long mCurStepSystemTime;
6803
Joe Onoratoabded112016-02-08 16:49:39 -08006804 LongSamplingCounter mUserCpuTime;
6805 LongSamplingCounter mSystemCpuTime;
Sudheer Shankaaf857412017-07-21 00:14:24 -07006806 LongSamplingCounter[][] mCpuClusterSpeedTimesUs;
Mike Ma3d422c32017-10-25 11:08:57 -07006807 LongSamplingCounter mCpuActiveTimeMs;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006808
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006809 LongSamplingCounterArray mCpuFreqTimeMs;
6810 LongSamplingCounterArray mScreenOffCpuFreqTimeMs;
Mike Ma3d422c32017-10-25 11:08:57 -07006811 LongSamplingCounterArray mCpuClusterTimesMs;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006812
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006813 LongSamplingCounterArray[] mProcStateTimeMs;
6814 LongSamplingCounterArray[] mProcStateScreenOffTimeMs;
6815
6816 IntArray mChildUids;
6817
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006818 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006819 * The statistics we have collected for this uid's wake locks.
6820 */
Joe Onoratoabded112016-02-08 16:49:39 -08006821 final OverflowArrayMap<Wakelock> mWakelockStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006822
6823 /**
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006824 * The statistics we have collected for this uid's syncs.
6825 */
Bookatz2bffb5b2017-04-13 11:59:33 -07006826 final OverflowArrayMap<DualTimer> mSyncStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006827
6828 /**
6829 * The statistics we have collected for this uid's jobs.
6830 */
Bookatzaa4594a2017-03-24 12:39:56 -07006831 final OverflowArrayMap<DualTimer> mJobStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006832
6833 /**
Dianne Hackborn94326cb2017-06-28 16:17:20 -07006834 * Count of the jobs that have completed and the reasons why they completed.
6835 */
6836 final ArrayMap<String, SparseIntArray> mJobCompletions = new ArrayMap<>();
6837
6838 /**
Amith Yamasani977e11f2018-02-16 11:29:54 -08006839 * Count of app launch events that had associated deferred job counts or info about
6840 * last time a job was run.
6841 */
6842 Counter mJobsDeferredEventCount;
6843
6844 /**
6845 * Count of deferred jobs that were pending when the app was launched or brought to
6846 * the foreground through a user interaction.
6847 */
6848 Counter mJobsDeferredCount;
6849
6850 /**
6851 * Sum of time since the last time a job was run for this app before it was launched.
6852 */
6853 LongSamplingCounter mJobsFreshnessTimeMs;
6854
6855 /**
6856 * Array of counts of instances where the time since the last job was run for the app
6857 * fell within one of the thresholds in {@link #JOB_FRESHNESS_BUCKETS}.
6858 */
6859 final Counter[] mJobsFreshnessBuckets;
6860
6861 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006862 * The statistics we have collected for this uid's sensor activations.
6863 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006864 final SparseArray<Sensor> mSensorStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006865
6866 /**
6867 * The statistics we have collected for this uid's processes.
6868 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006869 final ArrayMap<String, Proc> mProcessStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006870
6871 /**
6872 * The statistics we have collected for this uid's processes.
6873 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006874 final ArrayMap<String, Pkg> mPackageStats = new ArrayMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006875
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006876 /**
6877 * The transient wake stats we have collected for this uid's pids.
6878 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006879 final SparseArray<Pid> mPids = new SparseArray<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006880
Joe Onoratoabded112016-02-08 16:49:39 -08006881 public Uid(BatteryStatsImpl bsi, int uid) {
6882 mBsi = bsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006883 mUid = uid;
Joe Onoratoabded112016-02-08 16:49:39 -08006884
Bookatz867c0d72017-03-07 18:23:42 -08006885 mOnBatteryBackgroundTimeBase = new TimeBase();
6886 mOnBatteryBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
6887 mBsi.mClocks.elapsedRealtime() * 1000);
6888
Bookatzc8c44962017-05-11 12:12:54 -07006889 mOnBatteryScreenOffBackgroundTimeBase = new TimeBase();
6890 mOnBatteryScreenOffBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
6891 mBsi.mClocks.elapsedRealtime() * 1000);
6892
Joe Onoratoabded112016-02-08 16:49:39 -08006893 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6894 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Mike Ma3d422c32017-10-25 11:08:57 -07006895 mCpuActiveTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6896 mCpuClusterTimesMs = new LongSamplingCounterArray(mBsi.mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006897
Dianne Hackborn657153b2016-07-29 14:54:14 -07006898 mWakelockStats = mBsi.new OverflowArrayMap<Wakelock>(uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006899 @Override public Wakelock instantiateObject() {
6900 return new Wakelock(mBsi, Uid.this);
6901 }
6902 };
Bookatz2bffb5b2017-04-13 11:59:33 -07006903 mSyncStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
6904 @Override public DualTimer instantiateObject() {
6905 return new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
6906 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006907 }
6908 };
Bookatzaa4594a2017-03-24 12:39:56 -07006909 mJobStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
6910 @Override public DualTimer instantiateObject() {
6911 return new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
6912 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006913 }
6914 };
6915
6916 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_RUNNING,
6917 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
6918 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, this, FULL_WIFI_LOCK,
6919 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Bookatz867c0d72017-03-07 18:23:42 -08006920 mWifiScanTimer = new DualTimer(mBsi.mClocks, this, WIFI_SCAN,
6921 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006922 mWifiBatchedScanTimer = new StopwatchTimer[NUM_WIFI_BATCHED_SCAN_BINS];
Joe Onoratoabded112016-02-08 16:49:39 -08006923 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_MULTICAST_ENABLED,
6924 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006925 mProcessStateTimer = new StopwatchTimer[NUM_PROCESS_STATE];
Amith Yamasani977e11f2018-02-16 11:29:54 -08006926 mJobsDeferredEventCount = new Counter(mBsi.mOnBatteryTimeBase);
6927 mJobsDeferredCount = new Counter(mBsi.mOnBatteryTimeBase);
6928 mJobsFreshnessTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6929 mJobsFreshnessBuckets = new Counter[JOB_FRESHNESS_BUCKETS.length];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006930 }
6931
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006932 @VisibleForTesting
6933 public void setProcessStateForTest(int procState) {
6934 mProcessState = procState;
6935 }
6936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006937 @Override
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006938 public long[] getCpuFreqTimes(int which) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006939 return nullIfAllZeros(mCpuFreqTimeMs, which);
6940 }
6941
6942 @Override
6943 public long[] getScreenOffCpuFreqTimes(int which) {
6944 return nullIfAllZeros(mScreenOffCpuFreqTimeMs, which);
6945 }
6946
6947 @Override
Mike Ma3d422c32017-10-25 11:08:57 -07006948 public long getCpuActiveTime() {
6949 return mCpuActiveTimeMs.getCountLocked(STATS_SINCE_CHARGED);
6950 }
6951
6952 @Override
6953 public long[] getCpuClusterTimes() {
6954 return nullIfAllZeros(mCpuClusterTimesMs, STATS_SINCE_CHARGED);
6955 }
6956
6957
6958 @Override
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006959 public long[] getCpuFreqTimes(int which, int procState) {
6960 if (which < 0 || which >= NUM_PROCESS_STATE) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006961 return null;
6962 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006963 if (mProcStateTimeMs == null) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006964 return null;
6965 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006966 if (!mBsi.mPerProcStateCpuTimesAvailable) {
6967 mProcStateTimeMs = null;
6968 return null;
6969 }
6970 return nullIfAllZeros(mProcStateTimeMs[procState], which);
6971 }
6972
6973 @Override
6974 public long[] getScreenOffCpuFreqTimes(int which, int procState) {
6975 if (which < 0 || which >= NUM_PROCESS_STATE) {
6976 return null;
6977 }
6978 if (mProcStateScreenOffTimeMs == null) {
6979 return null;
6980 }
6981 if (!mBsi.mPerProcStateCpuTimesAvailable) {
6982 mProcStateScreenOffTimeMs = null;
6983 return null;
6984 }
6985 return nullIfAllZeros(mProcStateScreenOffTimeMs[procState], which);
6986 }
6987
6988 public void addIsolatedUid(int isolatedUid) {
6989 if (mChildUids == null) {
6990 mChildUids = new IntArray();
6991 } else if (mChildUids.indexOf(isolatedUid) >= 0) {
6992 return;
6993 }
6994 mChildUids.add(isolatedUid);
6995 }
6996
6997 public void removeIsolatedUid(int isolatedUid) {
6998 final int idx = mChildUids == null ? -1 : mChildUids.indexOf(isolatedUid);
6999 if (idx < 0) {
7000 return;
7001 }
7002 mChildUids.remove(idx);
7003 }
7004
7005 private long[] nullIfAllZeros(LongSamplingCounterArray cpuTimesMs, int which) {
7006 if (cpuTimesMs == null) {
7007 return null;
7008 }
7009 final long[] counts = cpuTimesMs.getCountsLocked(which);
7010 if (counts == null) {
7011 return null;
7012 }
7013 // Return counts only if at least one of the elements is non-zero.
7014 for (int i = counts.length - 1; i >= 0; --i) {
7015 if (counts[i] != 0) {
7016 return counts;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007017 }
7018 }
7019 return null;
7020 }
7021
Sudheer Shankae544d162017-12-28 17:06:20 -08007022 private void addProcStateTimesMs(int procState, long[] cpuTimesMs, boolean onBattery) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007023 if (mProcStateTimeMs == null) {
7024 mProcStateTimeMs = new LongSamplingCounterArray[NUM_PROCESS_STATE];
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007025 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007026 if (mProcStateTimeMs[procState] == null
7027 || mProcStateTimeMs[procState].getSize() != cpuTimesMs.length) {
7028 mProcStateTimeMs[procState] = new LongSamplingCounterArray(
7029 mBsi.mOnBatteryTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007030 }
Sudheer Shankae544d162017-12-28 17:06:20 -08007031 mProcStateTimeMs[procState].addCountLocked(cpuTimesMs, onBattery);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007032 }
7033
Sudheer Shankae544d162017-12-28 17:06:20 -08007034 private void addProcStateScreenOffTimesMs(int procState, long[] cpuTimesMs,
7035 boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007036 if (mProcStateScreenOffTimeMs == null) {
7037 mProcStateScreenOffTimeMs = new LongSamplingCounterArray[NUM_PROCESS_STATE];
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007038 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007039 if (mProcStateScreenOffTimeMs[procState] == null
7040 || mProcStateScreenOffTimeMs[procState].getSize() != cpuTimesMs.length) {
7041 mProcStateScreenOffTimeMs[procState] = new LongSamplingCounterArray(
7042 mBsi.mOnBatteryScreenOffTimeBase);
7043 }
Sudheer Shankae544d162017-12-28 17:06:20 -08007044 mProcStateScreenOffTimeMs[procState].addCountLocked(cpuTimesMs, onBatteryScreenOff);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007045 }
7046
7047 @Override
Bookatzc8c44962017-05-11 12:12:54 -07007048 public Timer getAggregatedPartialWakelockTimer() {
7049 return mAggregatedPartialWakelockTimer;
7050 }
7051
7052 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01007053 @UnsupportedAppUsage
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007054 public ArrayMap<String, ? extends BatteryStats.Uid.Wakelock> getWakelockStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007055 return mWakelockStats.getMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007056 }
7057
7058 @Override
Ahmed ElArabawyddd09692017-10-30 17:58:29 -07007059 public Timer getMulticastWakelockStats() {
7060 return mWifiMulticastTimer;
7061 }
7062
7063 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007064 public ArrayMap<String, ? extends BatteryStats.Timer> getSyncStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007065 return mSyncStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007066 }
7067
7068 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007069 public ArrayMap<String, ? extends BatteryStats.Timer> getJobStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007070 return mJobStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007071 }
7072
7073 @Override
Dianne Hackborn94326cb2017-06-28 16:17:20 -07007074 public ArrayMap<String, SparseIntArray> getJobCompletionStats() {
7075 return mJobCompletions;
7076 }
7077
7078 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01007079 @UnsupportedAppUsage
Dianne Hackborn61659e52014-07-09 16:13:01 -07007080 public SparseArray<? extends BatteryStats.Uid.Sensor> getSensorStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007081 return mSensorStats;
7082 }
7083
7084 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01007085 @UnsupportedAppUsage
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007086 public ArrayMap<String, ? extends BatteryStats.Uid.Proc> getProcessStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007087 return mProcessStats;
7088 }
7089
7090 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007091 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg> getPackageStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007092 return mPackageStats;
7093 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007094
7095 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01007096 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007097 public int getUid() {
7098 return mUid;
7099 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007100
7101 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007102 public void noteWifiRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007103 if (!mWifiRunning) {
7104 mWifiRunning = true;
7105 if (mWifiRunningTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007106 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
7107 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007108 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007109 mWifiRunningTimer.startRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007110 }
7111 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007112
Dianne Hackborn617f8772009-03-31 15:04:46 -07007113 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007114 public void noteWifiStoppedLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007115 if (mWifiRunning) {
7116 mWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007117 mWifiRunningTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007118 }
7119 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007120
Dianne Hackborn617f8772009-03-31 15:04:46 -07007121 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007122 public void noteFullWifiLockAcquiredLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07007123 if (!mFullWifiLockOut) {
7124 mFullWifiLockOut = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007125 if (mFullWifiLockTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007126 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
7127 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007128 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007129 mFullWifiLockTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007130 }
7131 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007132
The Android Open Source Project10592532009-03-18 17:39:46 -07007133 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007134 public void noteFullWifiLockReleasedLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07007135 if (mFullWifiLockOut) {
7136 mFullWifiLockOut = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007137 mFullWifiLockTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007138 }
7139 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007140
The Android Open Source Project10592532009-03-18 17:39:46 -07007141 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007142 public void noteWifiScanStartedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007143 if (!mWifiScanStarted) {
7144 mWifiScanStarted = true;
7145 if (mWifiScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007146 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
7147 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase,
7148 mOnBatteryBackgroundTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007149 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007150 mWifiScanTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007151 }
7152 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007153
The Android Open Source Project10592532009-03-18 17:39:46 -07007154 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007155 public void noteWifiScanStoppedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007156 if (mWifiScanStarted) {
7157 mWifiScanStarted = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007158 mWifiScanTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007159 }
7160 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007161
7162 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007163 public void noteWifiBatchedScanStartedLocked(int csph, long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007164 int bin = 0;
Navtej Singh Mann3c0ce5c2015-06-11 16:53:11 -07007165 while (csph > 8 && bin < NUM_WIFI_BATCHED_SCAN_BINS-1) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007166 csph = csph >> 3;
7167 bin++;
7168 }
7169
7170 if (mWifiBatchedScanBinStarted == bin) return;
7171
7172 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
7173 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007174 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007175 }
7176 mWifiBatchedScanBinStarted = bin;
7177 if (mWifiBatchedScanTimer[bin] == null) {
7178 makeWifiBatchedScanBin(bin, null);
7179 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007180 mWifiBatchedScanTimer[bin].startRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007181 }
7182
7183 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007184 public void noteWifiBatchedScanStoppedLocked(long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007185 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
7186 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007187 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007188 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
7189 }
7190 }
7191
7192 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007193 public void noteWifiMulticastEnabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007194 if (!mWifiMulticastEnabled) {
7195 mWifiMulticastEnabled = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007196 if (mWifiMulticastTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007197 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7198 WIFI_MULTICAST_ENABLED, mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007199 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007200 mWifiMulticastTimer.startRunningLocked(elapsedRealtimeMs);
Tej Singh4503e102018-01-04 14:35:01 -08007201 StatsLog.write_non_chained(
Bookatz90867622018-01-31 15:05:57 -08007202 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED, getUid(), null,
7203 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED__STATE__ON);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007204 }
7205 }
7206
7207 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007208 public void noteWifiMulticastDisabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007209 if (mWifiMulticastEnabled) {
7210 mWifiMulticastEnabled = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007211 mWifiMulticastTimer.stopRunningLocked(elapsedRealtimeMs);
Tej Singh4503e102018-01-04 14:35:01 -08007212 StatsLog.write_non_chained(
Bookatz90867622018-01-31 15:05:57 -08007213 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED, getUid(), null,
7214 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED__STATE__OFF);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007215 }
7216 }
7217
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007218 @Override
7219 public ControllerActivityCounter getWifiControllerActivity() {
7220 return mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07007221 }
7222
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007223 @Override
7224 public ControllerActivityCounter getBluetoothControllerActivity() {
7225 return mBluetoothControllerActivity;
7226 }
7227
7228 @Override
7229 public ControllerActivityCounter getModemControllerActivity() {
7230 return mModemControllerActivity;
7231 }
7232
7233 public ControllerActivityCounterImpl getOrCreateWifiControllerActivityLocked() {
7234 if (mWifiControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007235 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007236 NUM_BT_TX_LEVELS);
Adam Lesinski50e47602015-12-04 17:04:54 -08007237 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007238 return mWifiControllerActivity;
7239 }
7240
7241 public ControllerActivityCounterImpl getOrCreateBluetoothControllerActivityLocked() {
7242 if (mBluetoothControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007243 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007244 NUM_BT_TX_LEVELS);
7245 }
7246 return mBluetoothControllerActivity;
7247 }
7248
7249 public ControllerActivityCounterImpl getOrCreateModemControllerActivityLocked() {
7250 if (mModemControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007251 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007252 ModemActivityInfo.TX_POWER_LEVELS);
7253 }
7254 return mModemControllerActivity;
Adam Lesinski50e47602015-12-04 17:04:54 -08007255 }
7256
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007257 public StopwatchTimer createAudioTurnedOnTimerLocked() {
7258 if (mAudioTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007259 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
7260 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007261 }
7262 return mAudioTurnedOnTimer;
7263 }
7264
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007265 public void noteAudioTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007266 createAudioTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
7267 }
7268
7269 public void noteAudioTurnedOffLocked(long elapsedRealtimeMs) {
7270 if (mAudioTurnedOnTimer != null) {
7271 mAudioTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007272 }
7273 }
7274
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007275 public void noteResetAudioLocked(long elapsedRealtimeMs) {
7276 if (mAudioTurnedOnTimer != null) {
7277 mAudioTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007278 }
7279 }
7280
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007281 public StopwatchTimer createVideoTurnedOnTimerLocked() {
7282 if (mVideoTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007283 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
7284 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007285 }
7286 return mVideoTurnedOnTimer;
7287 }
7288
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007289 public void noteVideoTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007290 createVideoTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
7291 }
7292
7293 public void noteVideoTurnedOffLocked(long elapsedRealtimeMs) {
7294 if (mVideoTurnedOnTimer != null) {
7295 mVideoTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007296 }
7297 }
7298
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007299 public void noteResetVideoLocked(long elapsedRealtimeMs) {
7300 if (mVideoTurnedOnTimer != null) {
7301 mVideoTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007302 }
7303 }
7304
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007305 public StopwatchTimer createFlashlightTurnedOnTimerLocked() {
7306 if (mFlashlightTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007307 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7308 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007309 }
7310 return mFlashlightTurnedOnTimer;
7311 }
7312
7313 public void noteFlashlightTurnedOnLocked(long elapsedRealtimeMs) {
7314 createFlashlightTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
7315 }
7316
7317 public void noteFlashlightTurnedOffLocked(long elapsedRealtimeMs) {
7318 if (mFlashlightTurnedOnTimer != null) {
7319 mFlashlightTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
7320 }
7321 }
7322
7323 public void noteResetFlashlightLocked(long elapsedRealtimeMs) {
7324 if (mFlashlightTurnedOnTimer != null) {
7325 mFlashlightTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
7326 }
7327 }
7328
7329 public StopwatchTimer createCameraTurnedOnTimerLocked() {
7330 if (mCameraTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007331 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
7332 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007333 }
7334 return mCameraTurnedOnTimer;
7335 }
7336
7337 public void noteCameraTurnedOnLocked(long elapsedRealtimeMs) {
7338 createCameraTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
7339 }
7340
7341 public void noteCameraTurnedOffLocked(long elapsedRealtimeMs) {
7342 if (mCameraTurnedOnTimer != null) {
7343 mCameraTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
7344 }
7345 }
7346
7347 public void noteResetCameraLocked(long elapsedRealtimeMs) {
7348 if (mCameraTurnedOnTimer != null) {
7349 mCameraTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
7350 }
7351 }
7352
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007353 public StopwatchTimer createForegroundActivityTimerLocked() {
7354 if (mForegroundActivityTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007355 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7356 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007357 }
7358 return mForegroundActivityTimer;
7359 }
7360
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007361 public StopwatchTimer createForegroundServiceTimerLocked() {
7362 if (mForegroundServiceTimer == null) {
7363 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7364 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase);
7365 }
7366 return mForegroundServiceTimer;
7367 }
7368
Bookatzc8c44962017-05-11 12:12:54 -07007369 public DualTimer createAggregatedPartialWakelockTimerLocked() {
7370 if (mAggregatedPartialWakelockTimer == null) {
7371 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
7372 AGGREGATED_WAKE_TYPE_PARTIAL, null,
7373 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase);
7374 }
7375 return mAggregatedPartialWakelockTimer;
7376 }
7377
Bookatz867c0d72017-03-07 18:23:42 -08007378 public DualTimer createBluetoothScanTimerLocked() {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007379 if (mBluetoothScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007380 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
7381 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
7382 mOnBatteryBackgroundTimeBase);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007383 }
7384 return mBluetoothScanTimer;
7385 }
7386
Bookatzb1f04f32017-05-19 13:57:32 -07007387 public DualTimer createBluetoothUnoptimizedScanTimerLocked() {
7388 if (mBluetoothUnoptimizedScanTimer == null) {
7389 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
7390 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
7391 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
7392 }
7393 return mBluetoothUnoptimizedScanTimer;
7394 }
7395
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00007396 public void noteBluetoothScanStartedLocked(long elapsedRealtimeMs,
7397 boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007398 createBluetoothScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatzb1f04f32017-05-19 13:57:32 -07007399 if (isUnoptimized) {
7400 createBluetoothUnoptimizedScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
7401 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007402 }
7403
Bookatz94c5a312017-07-11 16:49:17 -07007404 public void noteBluetoothScanStoppedLocked(long elapsedRealtimeMs, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007405 if (mBluetoothScanTimer != null) {
7406 mBluetoothScanTimer.stopRunningLocked(elapsedRealtimeMs);
7407 }
Bookatz94c5a312017-07-11 16:49:17 -07007408 if (isUnoptimized && mBluetoothUnoptimizedScanTimer != null) {
Bookatzb1f04f32017-05-19 13:57:32 -07007409 mBluetoothUnoptimizedScanTimer.stopRunningLocked(elapsedRealtimeMs);
7410 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007411 }
7412
7413 public void noteResetBluetoothScanLocked(long elapsedRealtimeMs) {
7414 if (mBluetoothScanTimer != null) {
7415 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
7416 }
Bookatzb1f04f32017-05-19 13:57:32 -07007417 if (mBluetoothUnoptimizedScanTimer != null) {
7418 mBluetoothUnoptimizedScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
7419 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007420 }
7421
Bookatz956f36bf2017-04-28 09:48:17 -07007422 public Counter createBluetoothScanResultCounterLocked() {
7423 if (mBluetoothScanResultCounter == null) {
7424 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase);
7425 }
7426 return mBluetoothScanResultCounter;
7427 }
7428
Bookatzb1f04f32017-05-19 13:57:32 -07007429 public Counter createBluetoothScanResultBgCounterLocked() {
7430 if (mBluetoothScanResultBgCounter == null) {
7431 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase);
7432 }
7433 return mBluetoothScanResultBgCounter;
7434 }
7435
Bookatz4ebc0642017-05-11 12:21:19 -07007436 public void noteBluetoothScanResultsLocked(int numNewResults) {
7437 createBluetoothScanResultCounterLocked().addAtomic(numNewResults);
Bookatzb1f04f32017-05-19 13:57:32 -07007438 // Uses background timebase, so the count will only be incremented if uid in background.
7439 createBluetoothScanResultBgCounterLocked().addAtomic(numNewResults);
Bookatz956f36bf2017-04-28 09:48:17 -07007440 }
7441
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007442 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007443 public void noteActivityResumedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007444 // We always start, since we want multiple foreground PIDs to nest
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007445 createForegroundActivityTimerLocked().startRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007446 }
7447
7448 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007449 public void noteActivityPausedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007450 if (mForegroundActivityTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007451 mForegroundActivityTimer.stopRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007452 }
7453 }
7454
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007455 public void noteForegroundServiceResumedLocked(long elapsedRealtimeMs) {
7456 createForegroundServiceTimerLocked().startRunningLocked(elapsedRealtimeMs);
7457 }
7458
7459 public void noteForegroundServicePausedLocked(long elapsedRealtimeMs) {
7460 if (mForegroundServiceTimer != null) {
7461 mForegroundServiceTimer.stopRunningLocked(elapsedRealtimeMs);
7462 }
7463 }
7464
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007465 public BatchTimer createVibratorOnTimerLocked() {
7466 if (mVibratorOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007467 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
7468 mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007469 }
7470 return mVibratorOnTimer;
7471 }
7472
7473 public void noteVibratorOnLocked(long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08007474 createVibratorOnTimerLocked().addDuration(mBsi, durationMillis);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007475 }
7476
7477 public void noteVibratorOffLocked() {
7478 if (mVibratorOnTimer != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007479 mVibratorOnTimer.abortLastDuration(mBsi);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007480 }
7481 }
7482
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007483 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01007484 @UnsupportedAppUsage
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007485 public long getWifiRunningTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007486 if (mWifiRunningTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007487 return 0;
7488 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007489 return mWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007490 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07007491
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007492 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007493 public long getFullWifiLockTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007494 if (mFullWifiLockTimer == null) {
7495 return 0;
7496 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007497 return mFullWifiLockTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07007498 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007499
7500 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01007501 @UnsupportedAppUsage
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007502 public long getWifiScanTime(long elapsedRealtimeUs, int which) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007503 if (mWifiScanTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007504 return 0;
7505 }
Bookatzaa4594a2017-03-24 12:39:56 -07007506 return mWifiScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07007507 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007508
7509 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07007510 public int getWifiScanCount(int which) {
7511 if (mWifiScanTimer == null) {
7512 return 0;
7513 }
Bookatzaa4594a2017-03-24 12:39:56 -07007514 return mWifiScanTimer.getCountLocked(which);
Bookatz867c0d72017-03-07 18:23:42 -08007515 }
7516
7517 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07007518 public Timer getWifiScanTimer() {
7519 return mWifiScanTimer;
7520 }
7521
7522 @Override
Bookatz867c0d72017-03-07 18:23:42 -08007523 public int getWifiScanBackgroundCount(int which) {
Bookatzaa4594a2017-03-24 12:39:56 -07007524 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007525 return 0;
7526 }
7527 return mWifiScanTimer.getSubTimer().getCountLocked(which);
7528 }
7529
7530 @Override
7531 public long getWifiScanActualTime(final long elapsedRealtimeUs) {
7532 if (mWifiScanTimer == null) {
7533 return 0;
7534 }
7535 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
Bookatzaa4594a2017-03-24 12:39:56 -07007536 return mWifiScanTimer.getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Bookatz867c0d72017-03-07 18:23:42 -08007537 }
7538
7539 @Override
7540 public long getWifiScanBackgroundTime(final long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07007541 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007542 return 0;
7543 }
7544 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
7545 return mWifiScanTimer.getSubTimer().getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Dianne Hackborn62793e42015-03-09 11:15:41 -07007546 }
7547
7548 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07007549 public Timer getWifiScanBackgroundTimer() {
7550 if (mWifiScanTimer == null) {
7551 return null;
7552 }
7553 return mWifiScanTimer.getSubTimer();
7554 }
7555
7556 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007557 public long getWifiBatchedScanTime(int csphBin, long elapsedRealtimeUs, int which) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007558 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
7559 if (mWifiBatchedScanTimer[csphBin] == null) {
7560 return 0;
7561 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007562 return mWifiBatchedScanTimer[csphBin].getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007563 }
7564
7565 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07007566 public int getWifiBatchedScanCount(int csphBin, int which) {
7567 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
7568 if (mWifiBatchedScanTimer[csphBin] == null) {
7569 return 0;
7570 }
7571 return mWifiBatchedScanTimer[csphBin].getCountLocked(which);
7572 }
7573
7574 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007575 public long getWifiMulticastTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007576 if (mWifiMulticastTimer == null) {
7577 return 0;
7578 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007579 return mWifiMulticastTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007580 }
7581
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007582 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007583 public Timer getAudioTurnedOnTimer() {
7584 return mAudioTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007585 }
7586
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007587 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007588 public Timer getVideoTurnedOnTimer() {
7589 return mVideoTurnedOnTimer;
7590 }
7591
7592 @Override
7593 public Timer getFlashlightTurnedOnTimer() {
7594 return mFlashlightTurnedOnTimer;
7595 }
7596
7597 @Override
7598 public Timer getCameraTurnedOnTimer() {
7599 return mCameraTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007600 }
7601
Dianne Hackborn617f8772009-03-31 15:04:46 -07007602 @Override
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007603 public Timer getForegroundActivityTimer() {
7604 return mForegroundActivityTimer;
7605 }
7606
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007607 @Override
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007608 public Timer getForegroundServiceTimer() {
7609 return mForegroundServiceTimer;
7610 }
7611
7612 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007613 public Timer getBluetoothScanTimer() {
Bookatzaa4594a2017-03-24 12:39:56 -07007614 return mBluetoothScanTimer;
Bookatz867c0d72017-03-07 18:23:42 -08007615 }
7616
7617 @Override
7618 public Timer getBluetoothScanBackgroundTimer() {
7619 if (mBluetoothScanTimer == null) {
7620 return null;
7621 }
7622 return mBluetoothScanTimer.getSubTimer();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007623 }
7624
Bookatz956f36bf2017-04-28 09:48:17 -07007625 @Override
Bookatzb1f04f32017-05-19 13:57:32 -07007626 public Timer getBluetoothUnoptimizedScanTimer() {
7627 return mBluetoothUnoptimizedScanTimer;
7628 }
7629
7630 @Override
7631 public Timer getBluetoothUnoptimizedScanBackgroundTimer() {
7632 if (mBluetoothUnoptimizedScanTimer == null) {
7633 return null;
7634 }
7635 return mBluetoothUnoptimizedScanTimer.getSubTimer();
7636 }
7637
7638 @Override
Bookatz956f36bf2017-04-28 09:48:17 -07007639 public Counter getBluetoothScanResultCounter() {
7640 return mBluetoothScanResultCounter;
7641 }
7642
Bookatzb1f04f32017-05-19 13:57:32 -07007643 @Override
7644 public Counter getBluetoothScanResultBgCounter() {
7645 return mBluetoothScanResultBgCounter;
7646 }
7647
Dianne Hackborn61659e52014-07-09 16:13:01 -07007648 void makeProcessState(int i, Parcel in) {
7649 if (i < 0 || i >= NUM_PROCESS_STATE) return;
7650
7651 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007652 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
7653 mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007654 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08007655 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
7656 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007657 }
7658 }
7659
7660 @Override
7661 public long getProcessStateTime(int state, long elapsedRealtimeUs, int which) {
7662 if (state < 0 || state >= NUM_PROCESS_STATE) return 0;
7663 if (mProcessStateTimer[state] == null) {
7664 return 0;
7665 }
7666 return mProcessStateTimer[state].getTotalTimeLocked(elapsedRealtimeUs, which);
7667 }
7668
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007669 @Override
Joe Onorato713fec82016-03-04 10:34:02 -08007670 public Timer getProcessStateTimer(int state) {
7671 if (state < 0 || state >= NUM_PROCESS_STATE) return null;
7672 return mProcessStateTimer[state];
7673 }
7674
7675 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007676 public Timer getVibratorOnTimer() {
7677 return mVibratorOnTimer;
7678 }
7679
7680 @Override
Dianne Hackborn617f8772009-03-31 15:04:46 -07007681 public void noteUserActivityLocked(int type) {
7682 if (mUserActivityCounters == null) {
7683 initUserActivityLocked();
7684 }
Jeff Browndf693de2012-07-27 12:03:38 -07007685 if (type >= 0 && type < NUM_USER_ACTIVITY_TYPES) {
7686 mUserActivityCounters[type].stepAtomic();
7687 } else {
7688 Slog.w(TAG, "Unknown user activity type " + type + " was specified.",
7689 new Throwable());
7690 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07007691 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007692
Dianne Hackborn617f8772009-03-31 15:04:46 -07007693 @Override
7694 public boolean hasUserActivity() {
7695 return mUserActivityCounters != null;
7696 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007697
Dianne Hackborn617f8772009-03-31 15:04:46 -07007698 @Override
7699 public int getUserActivityCount(int type, int which) {
7700 if (mUserActivityCounters == null) {
7701 return 0;
7702 }
Evan Millarc64edde2009-04-18 12:26:32 -07007703 return mUserActivityCounters[type].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007704 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007705
Robert Greenwalta029ea12013-09-25 16:38:12 -07007706 void makeWifiBatchedScanBin(int i, Parcel in) {
7707 if (i < 0 || i >= NUM_WIFI_BATCHED_SCAN_BINS) return;
7708
Joe Onoratoabded112016-02-08 16:49:39 -08007709 ArrayList<StopwatchTimer> collected = mBsi.mWifiBatchedScanTimers.get(i);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007710 if (collected == null) {
7711 collected = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08007712 mBsi.mWifiBatchedScanTimers.put(i, collected);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007713 }
7714 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007715 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
7716 collected, mBsi.mOnBatteryTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007717 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08007718 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
7719 collected, mBsi.mOnBatteryTimeBase, in);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007720 }
7721 }
7722
7723
Dianne Hackborn617f8772009-03-31 15:04:46 -07007724 void initUserActivityLocked() {
7725 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
7726 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007727 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007728 }
7729 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007730
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007731 void noteNetworkActivityLocked(int type, long deltaBytes, long deltaPackets) {
7732 if (mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007733 initNetworkActivityLocked();
7734 }
7735 if (type >= 0 && type < NUM_NETWORK_ACTIVITY_TYPES) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007736 mNetworkByteActivityCounters[type].addCountLocked(deltaBytes);
7737 mNetworkPacketActivityCounters[type].addCountLocked(deltaPackets);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007738 } else {
7739 Slog.w(TAG, "Unknown network activity type " + type + " was specified.",
7740 new Throwable());
7741 }
7742 }
7743
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007744 void noteMobileRadioActiveTimeLocked(long batteryUptime) {
7745 if (mNetworkByteActivityCounters == null) {
7746 initNetworkActivityLocked();
7747 }
7748 mMobileRadioActiveTime.addCountLocked(batteryUptime);
7749 mMobileRadioActiveCount.addCountLocked(1);
7750 }
7751
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007752 @Override
7753 public boolean hasNetworkActivity() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007754 return mNetworkByteActivityCounters != null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007755 }
7756
7757 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007758 public long getNetworkActivityBytes(int type, int which) {
7759 if (mNetworkByteActivityCounters != null && type >= 0
7760 && type < mNetworkByteActivityCounters.length) {
7761 return mNetworkByteActivityCounters[type].getCountLocked(which);
7762 } else {
7763 return 0;
7764 }
7765 }
7766
7767 @Override
7768 public long getNetworkActivityPackets(int type, int which) {
7769 if (mNetworkPacketActivityCounters != null && type >= 0
7770 && type < mNetworkPacketActivityCounters.length) {
7771 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007772 } else {
7773 return 0;
7774 }
7775 }
7776
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007777 @Override
7778 public long getMobileRadioActiveTime(int which) {
7779 return mMobileRadioActiveTime != null
7780 ? mMobileRadioActiveTime.getCountLocked(which) : 0;
7781 }
7782
7783 @Override
7784 public int getMobileRadioActiveCount(int which) {
7785 return mMobileRadioActiveCount != null
7786 ? (int)mMobileRadioActiveCount.getCountLocked(which) : 0;
7787 }
7788
Adam Lesinskie08af192015-03-25 16:42:59 -07007789 @Override
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007790 public long getUserCpuTimeUs(int which) {
7791 return mUserCpuTime.getCountLocked(which);
7792 }
7793
7794 @Override
7795 public long getSystemCpuTimeUs(int which) {
7796 return mSystemCpuTime.getCountLocked(which);
7797 }
7798
7799 @Override
Adam Lesinski6832f392015-09-05 18:05:40 -07007800 public long getTimeAtCpuSpeed(int cluster, int step, int which) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07007801 if (mCpuClusterSpeedTimesUs != null) {
7802 if (cluster >= 0 && cluster < mCpuClusterSpeedTimesUs.length) {
7803 final LongSamplingCounter[] cpuSpeedTimesUs = mCpuClusterSpeedTimesUs[cluster];
7804 if (cpuSpeedTimesUs != null) {
7805 if (step >= 0 && step < cpuSpeedTimesUs.length) {
7806 final LongSamplingCounter c = cpuSpeedTimesUs[step];
Adam Lesinski6832f392015-09-05 18:05:40 -07007807 if (c != null) {
7808 return c.getCountLocked(which);
7809 }
7810 }
7811 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007812 }
7813 }
7814 return 0;
7815 }
7816
Adam Lesinski5f056f62016-07-14 16:56:08 -07007817 public void noteMobileRadioApWakeupLocked() {
7818 if (mMobileRadioApWakeupCount == null) {
7819 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7820 }
7821 mMobileRadioApWakeupCount.addCountLocked(1);
7822 }
7823
7824 @Override
7825 public long getMobileRadioApWakeupCount(int which) {
7826 if (mMobileRadioApWakeupCount != null) {
7827 return mMobileRadioApWakeupCount.getCountLocked(which);
7828 }
7829 return 0;
7830 }
7831
7832 public void noteWifiRadioApWakeupLocked() {
7833 if (mWifiRadioApWakeupCount == null) {
7834 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7835 }
7836 mWifiRadioApWakeupCount.addCountLocked(1);
7837 }
7838
7839 @Override
7840 public long getWifiRadioApWakeupCount(int which) {
7841 if (mWifiRadioApWakeupCount != null) {
7842 return mWifiRadioApWakeupCount.getCountLocked(which);
7843 }
7844 return 0;
7845 }
7846
Amith Yamasani977e11f2018-02-16 11:29:54 -08007847 @Override
7848 public void getDeferredJobsCheckinLineLocked(StringBuilder sb, int which) {
7849 sb.setLength(0);
7850 final int deferredEventCount = mJobsDeferredEventCount.getCountLocked(which);
7851 if (deferredEventCount == 0) {
7852 return;
7853 }
7854 final int deferredCount = mJobsDeferredCount.getCountLocked(which);
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007855 final long totalLatency = mJobsFreshnessTimeMs.getCountLocked(which);
Amith Yamasani977e11f2018-02-16 11:29:54 -08007856 sb.append(deferredEventCount); sb.append(',');
7857 sb.append(deferredCount); sb.append(',');
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007858 sb.append(totalLatency);
Amith Yamasani977e11f2018-02-16 11:29:54 -08007859 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
7860 if (mJobsFreshnessBuckets[i] == null) {
7861 sb.append(",0");
7862 } else {
7863 sb.append(",");
7864 sb.append(mJobsFreshnessBuckets[i].getCountLocked(which));
7865 }
7866 }
7867 }
7868
7869 @Override
7870 public void getDeferredJobsLineLocked(StringBuilder sb, int which) {
7871 sb.setLength(0);
7872 final int deferredEventCount = mJobsDeferredEventCount.getCountLocked(which);
7873 if (deferredEventCount == 0) {
7874 return;
7875 }
7876 final int deferredCount = mJobsDeferredCount.getCountLocked(which);
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007877 final long totalLatency = mJobsFreshnessTimeMs.getCountLocked(which);
Amith Yamasani977e11f2018-02-16 11:29:54 -08007878 sb.append("times="); sb.append(deferredEventCount); sb.append(", ");
7879 sb.append("count="); sb.append(deferredCount); sb.append(", ");
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007880 sb.append("totalLatencyMs="); sb.append(totalLatency); sb.append(", ");
Amith Yamasani977e11f2018-02-16 11:29:54 -08007881 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
7882 sb.append("<"); sb.append(JOB_FRESHNESS_BUCKETS[i]); sb.append("ms=");
7883 if (mJobsFreshnessBuckets[i] == null) {
7884 sb.append("0");
7885 } else {
7886 sb.append(mJobsFreshnessBuckets[i].getCountLocked(which));
7887 }
7888 sb.append(" ");
7889 }
7890 }
7891
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007892 void initNetworkActivityLocked() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007893 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
7894 mNetworkPacketActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007895 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007896 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7897 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007898 }
Joe Onoratoabded112016-02-08 16:49:39 -08007899 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7900 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007901 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07007902
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007903 /**
7904 * Clear all stats for this uid. Returns true if the uid is completely
7905 * inactive so can be dropped.
7906 */
Adam Lesinski5f212c82017-03-13 12:25:13 -07007907 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
Bookatz993a0be2017-07-21 09:03:23 -07007908 public boolean reset(long uptime, long realtime) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007909 boolean active = false;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007910
Bookatz993a0be2017-07-21 09:03:23 -07007911 mOnBatteryBackgroundTimeBase.init(uptime, realtime);
7912 mOnBatteryScreenOffBackgroundTimeBase.init(uptime, realtime);
7913
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007914 if (mWifiRunningTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007915 active |= !mWifiRunningTimer.reset(false);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007916 active |= mWifiRunning;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007917 }
7918 if (mFullWifiLockTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007919 active |= !mFullWifiLockTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007920 active |= mFullWifiLockOut;
7921 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07007922 if (mWifiScanTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007923 active |= !mWifiScanTimer.reset(false);
Nick Pelly6ccaa542012-06-15 15:22:47 -07007924 active |= mWifiScanStarted;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007925 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07007926 if (mWifiBatchedScanTimer != null) {
7927 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
7928 if (mWifiBatchedScanTimer[i] != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007929 active |= !mWifiBatchedScanTimer[i].reset(false);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007930 }
7931 }
7932 active |= (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED);
7933 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007934 if (mWifiMulticastTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007935 active |= !mWifiMulticastTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007936 active |= mWifiMulticastEnabled;
7937 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007938
7939 active |= !resetTimerIfNotNull(mAudioTurnedOnTimer, false);
7940 active |= !resetTimerIfNotNull(mVideoTurnedOnTimer, false);
7941 active |= !resetTimerIfNotNull(mFlashlightTurnedOnTimer, false);
7942 active |= !resetTimerIfNotNull(mCameraTurnedOnTimer, false);
7943 active |= !resetTimerIfNotNull(mForegroundActivityTimer, false);
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007944 active |= !resetTimerIfNotNull(mForegroundServiceTimer, false);
Bookatzc8c44962017-05-11 12:12:54 -07007945 active |= !resetTimerIfNotNull(mAggregatedPartialWakelockTimer, false);
Adam Lesinski5f056f62016-07-14 16:56:08 -07007946 active |= !resetTimerIfNotNull(mBluetoothScanTimer, false);
Bookatzb1f04f32017-05-19 13:57:32 -07007947 active |= !resetTimerIfNotNull(mBluetoothUnoptimizedScanTimer, false);
Bookatz956f36bf2017-04-28 09:48:17 -07007948 if (mBluetoothScanResultCounter != null) {
7949 mBluetoothScanResultCounter.reset(false);
7950 }
Bookatzb1f04f32017-05-19 13:57:32 -07007951 if (mBluetoothScanResultBgCounter != null) {
7952 mBluetoothScanResultBgCounter.reset(false);
7953 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007954
Dianne Hackborn61659e52014-07-09 16:13:01 -07007955 if (mProcessStateTimer != null) {
7956 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
7957 if (mProcessStateTimer[i] != null) {
7958 active |= !mProcessStateTimer[i].reset(false);
7959 }
7960 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08007961 active |= (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007962 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007963 if (mVibratorOnTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007964 if (mVibratorOnTimer.reset(false)) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007965 mVibratorOnTimer.detach();
7966 mVibratorOnTimer = null;
7967 } else {
7968 active = true;
7969 }
7970 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007971
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007972 if (mUserActivityCounters != null) {
7973 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
7974 mUserActivityCounters[i].reset(false);
7975 }
7976 }
7977
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007978 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007979 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007980 mNetworkByteActivityCounters[i].reset(false);
7981 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007982 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007983 mMobileRadioActiveTime.reset(false);
7984 mMobileRadioActiveCount.reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007985 }
7986
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007987 if (mWifiControllerActivity != null) {
7988 mWifiControllerActivity.reset(false);
7989 }
Adam Lesinskie08af192015-03-25 16:42:59 -07007990
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07007991 if (mBluetoothControllerActivity != null) {
7992 mBluetoothControllerActivity.reset(false);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007993 }
7994
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07007995 if (mModemControllerActivity != null) {
7996 mModemControllerActivity.reset(false);
Adam Lesinskie08af192015-03-25 16:42:59 -07007997 }
7998
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007999 mUserCpuTime.reset(false);
8000 mSystemCpuTime.reset(false);
Adam Lesinski6832f392015-09-05 18:05:40 -07008001
Sudheer Shankaaf857412017-07-21 00:14:24 -07008002 if (mCpuClusterSpeedTimesUs != null) {
8003 for (LongSamplingCounter[] speeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008004 if (speeds != null) {
8005 for (LongSamplingCounter speed : speeds) {
8006 if (speed != null) {
8007 speed.reset(false);
8008 }
8009 }
8010 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008011 }
8012 }
8013
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008014 if (mCpuFreqTimeMs != null) {
8015 mCpuFreqTimeMs.reset(false);
8016 }
8017 if (mScreenOffCpuFreqTimeMs != null) {
8018 mScreenOffCpuFreqTimeMs.reset(false);
8019 }
8020
Mike Ma3d422c32017-10-25 11:08:57 -07008021 mCpuActiveTimeMs.reset(false);
8022 mCpuClusterTimesMs.reset(false);
8023
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008024 if (mProcStateTimeMs != null) {
8025 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8026 if (counters != null) {
8027 counters.reset(false);
8028 }
8029 }
8030 }
8031 if (mProcStateScreenOffTimeMs != null) {
8032 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8033 if (counters != null) {
8034 counters.reset(false);
8035 }
8036 }
8037 }
8038
Adam Lesinski5f056f62016-07-14 16:56:08 -07008039 resetLongCounterIfNotNull(mMobileRadioApWakeupCount, false);
8040 resetLongCounterIfNotNull(mWifiRadioApWakeupCount, false);
8041
Dianne Hackbornd953c532014-08-16 18:17:38 -07008042 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
8043 for (int iw=wakeStats.size()-1; iw>=0; iw--) {
8044 Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07008045 if (wl.reset()) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008046 wakeStats.removeAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07008047 } else {
8048 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008049 }
8050 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07008051 mWakelockStats.cleanup();
Bookatz2bffb5b2017-04-13 11:59:33 -07008052 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008053 for (int is=syncStats.size()-1; is>=0; is--) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008054 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008055 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008056 syncStats.removeAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008057 timer.detach();
8058 } else {
8059 active = true;
8060 }
8061 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07008062 mSyncStats.cleanup();
Bookatzaa4594a2017-03-24 12:39:56 -07008063 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008064 for (int ij=jobStats.size()-1; ij>=0; ij--) {
Bookatzaa4594a2017-03-24 12:39:56 -07008065 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008066 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008067 jobStats.removeAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008068 timer.detach();
8069 } else {
8070 active = true;
8071 }
8072 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07008073 mJobStats.cleanup();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008074 mJobCompletions.clear();
Amith Yamasani977e11f2018-02-16 11:29:54 -08008075
8076 mJobsDeferredEventCount.reset(false);
8077 mJobsDeferredCount.reset(false);
8078 mJobsFreshnessTimeMs.reset(false);
8079 for (int ij = 0; ij < JOB_FRESHNESS_BUCKETS.length; ij++) {
8080 if (mJobsFreshnessBuckets[ij] != null) {
8081 mJobsFreshnessBuckets[ij].reset(false);
8082 }
8083 }
8084
Dianne Hackborn61659e52014-07-09 16:13:01 -07008085 for (int ise=mSensorStats.size()-1; ise>=0; ise--) {
8086 Sensor s = mSensorStats.valueAt(ise);
8087 if (s.reset()) {
8088 mSensorStats.removeAt(ise);
8089 } else {
8090 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008091 }
8092 }
Amith Yamasani977e11f2018-02-16 11:29:54 -08008093
Dianne Hackborn61659e52014-07-09 16:13:01 -07008094 for (int ip=mProcessStats.size()-1; ip>=0; ip--) {
8095 Proc proc = mProcessStats.valueAt(ip);
Dianne Hackborna8d10942015-11-19 17:55:19 -08008096 proc.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008097 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08008098 mProcessStats.clear();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008099 if (mPids.size() > 0) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008100 for (int i=mPids.size()-1; i>=0; i--) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008101 Pid pid = mPids.valueAt(i);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008102 if (pid.mWakeNesting > 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008103 active = true;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008104 } else {
8105 mPids.removeAt(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008106 }
8107 }
8108 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008109 if (mPackageStats.size() > 0) {
8110 Iterator<Map.Entry<String, Pkg>> it = mPackageStats.entrySet().iterator();
8111 while (it.hasNext()) {
8112 Map.Entry<String, Pkg> pkgEntry = it.next();
8113 Pkg p = pkgEntry.getValue();
8114 p.detach();
8115 if (p.mServiceStats.size() > 0) {
8116 Iterator<Map.Entry<String, Pkg.Serv>> it2
8117 = p.mServiceStats.entrySet().iterator();
8118 while (it2.hasNext()) {
8119 Map.Entry<String, Pkg.Serv> servEntry = it2.next();
8120 servEntry.getValue().detach();
8121 }
8122 }
8123 }
8124 mPackageStats.clear();
8125 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008126
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08008127 mLastStepUserTime = mLastStepSystemTime = 0;
8128 mCurStepUserTime = mCurStepSystemTime = 0;
8129
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008130 if (!active) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008131 if (mWifiRunningTimer != null) {
8132 mWifiRunningTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008133 }
8134 if (mFullWifiLockTimer != null) {
8135 mFullWifiLockTimer.detach();
8136 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008137 if (mWifiScanTimer != null) {
8138 mWifiScanTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008139 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008140 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8141 if (mWifiBatchedScanTimer[i] != null) {
8142 mWifiBatchedScanTimer[i].detach();
8143 }
8144 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008145 if (mWifiMulticastTimer != null) {
8146 mWifiMulticastTimer.detach();
8147 }
8148 if (mAudioTurnedOnTimer != null) {
8149 mAudioTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008150 mAudioTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008151 }
8152 if (mVideoTurnedOnTimer != null) {
8153 mVideoTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008154 mVideoTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008155 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008156 if (mFlashlightTurnedOnTimer != null) {
8157 mFlashlightTurnedOnTimer.detach();
8158 mFlashlightTurnedOnTimer = null;
8159 }
8160 if (mCameraTurnedOnTimer != null) {
8161 mCameraTurnedOnTimer.detach();
8162 mCameraTurnedOnTimer = null;
8163 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008164 if (mForegroundActivityTimer != null) {
8165 mForegroundActivityTimer.detach();
8166 mForegroundActivityTimer = null;
8167 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008168 if (mForegroundServiceTimer != null) {
8169 mForegroundServiceTimer.detach();
8170 mForegroundServiceTimer = null;
8171 }
Bookatzc8c44962017-05-11 12:12:54 -07008172 if (mAggregatedPartialWakelockTimer != null) {
8173 mAggregatedPartialWakelockTimer.detach();
8174 mAggregatedPartialWakelockTimer = null;
8175 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008176 if (mBluetoothScanTimer != null) {
8177 mBluetoothScanTimer.detach();
8178 mBluetoothScanTimer = null;
8179 }
Bookatzb1f04f32017-05-19 13:57:32 -07008180 if (mBluetoothUnoptimizedScanTimer != null) {
8181 mBluetoothUnoptimizedScanTimer.detach();
8182 mBluetoothUnoptimizedScanTimer = null;
8183 }
Bookatz956f36bf2017-04-28 09:48:17 -07008184 if (mBluetoothScanResultCounter != null) {
8185 mBluetoothScanResultCounter.detach();
8186 mBluetoothScanResultCounter = null;
8187 }
Bookatzb1f04f32017-05-19 13:57:32 -07008188 if (mBluetoothScanResultBgCounter != null) {
8189 mBluetoothScanResultBgCounter.detach();
8190 mBluetoothScanResultBgCounter = null;
8191 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008192 if (mUserActivityCounters != null) {
8193 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
8194 mUserActivityCounters[i].detach();
8195 }
8196 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008197 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008198 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008199 mNetworkByteActivityCounters[i].detach();
8200 mNetworkPacketActivityCounters[i].detach();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008201 }
8202 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008203
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008204 if (mWifiControllerActivity != null) {
8205 mWifiControllerActivity.detach();
Adam Lesinskie08af192015-03-25 16:42:59 -07008206 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008207
8208 if (mBluetoothControllerActivity != null) {
8209 mBluetoothControllerActivity.detach();
8210 }
8211
8212 if (mModemControllerActivity != null) {
8213 mModemControllerActivity.detach();
8214 }
8215
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008216 mPids.clear();
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008217
8218 mUserCpuTime.detach();
8219 mSystemCpuTime.detach();
Adam Lesinski6832f392015-09-05 18:05:40 -07008220
Sudheer Shankaaf857412017-07-21 00:14:24 -07008221 if (mCpuClusterSpeedTimesUs != null) {
8222 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008223 if (cpuSpeeds != null) {
8224 for (LongSamplingCounter c : cpuSpeeds) {
8225 if (c != null) {
8226 c.detach();
8227 }
8228 }
8229 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008230 }
8231 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008232
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008233 if (mCpuFreqTimeMs != null) {
8234 mCpuFreqTimeMs.detach();
8235 }
8236 if (mScreenOffCpuFreqTimeMs != null) {
8237 mScreenOffCpuFreqTimeMs.detach();
8238 }
Mike Ma3d422c32017-10-25 11:08:57 -07008239 mCpuActiveTimeMs.detach();
8240 mCpuClusterTimesMs.detach();
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008241
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008242 if (mProcStateTimeMs != null) {
8243 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8244 if (counters != null) {
8245 counters.detach();
8246 }
8247 }
8248 }
8249 if (mProcStateScreenOffTimeMs != null) {
8250 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8251 if (counters != null) {
8252 counters.detach();
8253 }
8254 }
8255 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008256 detachLongCounterIfNotNull(mMobileRadioApWakeupCount);
8257 detachLongCounterIfNotNull(mWifiRadioApWakeupCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008258 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008259
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008260 return !active;
8261 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008262
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008263 void writeJobCompletionsToParcelLocked(Parcel out) {
8264 int NJC = mJobCompletions.size();
8265 out.writeInt(NJC);
8266 for (int ijc=0; ijc<NJC; ijc++) {
8267 out.writeString(mJobCompletions.keyAt(ijc));
8268 SparseIntArray types = mJobCompletions.valueAt(ijc);
8269 int NT = types.size();
8270 out.writeInt(NT);
8271 for (int it=0; it<NT; it++) {
8272 out.writeInt(types.keyAt(it));
8273 out.writeInt(types.valueAt(it));
8274 }
8275 }
8276 }
8277
Bookatz867c0d72017-03-07 18:23:42 -08008278 void writeToParcelLocked(Parcel out, long uptimeUs, long elapsedRealtimeUs) {
8279 mOnBatteryBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatzc8c44962017-05-11 12:12:54 -07008280 mOnBatteryScreenOffBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08008281
Dianne Hackbornd953c532014-08-16 18:17:38 -07008282 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
8283 int NW = wakeStats.size();
Dianne Hackborn61659e52014-07-09 16:13:01 -07008284 out.writeInt(NW);
8285 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008286 out.writeString(wakeStats.keyAt(iw));
8287 Uid.Wakelock wakelock = wakeStats.valueAt(iw);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008288 wakelock.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008289 }
8290
Bookatz2bffb5b2017-04-13 11:59:33 -07008291 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008292 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008293 out.writeInt(NS);
8294 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008295 out.writeString(syncStats.keyAt(is));
Bookatz2bffb5b2017-04-13 11:59:33 -07008296 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008297 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
8298 }
8299
Bookatzaa4594a2017-03-24 12:39:56 -07008300 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008301 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008302 out.writeInt(NJ);
8303 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008304 out.writeString(jobStats.keyAt(ij));
Bookatzaa4594a2017-03-24 12:39:56 -07008305 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008306 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
8307 }
8308
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008309 writeJobCompletionsToParcelLocked(out);
8310
Amith Yamasani977e11f2018-02-16 11:29:54 -08008311 mJobsDeferredEventCount.writeToParcel(out);
8312 mJobsDeferredCount.writeToParcel(out);
8313 mJobsFreshnessTimeMs.writeToParcel(out);
8314 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
8315 Counter.writeCounterToParcel(out, mJobsFreshnessBuckets[i]);
8316 }
8317
Dianne Hackborn61659e52014-07-09 16:13:01 -07008318 int NSE = mSensorStats.size();
8319 out.writeInt(NSE);
8320 for (int ise=0; ise<NSE; ise++) {
8321 out.writeInt(mSensorStats.keyAt(ise));
8322 Uid.Sensor sensor = mSensorStats.valueAt(ise);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008323 sensor.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008324 }
8325
Dianne Hackborn61659e52014-07-09 16:13:01 -07008326 int NP = mProcessStats.size();
8327 out.writeInt(NP);
8328 for (int ip=0; ip<NP; ip++) {
8329 out.writeString(mProcessStats.keyAt(ip));
8330 Uid.Proc proc = mProcessStats.valueAt(ip);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008331 proc.writeToParcelLocked(out);
8332 }
8333
8334 out.writeInt(mPackageStats.size());
8335 for (Map.Entry<String, Uid.Pkg> pkgEntry : mPackageStats.entrySet()) {
8336 out.writeString(pkgEntry.getKey());
8337 Uid.Pkg pkg = pkgEntry.getValue();
8338 pkg.writeToParcelLocked(out);
8339 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008340
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008341 if (mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008342 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008343 mWifiRunningTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008344 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008345 out.writeInt(0);
8346 }
8347 if (mFullWifiLockTimer != null) {
8348 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008349 mFullWifiLockTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008350 } else {
8351 out.writeInt(0);
8352 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008353 if (mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008354 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008355 mWifiScanTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008356 } else {
8357 out.writeInt(0);
8358 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008359 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8360 if (mWifiBatchedScanTimer[i] != null) {
8361 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008362 mWifiBatchedScanTimer[i].writeToParcel(out, elapsedRealtimeUs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07008363 } else {
8364 out.writeInt(0);
8365 }
8366 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008367 if (mWifiMulticastTimer != null) {
8368 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008369 mWifiMulticastTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008370 } else {
8371 out.writeInt(0);
8372 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008373
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008374 if (mAudioTurnedOnTimer != null) {
8375 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008376 mAudioTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008377 } else {
8378 out.writeInt(0);
8379 }
8380 if (mVideoTurnedOnTimer != null) {
8381 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008382 mVideoTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008383 } else {
8384 out.writeInt(0);
8385 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008386 if (mFlashlightTurnedOnTimer != null) {
8387 out.writeInt(1);
8388 mFlashlightTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
8389 } else {
8390 out.writeInt(0);
8391 }
8392 if (mCameraTurnedOnTimer != null) {
8393 out.writeInt(1);
8394 mCameraTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
8395 } else {
8396 out.writeInt(0);
8397 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008398 if (mForegroundActivityTimer != null) {
8399 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008400 mForegroundActivityTimer.writeToParcel(out, elapsedRealtimeUs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008401 } else {
8402 out.writeInt(0);
8403 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008404 if (mForegroundServiceTimer != null) {
8405 out.writeInt(1);
8406 mForegroundServiceTimer.writeToParcel(out, elapsedRealtimeUs);
8407 } else {
8408 out.writeInt(0);
8409 }
Bookatzc8c44962017-05-11 12:12:54 -07008410 if (mAggregatedPartialWakelockTimer != null) {
8411 out.writeInt(1);
8412 mAggregatedPartialWakelockTimer.writeToParcel(out, elapsedRealtimeUs);
8413 } else {
8414 out.writeInt(0);
8415 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008416 if (mBluetoothScanTimer != null) {
8417 out.writeInt(1);
8418 mBluetoothScanTimer.writeToParcel(out, elapsedRealtimeUs);
8419 } else {
8420 out.writeInt(0);
8421 }
Bookatzb1f04f32017-05-19 13:57:32 -07008422 if (mBluetoothUnoptimizedScanTimer != null) {
8423 out.writeInt(1);
8424 mBluetoothUnoptimizedScanTimer.writeToParcel(out, elapsedRealtimeUs);
8425 } else {
8426 out.writeInt(0);
8427 }
Bookatz956f36bf2017-04-28 09:48:17 -07008428 if (mBluetoothScanResultCounter != null) {
8429 out.writeInt(1);
8430 mBluetoothScanResultCounter.writeToParcel(out);
8431 } else {
8432 out.writeInt(0);
8433 }
Bookatzb1f04f32017-05-19 13:57:32 -07008434 if (mBluetoothScanResultBgCounter != null) {
8435 out.writeInt(1);
8436 mBluetoothScanResultBgCounter.writeToParcel(out);
8437 } else {
8438 out.writeInt(0);
8439 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07008440 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8441 if (mProcessStateTimer[i] != null) {
8442 out.writeInt(1);
8443 mProcessStateTimer[i].writeToParcel(out, elapsedRealtimeUs);
8444 } else {
8445 out.writeInt(0);
8446 }
8447 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008448 if (mVibratorOnTimer != null) {
8449 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008450 mVibratorOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008451 } else {
8452 out.writeInt(0);
8453 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008454 if (mUserActivityCounters != null) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07008455 out.writeInt(1);
8456 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
8457 mUserActivityCounters[i].writeToParcel(out);
8458 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008459 } else {
8460 out.writeInt(0);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008461 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008462 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008463 out.writeInt(1);
8464 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008465 mNetworkByteActivityCounters[i].writeToParcel(out);
8466 mNetworkPacketActivityCounters[i].writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008467 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08008468 mMobileRadioActiveTime.writeToParcel(out);
8469 mMobileRadioActiveCount.writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008470 } else {
8471 out.writeInt(0);
8472 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008473
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008474 if (mWifiControllerActivity != null) {
8475 out.writeInt(1);
8476 mWifiControllerActivity.writeToParcel(out, 0);
8477 } else {
8478 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07008479 }
8480
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008481 if (mBluetoothControllerActivity != null) {
8482 out.writeInt(1);
8483 mBluetoothControllerActivity.writeToParcel(out, 0);
8484 } else {
8485 out.writeInt(0);
8486 }
8487
8488 if (mModemControllerActivity != null) {
8489 out.writeInt(1);
8490 mModemControllerActivity.writeToParcel(out, 0);
8491 } else {
8492 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07008493 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008494
8495 mUserCpuTime.writeToParcel(out);
8496 mSystemCpuTime.writeToParcel(out);
8497
Sudheer Shankaaf857412017-07-21 00:14:24 -07008498 if (mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008499 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -07008500 out.writeInt(mCpuClusterSpeedTimesUs.length);
8501 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008502 if (cpuSpeeds != null) {
8503 out.writeInt(1);
8504 out.writeInt(cpuSpeeds.length);
8505 for (LongSamplingCounter c : cpuSpeeds) {
8506 if (c != null) {
8507 out.writeInt(1);
8508 c.writeToParcel(out);
8509 } else {
8510 out.writeInt(0);
8511 }
8512 }
8513 } else {
8514 out.writeInt(0);
8515 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008516 }
Adam Lesinski6832f392015-09-05 18:05:40 -07008517 } else {
8518 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008519 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008520
Sudheer Shanka59f5c002017-05-15 10:57:15 -07008521 LongSamplingCounterArray.writeToParcel(out, mCpuFreqTimeMs);
8522 LongSamplingCounterArray.writeToParcel(out, mScreenOffCpuFreqTimeMs);
Mike Ma3d422c32017-10-25 11:08:57 -07008523
8524 mCpuActiveTimeMs.writeToParcel(out);
8525 mCpuClusterTimesMs.writeToParcel(out);
8526
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008527 if (mProcStateTimeMs != null) {
8528 out.writeInt(mProcStateTimeMs.length);
8529 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8530 LongSamplingCounterArray.writeToParcel(out, counters);
8531 }
8532 } else {
8533 out.writeInt(0);
8534 }
8535 if (mProcStateScreenOffTimeMs != null) {
8536 out.writeInt(mProcStateScreenOffTimeMs.length);
8537 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8538 LongSamplingCounterArray.writeToParcel(out, counters);
8539 }
8540 } else {
8541 out.writeInt(0);
8542 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008543
Adam Lesinski5f056f62016-07-14 16:56:08 -07008544 if (mMobileRadioApWakeupCount != null) {
8545 out.writeInt(1);
8546 mMobileRadioApWakeupCount.writeToParcel(out);
8547 } else {
8548 out.writeInt(0);
8549 }
8550
8551 if (mWifiRadioApWakeupCount != null) {
8552 out.writeInt(1);
8553 mWifiRadioApWakeupCount.writeToParcel(out);
8554 } else {
8555 out.writeInt(0);
8556 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008557 }
8558
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008559 void readJobCompletionsFromParcelLocked(Parcel in) {
8560 int numJobCompletions = in.readInt();
8561 mJobCompletions.clear();
8562 for (int j = 0; j < numJobCompletions; j++) {
8563 String jobName = in.readString();
8564 int numTypes = in.readInt();
8565 if (numTypes > 0) {
8566 SparseIntArray types = new SparseIntArray();
8567 for (int k = 0; k < numTypes; k++) {
8568 int type = in.readInt();
8569 int count = in.readInt();
8570 types.put(type, count);
8571 }
8572 mJobCompletions.put(jobName, types);
8573 }
8574 }
8575 }
8576
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008577 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase, Parcel in) {
Bookatz867c0d72017-03-07 18:23:42 -08008578 mOnBatteryBackgroundTimeBase.readFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -07008579 mOnBatteryScreenOffBackgroundTimeBase.readFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -08008580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008581 int numWakelocks = in.readInt();
8582 mWakelockStats.clear();
8583 for (int j = 0; j < numWakelocks; j++) {
8584 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008585 Uid.Wakelock wakelock = new Wakelock(mBsi, this);
Bookatz5b5ec322017-05-26 09:40:38 -07008586 wakelock.readFromParcelLocked(
8587 timeBase, screenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase, in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07008588 mWakelockStats.add(wakelockName, wakelock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008589 }
8590
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008591 int numSyncs = in.readInt();
8592 mSyncStats.clear();
8593 for (int j = 0; j < numSyncs; j++) {
8594 String syncName = in.readString();
8595 if (in.readInt() != 0) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008596 mSyncStats.add(syncName, new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
8597 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008598 }
8599 }
8600
8601 int numJobs = in.readInt();
8602 mJobStats.clear();
8603 for (int j = 0; j < numJobs; j++) {
8604 String jobName = in.readString();
8605 if (in.readInt() != 0) {
Bookatzaa4594a2017-03-24 12:39:56 -07008606 mJobStats.add(jobName, new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
8607 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008608 }
8609 }
8610
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008611 readJobCompletionsFromParcelLocked(in);
8612
Amith Yamasani977e11f2018-02-16 11:29:54 -08008613 mJobsDeferredEventCount = new Counter(mBsi.mOnBatteryTimeBase, in);
8614 mJobsDeferredCount = new Counter(mBsi.mOnBatteryTimeBase, in);
8615 mJobsFreshnessTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8616 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
8617 mJobsFreshnessBuckets[i] = Counter.readCounterFromParcel(mBsi.mOnBatteryTimeBase,
8618 in);
8619 }
8620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008621 int numSensors = in.readInt();
8622 mSensorStats.clear();
8623 for (int k = 0; k < numSensors; k++) {
8624 int sensorNumber = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008625 Uid.Sensor sensor = new Sensor(mBsi, this, sensorNumber);
Bookatz867c0d72017-03-07 18:23:42 -08008626 sensor.readFromParcelLocked(mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
8627 in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008628 mSensorStats.put(sensorNumber, sensor);
8629 }
8630
8631 int numProcs = in.readInt();
8632 mProcessStats.clear();
8633 for (int k = 0; k < numProcs; k++) {
8634 String processName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008635 Uid.Proc proc = new Proc(mBsi, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008636 proc.readFromParcelLocked(in);
8637 mProcessStats.put(processName, proc);
8638 }
8639
8640 int numPkgs = in.readInt();
8641 mPackageStats.clear();
8642 for (int l = 0; l < numPkgs; l++) {
8643 String packageName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008644 Uid.Pkg pkg = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008645 pkg.readFromParcelLocked(in);
8646 mPackageStats.put(packageName, pkg);
8647 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008648
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008649 mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008650 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008651 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
8652 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008653 } else {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008654 mWifiRunningTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008655 }
8656 mFullWifiLockOut = false;
8657 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008658 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
8659 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008660 } else {
8661 mFullWifiLockTimer = null;
8662 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008663 mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008664 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08008665 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
8666 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
8667 in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008668 } else {
Nick Pelly6ccaa542012-06-15 15:22:47 -07008669 mWifiScanTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008670 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008671 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
8672 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8673 if (in.readInt() != 0) {
8674 makeWifiBatchedScanBin(i, in);
8675 } else {
8676 mWifiBatchedScanTimer[i] = null;
8677 }
8678 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008679 mWifiMulticastEnabled = false;
8680 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008681 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_MULTICAST_ENABLED,
8682 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008683 } else {
8684 mWifiMulticastTimer = null;
8685 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008686 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008687 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
8688 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008689 } else {
8690 mAudioTurnedOnTimer = null;
8691 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008692 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008693 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
8694 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008695 } else {
8696 mVideoTurnedOnTimer = null;
8697 }
8698 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008699 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8700 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008701 } else {
8702 mFlashlightTurnedOnTimer = null;
8703 }
8704 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008705 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
8706 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008707 } else {
8708 mCameraTurnedOnTimer = null;
8709 }
8710 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008711 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8712 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008713 } else {
8714 mForegroundActivityTimer = null;
8715 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008716 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008717 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8718 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase, in);
8719 } else {
8720 mForegroundServiceTimer = null;
8721 }
8722 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -07008723 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
8724 AGGREGATED_WAKE_TYPE_PARTIAL, null,
8725 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase,
8726 in);
8727 } else {
8728 mAggregatedPartialWakelockTimer = null;
8729 }
8730 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08008731 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
8732 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
8733 mOnBatteryBackgroundTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008734 } else {
8735 mBluetoothScanTimer = null;
8736 }
Bookatz956f36bf2017-04-28 09:48:17 -07008737 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -07008738 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
8739 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
8740 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in);
8741 } else {
8742 mBluetoothUnoptimizedScanTimer = null;
8743 }
8744 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -07008745 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase, in);
8746 } else {
8747 mBluetoothScanResultCounter = null;
8748 }
Bookatzb1f04f32017-05-19 13:57:32 -07008749 if (in.readInt() != 0) {
8750 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase, in);
8751 } else {
8752 mBluetoothScanResultBgCounter = null;
8753 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08008754 mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07008755 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8756 if (in.readInt() != 0) {
8757 makeProcessState(i, in);
8758 } else {
8759 mProcessStateTimer[i] = null;
8760 }
8761 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008762 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008763 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
8764 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008765 } else {
8766 mVibratorOnTimer = null;
8767 }
8768 if (in.readInt() != 0) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07008769 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
8770 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08008771 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008772 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008773 } else {
8774 mUserActivityCounters = null;
Dianne Hackborn617f8772009-03-31 15:04:46 -07008775 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008776 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008777 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
8778 mNetworkPacketActivityCounters
8779 = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008780 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008781 mNetworkByteActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08008782 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008783 mNetworkPacketActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08008784 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008785 }
Joe Onoratoabded112016-02-08 16:49:39 -08008786 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8787 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008788 } else {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008789 mNetworkByteActivityCounters = null;
8790 mNetworkPacketActivityCounters = null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008791 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008792
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008793 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008794 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008795 NUM_WIFI_TX_LEVELS, in);
8796 } else {
8797 mWifiControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07008798 }
8799
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008800 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008801 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008802 NUM_BT_TX_LEVELS, in);
8803 } else {
8804 mBluetoothControllerActivity = null;
8805 }
8806
8807 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008808 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008809 ModemActivityInfo.TX_POWER_LEVELS, in);
8810 } else {
8811 mModemControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07008812 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008813
Joe Onoratoabded112016-02-08 16:49:39 -08008814 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8815 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008816
Adam Lesinski6832f392015-09-05 18:05:40 -07008817 if (in.readInt() != 0) {
8818 int numCpuClusters = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008819 if (mBsi.mPowerProfile != null && mBsi.mPowerProfile.getNumCpuClusters() != numCpuClusters) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008820 throw new ParcelFormatException("Incompatible number of cpu clusters");
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008821 }
Adam Lesinski6832f392015-09-05 18:05:40 -07008822
Sudheer Shankaaf857412017-07-21 00:14:24 -07008823 mCpuClusterSpeedTimesUs = new LongSamplingCounter[numCpuClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -07008824 for (int cluster = 0; cluster < numCpuClusters; cluster++) {
8825 if (in.readInt() != 0) {
8826 int numSpeeds = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008827 if (mBsi.mPowerProfile != null &&
8828 mBsi.mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != numSpeeds) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008829 throw new ParcelFormatException("Incompatible number of cpu speeds");
8830 }
8831
8832 final LongSamplingCounter[] cpuSpeeds = new LongSamplingCounter[numSpeeds];
Sudheer Shankaaf857412017-07-21 00:14:24 -07008833 mCpuClusterSpeedTimesUs[cluster] = cpuSpeeds;
Adam Lesinski6832f392015-09-05 18:05:40 -07008834 for (int speed = 0; speed < numSpeeds; speed++) {
8835 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008836 cpuSpeeds[speed] = new LongSamplingCounter(
8837 mBsi.mOnBatteryTimeBase, in);
Adam Lesinski6832f392015-09-05 18:05:40 -07008838 }
8839 }
Adam Lesinskia57a5402015-09-28 10:21:33 -07008840 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008841 mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -07008842 }
8843 }
8844 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008845 mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008846 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008847
Sudheer Shanka59f5c002017-05-15 10:57:15 -07008848 mCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(in, mBsi.mOnBatteryTimeBase);
8849 mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(
8850 in, mBsi.mOnBatteryScreenOffTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008851
Mike Ma3d422c32017-10-25 11:08:57 -07008852 mCpuActiveTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8853 mCpuClusterTimesMs = new LongSamplingCounterArray(mBsi.mOnBatteryTimeBase, in);
8854
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008855 int length = in.readInt();
8856 if (length == NUM_PROCESS_STATE) {
8857 mProcStateTimeMs = new LongSamplingCounterArray[length];
8858 for (int procState = 0; procState < length; ++procState) {
8859 mProcStateTimeMs[procState] = LongSamplingCounterArray.readFromParcel(
8860 in, mBsi.mOnBatteryTimeBase);
8861 }
8862 } else {
8863 mProcStateTimeMs = null;
8864 }
8865 length = in.readInt();
8866 if (length == NUM_PROCESS_STATE) {
8867 mProcStateScreenOffTimeMs = new LongSamplingCounterArray[length];
8868 for (int procState = 0; procState < length; ++procState) {
8869 mProcStateScreenOffTimeMs[procState] = LongSamplingCounterArray.readFromParcel(
8870 in, mBsi.mOnBatteryScreenOffTimeBase);
8871 }
8872 } else {
8873 mProcStateScreenOffTimeMs = null;
8874 }
8875
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008876 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07008877 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8878 } else {
8879 mMobileRadioApWakeupCount = null;
8880 }
8881
8882 if (in.readInt() != 0) {
8883 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8884 } else {
8885 mWifiRadioApWakeupCount = null;
8886 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008887 }
8888
Amith Yamasani977e11f2018-02-16 11:29:54 -08008889 public void noteJobsDeferredLocked(int numDeferred, long sinceLast) {
8890 mJobsDeferredEventCount.addAtomic(1);
8891 mJobsDeferredCount.addAtomic(numDeferred);
8892 if (sinceLast != 0) {
8893 // Add the total time, which can be divided by the event count to get an average
8894 mJobsFreshnessTimeMs.addCountLocked(sinceLast);
8895 // Also keep track of how many times there were in these different buckets.
8896 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
8897 if (sinceLast < JOB_FRESHNESS_BUCKETS[i]) {
8898 if (mJobsFreshnessBuckets[i] == null) {
8899 mJobsFreshnessBuckets[i] = new Counter(
8900 mBsi.mOnBatteryTimeBase);
8901 }
8902 mJobsFreshnessBuckets[i].addAtomic(1);
8903 break;
8904 }
8905 }
8906 }
8907 }
8908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008909 /**
8910 * The statistics associated with a particular wake lock.
8911 */
Joe Onoratoabded112016-02-08 16:49:39 -08008912 public static class Wakelock extends BatteryStats.Uid.Wakelock {
8913 /**
8914 * BatteryStatsImpl that we are associated with.
8915 */
8916 protected BatteryStatsImpl mBsi;
8917
8918 /**
8919 * BatteryStatsImpl that we are associated with.
8920 */
8921 protected Uid mUid;
8922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008923 /**
8924 * How long (in ms) this uid has been keeping the device partially awake.
Bookatz5b5ec322017-05-26 09:40:38 -07008925 * 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 -08008926 */
Bookatz5b5ec322017-05-26 09:40:38 -07008927 DualTimer mTimerPartial;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008928
8929 /**
8930 * How long (in ms) this uid has been keeping the device fully awake.
8931 */
Evan Millarc64edde2009-04-18 12:26:32 -07008932 StopwatchTimer mTimerFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008933
8934 /**
8935 * How long (in ms) this uid has had a window keeping the device awake.
8936 */
Evan Millarc64edde2009-04-18 12:26:32 -07008937 StopwatchTimer mTimerWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008938
8939 /**
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008940 * How long (in ms) this uid has had a draw wake lock.
Adam Lesinski9425fe22015-06-19 12:02:13 -07008941 */
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008942 StopwatchTimer mTimerDraw;
Adam Lesinski9425fe22015-06-19 12:02:13 -07008943
Joe Onoratoabded112016-02-08 16:49:39 -08008944 public Wakelock(BatteryStatsImpl bsi, Uid uid) {
8945 mBsi = bsi;
8946 mUid = uid;
8947 }
8948
Adam Lesinski9425fe22015-06-19 12:02:13 -07008949 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008950 * Reads a possibly null Timer from a Parcel. The timer is associated with the
8951 * proper timer pool from the given BatteryStatsImpl object.
8952 *
8953 * @param in the Parcel to be read from.
8954 * return a new Timer, or null.
8955 */
Joe Onorato92fd23f2016-07-25 11:18:42 -07008956 private StopwatchTimer readStopwatchTimerFromParcel(int type,
8957 ArrayList<StopwatchTimer> pool, TimeBase timeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008958 if (in.readInt() == 0) {
8959 return null;
8960 }
8961
Joe Onoratoabded112016-02-08 16:49:39 -08008962 return new StopwatchTimer(mBsi.mClocks, mUid, type, pool, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008963 }
8964
Joe Onorato92fd23f2016-07-25 11:18:42 -07008965 /**
8966 * Reads a possibly null Timer from a Parcel. The timer is associated with the
8967 * proper timer pool from the given BatteryStatsImpl object.
8968 *
8969 * @param in the Parcel to be read from.
8970 * return a new Timer, or null.
8971 */
Bookatz5b5ec322017-05-26 09:40:38 -07008972 private DualTimer readDualTimerFromParcel(int type, ArrayList<StopwatchTimer> pool,
8973 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07008974 if (in.readInt() == 0) {
8975 return null;
8976 }
8977
Bookatz5b5ec322017-05-26 09:40:38 -07008978 return new DualTimer(mBsi.mClocks, mUid, type, pool, timeBase, bgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07008979 }
8980
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008981 boolean reset() {
8982 boolean wlactive = false;
8983 if (mTimerFull != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008984 wlactive |= !mTimerFull.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008985 }
8986 if (mTimerPartial != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008987 wlactive |= !mTimerPartial.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008988 }
8989 if (mTimerWindow != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008990 wlactive |= !mTimerWindow.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008991 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008992 if (mTimerDraw != null) {
8993 wlactive |= !mTimerDraw.reset(false);
Adam Lesinski9425fe22015-06-19 12:02:13 -07008994 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008995 if (!wlactive) {
8996 if (mTimerFull != null) {
8997 mTimerFull.detach();
8998 mTimerFull = null;
8999 }
9000 if (mTimerPartial != null) {
9001 mTimerPartial.detach();
9002 mTimerPartial = null;
9003 }
9004 if (mTimerWindow != null) {
9005 mTimerWindow.detach();
9006 mTimerWindow = null;
9007 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07009008 if (mTimerDraw != null) {
9009 mTimerDraw.detach();
9010 mTimerDraw = null;
Adam Lesinski9425fe22015-06-19 12:02:13 -07009011 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009012 }
9013 return !wlactive;
9014 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009015
Bookatz5b5ec322017-05-26 09:40:38 -07009016 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase,
9017 TimeBase screenOffBgTimeBase, Parcel in) {
9018 mTimerPartial = readDualTimerFromParcel(WAKE_TYPE_PARTIAL,
9019 mBsi.mPartialTimers, screenOffTimeBase, screenOffBgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07009020 mTimerFull = readStopwatchTimerFromParcel(WAKE_TYPE_FULL,
9021 mBsi.mFullTimers, timeBase, in);
9022 mTimerWindow = readStopwatchTimerFromParcel(WAKE_TYPE_WINDOW,
9023 mBsi.mWindowTimers, timeBase, in);
9024 mTimerDraw = readStopwatchTimerFromParcel(WAKE_TYPE_DRAW,
9025 mBsi.mDrawTimers, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009026 }
9027
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009028 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
9029 Timer.writeTimerToParcel(out, mTimerPartial, elapsedRealtimeUs);
9030 Timer.writeTimerToParcel(out, mTimerFull, elapsedRealtimeUs);
9031 Timer.writeTimerToParcel(out, mTimerWindow, elapsedRealtimeUs);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07009032 Timer.writeTimerToParcel(out, mTimerDraw, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009033 }
9034
9035 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01009036 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009037 public Timer getWakeTime(int type) {
9038 switch (type) {
9039 case WAKE_TYPE_FULL: return mTimerFull;
9040 case WAKE_TYPE_PARTIAL: return mTimerPartial;
9041 case WAKE_TYPE_WINDOW: return mTimerWindow;
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07009042 case WAKE_TYPE_DRAW: return mTimerDraw;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009043 default: throw new IllegalArgumentException("type = " + type);
9044 }
9045 }
9046 }
9047
Joe Onoratoabded112016-02-08 16:49:39 -08009048 public static class Sensor extends BatteryStats.Uid.Sensor {
9049 /**
9050 * BatteryStatsImpl that we are associated with.
9051 */
9052 protected BatteryStatsImpl mBsi;
9053
9054 /**
Bookatz867c0d72017-03-07 18:23:42 -08009055 * Uid that we are associated with.
Joe Onoratoabded112016-02-08 16:49:39 -08009056 */
9057 protected Uid mUid;
9058
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009059 final int mHandle;
Bookatz867c0d72017-03-07 18:23:42 -08009060 DualTimer mTimer;
Amith Yamasaniab9ad192016-12-06 12:46:59 -08009061
Joe Onoratoabded112016-02-08 16:49:39 -08009062 public Sensor(BatteryStatsImpl bsi, Uid uid, int handle) {
9063 mBsi = bsi;
9064 mUid = uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009065 mHandle = handle;
9066 }
9067
Bookatz867c0d72017-03-07 18:23:42 -08009068 private DualTimer readTimersFromParcel(
9069 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009070 if (in.readInt() == 0) {
9071 return null;
9072 }
9073
Joe Onoratoabded112016-02-08 16:49:39 -08009074 ArrayList<StopwatchTimer> pool = mBsi.mSensorTimers.get(mHandle);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009075 if (pool == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07009076 pool = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08009077 mBsi.mSensorTimers.put(mHandle, pool);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009078 }
Bookatz867c0d72017-03-07 18:23:42 -08009079 return new DualTimer(mBsi.mClocks, mUid, 0, pool, timeBase, bgTimeBase, in);
Amith Yamasaniab9ad192016-12-06 12:46:59 -08009080 }
9081
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009082 boolean reset() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009083 if (mTimer.reset(true)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009084 mTimer = null;
9085 return true;
9086 }
9087 return false;
9088 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009089
Bookatz867c0d72017-03-07 18:23:42 -08009090 void readFromParcelLocked(TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
9091 mTimer = readTimersFromParcel(timeBase, bgTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009092 }
9093
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009094 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07009095 Timer.writeTimerToParcel(out, mTimer, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009096 }
9097
9098 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01009099 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009100 public Timer getSensorTime() {
Bookatzaa4594a2017-03-24 12:39:56 -07009101 return mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009102 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009103
9104 @Override
Bookatz867c0d72017-03-07 18:23:42 -08009105 public Timer getSensorBackgroundTime() {
9106 if (mTimer == null) {
9107 return null;
9108 }
9109 return mTimer.getSubTimer();
Amith Yamasaniab9ad192016-12-06 12:46:59 -08009110 }
9111
9112 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01009113 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009114 public int getHandle() {
9115 return mHandle;
9116 }
9117 }
9118
9119 /**
9120 * The statistics associated with a particular process.
9121 */
Joe Onoratoabded112016-02-08 16:49:39 -08009122 public static class Proc extends BatteryStats.Uid.Proc implements TimeBaseObs {
9123 /**
9124 * BatteryStatsImpl that we are associated with.
9125 */
9126 protected BatteryStatsImpl mBsi;
9127
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009128 /**
Dianne Hackborncd0e3352014-08-07 17:08:09 -07009129 * The name of this process.
9130 */
9131 final String mName;
9132
9133 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -08009134 * Remains true until removed from the stats.
9135 */
9136 boolean mActive = true;
9137
9138 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07009139 * Total time (in ms) spent executing in user code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009140 */
9141 long mUserTime;
9142
9143 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07009144 * Total time (in ms) spent executing in kernel code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009145 */
9146 long mSystemTime;
9147
9148 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07009149 * Amount of time (in ms) the process was running in the foreground.
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009150 */
9151 long mForegroundTime;
9152
9153 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009154 * Number of times the process has been started.
9155 */
9156 int mStarts;
9157
9158 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009159 * Number of times the process has crashed.
9160 */
9161 int mNumCrashes;
9162
9163 /**
9164 * Number of times the process has had an ANR.
9165 */
9166 int mNumAnrs;
9167
9168 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009169 * The amount of user time loaded from a previous save.
9170 */
9171 long mLoadedUserTime;
9172
9173 /**
9174 * The amount of system time loaded from a previous save.
9175 */
9176 long mLoadedSystemTime;
9177
9178 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009179 * The amount of foreground time loaded from a previous save.
9180 */
9181 long mLoadedForegroundTime;
9182
9183 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009184 * The number of times the process has started from a previous save.
9185 */
9186 int mLoadedStarts;
9187
9188 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009189 * Number of times the process has crashed from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009190 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009191 int mLoadedNumCrashes;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009192
9193 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009194 * Number of times the process has had an ANR from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009195 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009196 int mLoadedNumAnrs;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009197
9198 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009199 * The amount of user time when last unplugged.
9200 */
9201 long mUnpluggedUserTime;
9202
9203 /**
9204 * The amount of system time when last unplugged.
9205 */
9206 long mUnpluggedSystemTime;
9207
9208 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009209 * The amount of foreground time since unplugged.
9210 */
9211 long mUnpluggedForegroundTime;
9212
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009213 /**
9214 * The number of times the process has started before unplugged.
9215 */
9216 int mUnpluggedStarts;
9217
Dianne Hackborn61659e52014-07-09 16:13:01 -07009218 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009219 * Number of times the process has crashed before unplugged.
9220 */
9221 int mUnpluggedNumCrashes;
9222
9223 /**
9224 * Number of times the process has had an ANR before unplugged.
9225 */
9226 int mUnpluggedNumAnrs;
9227
Dianne Hackborn287952c2010-09-22 22:34:31 -07009228 ArrayList<ExcessivePower> mExcessivePower;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009229
Joe Onoratoabded112016-02-08 16:49:39 -08009230 public Proc(BatteryStatsImpl bsi, String name) {
9231 mBsi = bsi;
Dianne Hackborncd0e3352014-08-07 17:08:09 -07009232 mName = name;
Joe Onoratoabded112016-02-08 16:49:39 -08009233 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009234 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07009235
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009236 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009237 mUnpluggedUserTime = mUserTime;
9238 mUnpluggedSystemTime = mSystemTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009239 mUnpluggedForegroundTime = mForegroundTime;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009240 mUnpluggedStarts = mStarts;
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009241 mUnpluggedNumCrashes = mNumCrashes;
9242 mUnpluggedNumAnrs = mNumAnrs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009243 }
9244
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009245 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009246 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009247
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009248 void detach() {
Dianne Hackborn099bc622014-01-22 13:39:16 -08009249 mActive = false;
Joe Onoratoabded112016-02-08 16:49:39 -08009250 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009251 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009252
Dianne Hackborn287952c2010-09-22 22:34:31 -07009253 public int countExcessivePowers() {
9254 return mExcessivePower != null ? mExcessivePower.size() : 0;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009255 }
9256
Dianne Hackborn287952c2010-09-22 22:34:31 -07009257 public ExcessivePower getExcessivePower(int i) {
9258 if (mExcessivePower != null) {
9259 return mExcessivePower.get(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009260 }
9261 return null;
9262 }
9263
Dianne Hackborn287952c2010-09-22 22:34:31 -07009264 public void addExcessiveCpu(long overTime, long usedTime) {
9265 if (mExcessivePower == null) {
9266 mExcessivePower = new ArrayList<ExcessivePower>();
9267 }
9268 ExcessivePower ew = new ExcessivePower();
9269 ew.type = ExcessivePower.TYPE_CPU;
9270 ew.overTime = overTime;
9271 ew.usedTime = usedTime;
9272 mExcessivePower.add(ew);
9273 }
9274
9275 void writeExcessivePowerToParcelLocked(Parcel out) {
9276 if (mExcessivePower == null) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009277 out.writeInt(0);
9278 return;
9279 }
9280
Dianne Hackborn287952c2010-09-22 22:34:31 -07009281 final int N = mExcessivePower.size();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009282 out.writeInt(N);
9283 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009284 ExcessivePower ew = mExcessivePower.get(i);
9285 out.writeInt(ew.type);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009286 out.writeLong(ew.overTime);
9287 out.writeLong(ew.usedTime);
9288 }
9289 }
9290
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009291 void readExcessivePowerFromParcelLocked(Parcel in) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009292 final int N = in.readInt();
9293 if (N == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009294 mExcessivePower = null;
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009295 return;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009296 }
9297
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08009298 if (N > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009299 throw new ParcelFormatException(
9300 "File corrupt: too many excessive power entries " + N);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08009301 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009302
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009303 mExcessivePower = new ArrayList<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009304 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009305 ExcessivePower ew = new ExcessivePower();
9306 ew.type = in.readInt();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009307 ew.overTime = in.readLong();
9308 ew.usedTime = in.readLong();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009309 mExcessivePower.add(ew);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009310 }
9311 }
9312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009313 void writeToParcelLocked(Parcel out) {
9314 out.writeLong(mUserTime);
9315 out.writeLong(mSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009316 out.writeLong(mForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009317 out.writeInt(mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009318 out.writeInt(mNumCrashes);
9319 out.writeInt(mNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009320 out.writeLong(mLoadedUserTime);
9321 out.writeLong(mLoadedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009322 out.writeLong(mLoadedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009323 out.writeInt(mLoadedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009324 out.writeInt(mLoadedNumCrashes);
9325 out.writeInt(mLoadedNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009326 out.writeLong(mUnpluggedUserTime);
9327 out.writeLong(mUnpluggedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009328 out.writeLong(mUnpluggedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009329 out.writeInt(mUnpluggedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009330 out.writeInt(mUnpluggedNumCrashes);
9331 out.writeInt(mUnpluggedNumAnrs);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009332 writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009333 }
9334
9335 void readFromParcelLocked(Parcel in) {
9336 mUserTime = in.readLong();
9337 mSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009338 mForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009339 mStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009340 mNumCrashes = in.readInt();
9341 mNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009342 mLoadedUserTime = in.readLong();
9343 mLoadedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009344 mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009345 mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009346 mLoadedNumCrashes = in.readInt();
9347 mLoadedNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009348 mUnpluggedUserTime = in.readLong();
9349 mUnpluggedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009350 mUnpluggedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009351 mUnpluggedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009352 mUnpluggedNumCrashes = in.readInt();
9353 mUnpluggedNumAnrs = in.readInt();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009354 readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009355 }
9356
Mathew Inwoodc185f082018-08-20 14:28:54 +01009357 @UnsupportedAppUsage
Adam Lesinski06af1fa2015-05-05 17:35:35 -07009358 public void addCpuTimeLocked(int utime, int stime) {
Sudheer Shankac57729a2018-02-09 15:44:42 -08009359 addCpuTimeLocked(utime, stime, mBsi.mOnBatteryTimeBase.isRunning());
9360 }
9361
9362 public void addCpuTimeLocked(int utime, int stime, boolean isRunning) {
9363 if (isRunning) {
9364 mUserTime += utime;
9365 mSystemTime += stime;
9366 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009367 }
9368
Mathew Inwoodc185f082018-08-20 14:28:54 +01009369 @UnsupportedAppUsage
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009370 public void addForegroundTimeLocked(long ttime) {
9371 mForegroundTime += ttime;
9372 }
9373
Mathew Inwoodc185f082018-08-20 14:28:54 +01009374 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009375 public void incStartsLocked() {
9376 mStarts++;
9377 }
9378
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009379 public void incNumCrashesLocked() {
9380 mNumCrashes++;
9381 }
9382
9383 public void incNumAnrsLocked() {
9384 mNumAnrs++;
9385 }
9386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009387 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -08009388 public boolean isActive() {
9389 return mActive;
9390 }
9391
9392 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01009393 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009394 public long getUserTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009395 long val = mUserTime;
9396 if (which == STATS_CURRENT) {
9397 val -= mLoadedUserTime;
9398 } else if (which == STATS_SINCE_UNPLUGGED) {
9399 val -= mUnpluggedUserTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009400 }
9401 return val;
9402 }
9403
9404 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01009405 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009406 public long getSystemTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009407 long val = mSystemTime;
9408 if (which == STATS_CURRENT) {
9409 val -= mLoadedSystemTime;
9410 } else if (which == STATS_SINCE_UNPLUGGED) {
9411 val -= mUnpluggedSystemTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009412 }
9413 return val;
9414 }
9415
9416 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01009417 @UnsupportedAppUsage
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009418 public long getForegroundTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009419 long val = mForegroundTime;
9420 if (which == STATS_CURRENT) {
9421 val -= mLoadedForegroundTime;
9422 } else if (which == STATS_SINCE_UNPLUGGED) {
9423 val -= mUnpluggedForegroundTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009424 }
9425 return val;
9426 }
9427
9428 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01009429 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009430 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009431 int val = mStarts;
9432 if (which == STATS_CURRENT) {
9433 val -= mLoadedStarts;
9434 } else if (which == STATS_SINCE_UNPLUGGED) {
9435 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009436 }
9437 return val;
9438 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07009439
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009440 @Override
9441 public int getNumCrashes(int which) {
9442 int val = mNumCrashes;
9443 if (which == STATS_CURRENT) {
9444 val -= mLoadedNumCrashes;
9445 } else if (which == STATS_SINCE_UNPLUGGED) {
9446 val -= mUnpluggedNumCrashes;
9447 }
9448 return val;
9449 }
9450
9451 @Override
9452 public int getNumAnrs(int which) {
9453 int val = mNumAnrs;
9454 if (which == STATS_CURRENT) {
9455 val -= mLoadedNumAnrs;
9456 } else if (which == STATS_SINCE_UNPLUGGED) {
9457 val -= mUnpluggedNumAnrs;
9458 }
9459 return val;
9460 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009461 }
9462
9463 /**
9464 * The statistics associated with a particular package.
9465 */
Joe Onoratoabded112016-02-08 16:49:39 -08009466 public static class Pkg extends BatteryStats.Uid.Pkg implements TimeBaseObs {
9467 /**
9468 * BatteryStatsImpl that we are associated with.
9469 */
9470 protected BatteryStatsImpl mBsi;
9471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009472 /**
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009473 * Number of times wakeup alarms have occurred for this app.
Bookatz98d4d5c2017-08-01 19:07:54 -07009474 * On screen-off timebase starting in report v25.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009475 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009476 ArrayMap<String, Counter> mWakeupAlarms = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009477
9478 /**
9479 * The statics we have collected for this package's services.
9480 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009481 final ArrayMap<String, Serv> mServiceStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009482
Joe Onoratoabded112016-02-08 16:49:39 -08009483 public Pkg(BatteryStatsImpl bsi) {
9484 mBsi = bsi;
9485 mBsi.mOnBatteryScreenOffTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009486 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009487
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009488 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009489 }
9490
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009491 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009492 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009493
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009494 void detach() {
Joe Onoratoabded112016-02-08 16:49:39 -08009495 mBsi.mOnBatteryScreenOffTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009496 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009497
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009498 void readFromParcelLocked(Parcel in) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009499 int numWA = in.readInt();
9500 mWakeupAlarms.clear();
9501 for (int i=0; i<numWA; i++) {
9502 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -07009503 mWakeupAlarms.put(tag, new Counter(mBsi.mOnBatteryScreenOffTimeBase, in));
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009504 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009505
9506 int numServs = in.readInt();
9507 mServiceStats.clear();
9508 for (int m = 0; m < numServs; m++) {
9509 String serviceName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08009510 Uid.Pkg.Serv serv = new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009511 mServiceStats.put(serviceName, serv);
9512
9513 serv.readFromParcelLocked(in);
9514 }
9515 }
9516
9517 void writeToParcelLocked(Parcel out) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009518 int numWA = mWakeupAlarms.size();
9519 out.writeInt(numWA);
9520 for (int i=0; i<numWA; i++) {
9521 out.writeString(mWakeupAlarms.keyAt(i));
9522 mWakeupAlarms.valueAt(i).writeToParcel(out);
9523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009524
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009525 final int NS = mServiceStats.size();
9526 out.writeInt(NS);
9527 for (int i=0; i<NS; i++) {
9528 out.writeString(mServiceStats.keyAt(i));
9529 Uid.Pkg.Serv serv = mServiceStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009530 serv.writeToParcelLocked(out);
9531 }
9532 }
9533
9534 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009535 public ArrayMap<String, ? extends BatteryStats.Counter> getWakeupAlarmStats() {
9536 return mWakeupAlarms;
9537 }
9538
9539 public void noteWakeupAlarmLocked(String tag) {
9540 Counter c = mWakeupAlarms.get(tag);
9541 if (c == null) {
Bookatz98d4d5c2017-08-01 19:07:54 -07009542 c = new Counter(mBsi.mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009543 mWakeupAlarms.put(tag, c);
9544 }
9545 c.stepAtomic();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009546 }
9547
9548 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009549 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg.Serv> getServiceStats() {
9550 return mServiceStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009551 }
9552
9553 /**
9554 * The statistics associated with a particular service.
9555 */
Joe Onoratoabded112016-02-08 16:49:39 -08009556 public static class Serv extends BatteryStats.Uid.Pkg.Serv implements TimeBaseObs {
9557 /**
9558 * BatteryStatsImpl that we are associated with.
9559 */
9560 protected BatteryStatsImpl mBsi;
9561
9562 /**
9563 * The android package in which this service resides.
9564 */
9565 protected Pkg mPkg;
9566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009567 /**
9568 * Total time (ms in battery uptime) the service has been left started.
9569 */
Joe Onoratoabded112016-02-08 16:49:39 -08009570 protected long mStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009571
9572 /**
9573 * If service has been started and not yet stopped, this is
9574 * when it was started.
9575 */
Joe Onoratoabded112016-02-08 16:49:39 -08009576 protected long mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009577
9578 /**
9579 * True if we are currently running.
9580 */
Joe Onoratoabded112016-02-08 16:49:39 -08009581 protected boolean mRunning;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009582
9583 /**
9584 * Total number of times startService() has been called.
9585 */
Joe Onoratoabded112016-02-08 16:49:39 -08009586 protected int mStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009587
9588 /**
9589 * Total time (ms in battery uptime) the service has been left launched.
9590 */
Joe Onoratoabded112016-02-08 16:49:39 -08009591 protected long mLaunchedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009592
9593 /**
9594 * If service has been launched and not yet exited, this is
9595 * when it was launched (ms in battery uptime).
9596 */
Joe Onoratoabded112016-02-08 16:49:39 -08009597 protected long mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009598
9599 /**
9600 * True if we are currently launched.
9601 */
Joe Onoratoabded112016-02-08 16:49:39 -08009602 protected boolean mLaunched;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009603
9604 /**
9605 * Total number times the service has been launched.
9606 */
Joe Onoratoabded112016-02-08 16:49:39 -08009607 protected int mLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009608
9609 /**
9610 * The amount of time spent started loaded from a previous save
9611 * (ms in battery uptime).
9612 */
Joe Onoratoabded112016-02-08 16:49:39 -08009613 protected long mLoadedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009614
9615 /**
9616 * The number of starts loaded from a previous save.
9617 */
Joe Onoratoabded112016-02-08 16:49:39 -08009618 protected int mLoadedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009619
9620 /**
9621 * The number of launches loaded from a previous save.
9622 */
Joe Onoratoabded112016-02-08 16:49:39 -08009623 protected int mLoadedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009624
9625 /**
9626 * The amount of time spent started as of the last run (ms
9627 * in battery uptime).
9628 */
Joe Onoratoabded112016-02-08 16:49:39 -08009629 protected long mLastStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009630
9631 /**
9632 * The number of starts as of the last run.
9633 */
Joe Onoratoabded112016-02-08 16:49:39 -08009634 protected int mLastStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009635
9636 /**
9637 * The number of launches as of the last run.
9638 */
Joe Onoratoabded112016-02-08 16:49:39 -08009639 protected int mLastLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009640
9641 /**
9642 * The amount of time spent started when last unplugged (ms
9643 * in battery uptime).
9644 */
Joe Onoratoabded112016-02-08 16:49:39 -08009645 protected long mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009646
9647 /**
9648 * The number of starts when last unplugged.
9649 */
Joe Onoratoabded112016-02-08 16:49:39 -08009650 protected int mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009651
9652 /**
9653 * The number of launches when last unplugged.
9654 */
Joe Onoratoabded112016-02-08 16:49:39 -08009655 protected int mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009656
Joe Onoratoabded112016-02-08 16:49:39 -08009657 /**
9658 * Construct a Serv. Also adds it to the on-battery time base as a listener.
9659 */
9660 public Serv(BatteryStatsImpl bsi) {
9661 mBsi = bsi;
9662 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009663 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009664
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009665 public void onTimeStarted(long elapsedRealtime, long baseUptime,
9666 long baseRealtime) {
9667 mUnpluggedStartTime = getStartTimeToNowLocked(baseUptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009668 mUnpluggedStarts = mStarts;
9669 mUnpluggedLaunches = mLaunches;
9670 }
9671
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009672 public void onTimeStopped(long elapsedRealtime, long baseUptime,
9673 long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009674 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009675
Joe Onoratoabded112016-02-08 16:49:39 -08009676 /**
9677 * Remove this Serv as a listener from the time base.
9678 */
9679 public void detach() {
9680 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009681 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009682
Joe Onoratoabded112016-02-08 16:49:39 -08009683 public void readFromParcelLocked(Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009684 mStartTime = in.readLong();
9685 mRunningSince = in.readLong();
9686 mRunning = in.readInt() != 0;
9687 mStarts = in.readInt();
9688 mLaunchedTime = in.readLong();
9689 mLaunchedSince = in.readLong();
9690 mLaunched = in.readInt() != 0;
9691 mLaunches = in.readInt();
9692 mLoadedStartTime = in.readLong();
9693 mLoadedStarts = in.readInt();
9694 mLoadedLaunches = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07009695 mLastStartTime = 0;
9696 mLastStarts = 0;
9697 mLastLaunches = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009698 mUnpluggedStartTime = in.readLong();
9699 mUnpluggedStarts = in.readInt();
9700 mUnpluggedLaunches = in.readInt();
9701 }
9702
Joe Onoratoabded112016-02-08 16:49:39 -08009703 public void writeToParcelLocked(Parcel out) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009704 out.writeLong(mStartTime);
9705 out.writeLong(mRunningSince);
9706 out.writeInt(mRunning ? 1 : 0);
9707 out.writeInt(mStarts);
9708 out.writeLong(mLaunchedTime);
9709 out.writeLong(mLaunchedSince);
9710 out.writeInt(mLaunched ? 1 : 0);
9711 out.writeInt(mLaunches);
9712 out.writeLong(mLoadedStartTime);
9713 out.writeInt(mLoadedStarts);
9714 out.writeInt(mLoadedLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009715 out.writeLong(mUnpluggedStartTime);
9716 out.writeInt(mUnpluggedStarts);
9717 out.writeInt(mUnpluggedLaunches);
9718 }
9719
Joe Onoratoabded112016-02-08 16:49:39 -08009720 public long getLaunchTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009721 if (!mLaunched) return mLaunchedTime;
9722 return mLaunchedTime + batteryUptime - mLaunchedSince;
9723 }
9724
Joe Onoratoabded112016-02-08 16:49:39 -08009725 public long getStartTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009726 if (!mRunning) return mStartTime;
9727 return mStartTime + batteryUptime - mRunningSince;
9728 }
9729
Mathew Inwoodc185f082018-08-20 14:28:54 +01009730 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009731 public void startLaunchedLocked() {
9732 if (!mLaunched) {
9733 mLaunches++;
Joe Onoratoabded112016-02-08 16:49:39 -08009734 mLaunchedSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009735 mLaunched = true;
9736 }
9737 }
9738
Mathew Inwoodc185f082018-08-20 14:28:54 +01009739 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009740 public void stopLaunchedLocked() {
9741 if (mLaunched) {
Joe Onoratoabded112016-02-08 16:49:39 -08009742 long time = mBsi.getBatteryUptimeLocked() - mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009743 if (time > 0) {
9744 mLaunchedTime += time;
9745 } else {
9746 mLaunches--;
9747 }
9748 mLaunched = false;
9749 }
9750 }
9751
Mathew Inwoodc185f082018-08-20 14:28:54 +01009752 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009753 public void startRunningLocked() {
9754 if (!mRunning) {
9755 mStarts++;
Joe Onoratoabded112016-02-08 16:49:39 -08009756 mRunningSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009757 mRunning = true;
9758 }
9759 }
9760
Mathew Inwoodc185f082018-08-20 14:28:54 +01009761 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009762 public void stopRunningLocked() {
9763 if (mRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08009764 long time = mBsi.getBatteryUptimeLocked() - mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009765 if (time > 0) {
9766 mStartTime += time;
9767 } else {
9768 mStarts--;
9769 }
9770 mRunning = false;
9771 }
9772 }
9773
Mathew Inwoodc185f082018-08-20 14:28:54 +01009774 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009775 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -08009776 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009777 }
9778
9779 @Override
9780 public int getLaunches(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009781 int val = mLaunches;
9782 if (which == STATS_CURRENT) {
9783 val -= mLoadedLaunches;
9784 } else if (which == STATS_SINCE_UNPLUGGED) {
9785 val -= mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009786 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009787 return val;
9788 }
9789
9790 @Override
9791 public long getStartTime(long now, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009792 long val = getStartTimeToNowLocked(now);
9793 if (which == STATS_CURRENT) {
9794 val -= mLoadedStartTime;
9795 } else if (which == STATS_SINCE_UNPLUGGED) {
9796 val -= mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009797 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009798 return val;
9799 }
9800
9801 @Override
9802 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009803 int val = mStarts;
9804 if (which == STATS_CURRENT) {
9805 val -= mLoadedStarts;
9806 } else if (which == STATS_SINCE_UNPLUGGED) {
9807 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009808 }
9809
9810 return val;
9811 }
9812 }
9813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009814 final Serv newServiceStatsLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08009815 return new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009816 }
9817 }
9818
9819 /**
9820 * Retrieve the statistics object for a particular process, creating
9821 * if needed.
9822 */
9823 public Proc getProcessStatsLocked(String name) {
9824 Proc ps = mProcessStats.get(name);
9825 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08009826 ps = new Proc(mBsi, name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009827 mProcessStats.put(name, ps);
9828 }
9829
9830 return ps;
9831 }
9832
Andreas Gampe3f24e692018-02-05 13:24:28 -08009833 @GuardedBy("mBsi")
Dianne Hackborna8d10942015-11-19 17:55:19 -08009834 public void updateUidProcessStateLocked(int procState) {
9835 int uidRunningState;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009836 // Make special note of Foreground Services
9837 final boolean userAwareService =
9838 (procState == ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009839 uidRunningState = BatteryStats.mapToInternalProcessState(procState);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009840
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009841 if (mProcessState == uidRunningState && userAwareService == mInForegroundService) {
9842 return;
9843 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08009844
Bookatz867c0d72017-03-07 18:23:42 -08009845 final long elapsedRealtimeMs = mBsi.mClocks.elapsedRealtime();
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009846 if (mProcessState != uidRunningState) {
9847 final long uptimeMs = mBsi.mClocks.uptimeMillis();
Dianne Hackborna8d10942015-11-19 17:55:19 -08009848
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009849 if (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
9850 mProcessStateTimer[mProcessState].stopRunningLocked(elapsedRealtimeMs);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009851
Sudheer Shanka5c19b892018-01-05 17:25:46 -08009852 if (mBsi.trackPerProcStateCpuTimes()) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009853 if (mBsi.mPendingUids.size() == 0) {
Sudheer Shankae544d162017-12-28 17:06:20 -08009854 mBsi.mExternalSync.scheduleReadProcStateCpuTimes(
9855 mBsi.mOnBatteryTimeBase.isRunning(),
Sudheer Shankac20379e2018-02-15 00:06:21 -08009856 mBsi.mOnBatteryScreenOffTimeBase.isRunning(),
9857 mBsi.mConstants.PROC_STATE_CPU_TIMES_READ_DELAY_MS);
Mike Ma234d1822018-03-13 18:53:21 -07009858 mBsi.mNumSingleUidCpuTimeReads++;
Sudheer Shankac20379e2018-02-15 00:06:21 -08009859 } else {
Mike Ma234d1822018-03-13 18:53:21 -07009860 mBsi.mNumBatchedSingleUidCpuTimeReads++;
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009861 }
9862 if (mBsi.mPendingUids.indexOfKey(mUid) < 0
9863 || ArrayUtils.contains(CRITICAL_PROC_STATES, mProcessState)) {
9864 mBsi.mPendingUids.put(mUid, mProcessState);
9865 }
9866 } else {
9867 mBsi.mPendingUids.clear();
9868 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07009869 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009870 mProcessState = uidRunningState;
9871 if (uidRunningState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
9872 if (mProcessStateTimer[uidRunningState] == null) {
9873 makeProcessState(uidRunningState, null);
9874 }
9875 mProcessStateTimer[uidRunningState].startRunningLocked(elapsedRealtimeMs);
9876 }
9877
9878 updateOnBatteryBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
9879 updateOnBatteryScreenOffBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009880 }
Bookatz867c0d72017-03-07 18:23:42 -08009881
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009882 if (userAwareService != mInForegroundService) {
9883 if (userAwareService) {
9884 noteForegroundServiceResumedLocked(elapsedRealtimeMs);
9885 } else {
9886 noteForegroundServicePausedLocked(elapsedRealtimeMs);
9887 }
9888 mInForegroundService = userAwareService;
9889 }
Bookatz867c0d72017-03-07 18:23:42 -08009890 }
9891
Bookatzc8c44962017-05-11 12:12:54 -07009892 /** Whether to consider Uid to be in the background for background timebase purposes. */
9893 public boolean isInBackground() {
Bookatz867c0d72017-03-07 18:23:42 -08009894 // Note that PROCESS_STATE_CACHED and ActivityManager.PROCESS_STATE_NONEXISTENT is
9895 // also considered to be 'background' for our purposes, because it's not foreground.
Bookatzc8c44962017-05-11 12:12:54 -07009896 return mProcessState >= PROCESS_STATE_BACKGROUND;
9897 }
9898
9899 public boolean updateOnBatteryBgTimeBase(long uptimeUs, long realtimeUs) {
9900 boolean on = mBsi.mOnBatteryTimeBase.isRunning() && isInBackground();
9901 return mOnBatteryBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
9902 }
9903
9904 public boolean updateOnBatteryScreenOffBgTimeBase(long uptimeUs, long realtimeUs) {
9905 boolean on = mBsi.mOnBatteryScreenOffTimeBase.isRunning() && isInBackground();
9906 return mOnBatteryScreenOffBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009907 }
9908
Dianne Hackbornb5e31652010-09-07 12:13:55 -07009909 public SparseArray<? extends Pid> getPidStats() {
9910 return mPids;
9911 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009912
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009913 public Pid getPidStatsLocked(int pid) {
9914 Pid p = mPids.get(pid);
9915 if (p == null) {
9916 p = new Pid();
9917 mPids.put(pid, p);
9918 }
9919 return p;
9920 }
9921
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009922 /**
9923 * Retrieve the statistics object for a particular service, creating
9924 * if needed.
9925 */
9926 public Pkg getPackageStatsLocked(String name) {
9927 Pkg ps = mPackageStats.get(name);
9928 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08009929 ps = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009930 mPackageStats.put(name, ps);
9931 }
9932
9933 return ps;
9934 }
9935
9936 /**
9937 * Retrieve the statistics object for a particular service, creating
9938 * if needed.
9939 */
9940 public Pkg.Serv getServiceStatsLocked(String pkg, String serv) {
9941 Pkg ps = getPackageStatsLocked(pkg);
9942 Pkg.Serv ss = ps.mServiceStats.get(serv);
9943 if (ss == null) {
9944 ss = ps.newServiceStatsLocked();
9945 ps.mServiceStats.put(serv, ss);
9946 }
9947
9948 return ss;
9949 }
9950
Dianne Hackbornd953c532014-08-16 18:17:38 -07009951 public void readSyncSummaryFromParcelLocked(String name, Parcel in) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009952 DualTimer timer = mSyncStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07009953 timer.readSummaryFromParcelLocked(in);
9954 mSyncStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009955 }
9956
Dianne Hackbornd953c532014-08-16 18:17:38 -07009957 public void readJobSummaryFromParcelLocked(String name, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07009958 DualTimer timer = mJobStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07009959 timer.readSummaryFromParcelLocked(in);
9960 mJobStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009961 }
9962
Dianne Hackbornd953c532014-08-16 18:17:38 -07009963 public void readWakeSummaryFromParcelLocked(String wlName, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08009964 Wakelock wl = new Wakelock(mBsi, this);
Dianne Hackbornd953c532014-08-16 18:17:38 -07009965 mWakelockStats.add(wlName, wl);
9966 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009967 getWakelockTimerLocked(wl, WAKE_TYPE_FULL).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009968 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07009969 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009970 getWakelockTimerLocked(wl, WAKE_TYPE_PARTIAL).readSummaryFromParcelLocked(in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07009971 }
9972 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009973 getWakelockTimerLocked(wl, WAKE_TYPE_WINDOW).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009974 }
Adam Lesinski9425fe22015-06-19 12:02:13 -07009975 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009976 getWakelockTimerLocked(wl, WAKE_TYPE_DRAW).readSummaryFromParcelLocked(in);
Adam Lesinski9425fe22015-06-19 12:02:13 -07009977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009978 }
9979
Bookatz867c0d72017-03-07 18:23:42 -08009980 public DualTimer getSensorTimerLocked(int sensor, boolean create) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009981 Sensor se = mSensorStats.get(sensor);
9982 if (se == null) {
9983 if (!create) {
9984 return null;
9985 }
Joe Onoratoabded112016-02-08 16:49:39 -08009986 se = new Sensor(mBsi, this, sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009987 mSensorStats.put(sensor, se);
9988 }
Bookatz867c0d72017-03-07 18:23:42 -08009989 DualTimer t = se.mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009990 if (t != null) {
9991 return t;
9992 }
Joe Onoratoabded112016-02-08 16:49:39 -08009993 ArrayList<StopwatchTimer> timers = mBsi.mSensorTimers.get(sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009994 if (timers == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07009995 timers = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08009996 mBsi.mSensorTimers.put(sensor, timers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009997 }
Bookatz867c0d72017-03-07 18:23:42 -08009998 t = new DualTimer(mBsi.mClocks, this, BatteryStats.SENSOR, timers,
9999 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010000 se.mTimer = t;
10001 return t;
10002 }
10003
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010004 public void noteStartSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -070010005 DualTimer t = mSyncStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010006 if (t != null) {
10007 t.startRunningLocked(elapsedRealtimeMs);
10008 }
10009 }
10010
10011 public void noteStopSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -070010012 DualTimer t = mSyncStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010013 if (t != null) {
10014 t.stopRunningLocked(elapsedRealtimeMs);
10015 }
10016 }
10017
10018 public void noteStartJobLocked(String name, long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -070010019 DualTimer t = mJobStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010020 if (t != null) {
10021 t.startRunningLocked(elapsedRealtimeMs);
10022 }
10023 }
10024
Dianne Hackborn94326cb2017-06-28 16:17:20 -070010025 public void noteStopJobLocked(String name, long elapsedRealtimeMs, int stopReason) {
Bookatzaa4594a2017-03-24 12:39:56 -070010026 DualTimer t = mJobStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010027 if (t != null) {
10028 t.stopRunningLocked(elapsedRealtimeMs);
10029 }
Dianne Hackborn94326cb2017-06-28 16:17:20 -070010030 if (mBsi.mOnBatteryTimeBase.isRunning()) {
10031 SparseIntArray types = mJobCompletions.get(name);
10032 if (types == null) {
10033 types = new SparseIntArray();
10034 mJobCompletions.put(name, types);
10035 }
10036 int last = types.get(stopReason, 0);
10037 types.put(stopReason, last + 1);
10038 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010039 }
10040
Bookatz5b5ec322017-05-26 09:40:38 -070010041 public StopwatchTimer getWakelockTimerLocked(Wakelock wl, int type) {
10042 if (wl == null) {
10043 return null;
10044 }
10045 switch (type) {
10046 case WAKE_TYPE_PARTIAL: {
10047 DualTimer t = wl.mTimerPartial;
10048 if (t == null) {
10049 t = new DualTimer(mBsi.mClocks, this, WAKE_TYPE_PARTIAL,
10050 mBsi.mPartialTimers, mBsi.mOnBatteryScreenOffTimeBase,
10051 mOnBatteryScreenOffBackgroundTimeBase);
10052 wl.mTimerPartial = t;
10053 }
10054 return t;
10055 }
10056 case WAKE_TYPE_FULL: {
10057 StopwatchTimer t = wl.mTimerFull;
10058 if (t == null) {
10059 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_FULL,
10060 mBsi.mFullTimers, mBsi.mOnBatteryTimeBase);
10061 wl.mTimerFull = t;
10062 }
10063 return t;
10064 }
10065 case WAKE_TYPE_WINDOW: {
10066 StopwatchTimer t = wl.mTimerWindow;
10067 if (t == null) {
10068 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_WINDOW,
10069 mBsi.mWindowTimers, mBsi.mOnBatteryTimeBase);
10070 wl.mTimerWindow = t;
10071 }
10072 return t;
10073 }
10074 case WAKE_TYPE_DRAW: {
10075 StopwatchTimer t = wl.mTimerDraw;
10076 if (t == null) {
10077 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_DRAW,
10078 mBsi.mDrawTimers, mBsi.mOnBatteryTimeBase);
10079 wl.mTimerDraw = t;
10080 }
10081 return t;
10082 }
10083 default:
10084 throw new IllegalArgumentException("type=" + type);
10085 }
10086 }
10087
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010088 public void noteStartWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070010089 Wakelock wl = mWakelockStats.startObject(name);
10090 if (wl != null) {
Bookatz5b5ec322017-05-26 09:40:38 -070010091 getWakelockTimerLocked(wl, type).startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010092 }
Bookatzc8c44962017-05-11 12:12:54 -070010093 if (type == WAKE_TYPE_PARTIAL) {
10094 createAggregatedPartialWakelockTimerLocked().startRunningLocked(elapsedRealtimeMs);
10095 if (pid >= 0) {
10096 Pid p = getPidStatsLocked(pid);
10097 if (p.mWakeNesting++ == 0) {
10098 p.mWakeStartMs = elapsedRealtimeMs;
10099 }
Dianne Hackbornb8071d792010-09-09 16:45:15 -070010100 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010101 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010102 }
10103
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010104 public void noteStopWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070010105 Wakelock wl = mWakelockStats.stopObject(name);
10106 if (wl != null) {
Bookatzd6746242017-10-24 18:39:35 -070010107 StopwatchTimer wlt = getWakelockTimerLocked(wl, type);
10108 wlt.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010109 }
Bookatzc8c44962017-05-11 12:12:54 -070010110 if (type == WAKE_TYPE_PARTIAL) {
10111 if (mAggregatedPartialWakelockTimer != null) {
10112 mAggregatedPartialWakelockTimer.stopRunningLocked(elapsedRealtimeMs);
10113 }
10114 if (pid >= 0) {
10115 Pid p = mPids.get(pid);
10116 if (p != null && p.mWakeNesting > 0) {
10117 if (p.mWakeNesting-- == 1) {
10118 p.mWakeSumMs += elapsedRealtimeMs - p.mWakeStartMs;
10119 p.mWakeStartMs = 0;
10120 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -080010121 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010122 }
10123 }
10124 }
10125
Dianne Hackborn287952c2010-09-22 22:34:31 -070010126 public void reportExcessiveCpuLocked(String proc, long overTime, long usedTime) {
10127 Proc p = getProcessStatsLocked(proc);
10128 if (p != null) {
10129 p.addExcessiveCpu(overTime, usedTime);
10130 }
10131 }
10132
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010133 public void noteStartSensor(int sensor, long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -080010134 DualTimer t = getSensorTimerLocked(sensor, /* create= */ true);
Amith Yamasani154d1242017-02-16 10:01:48 -080010135 t.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010136 }
10137
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010138 public void noteStopSensor(int sensor, long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010139 // Don't create a timer if one doesn't already exist
Bookatz867c0d72017-03-07 18:23:42 -080010140 DualTimer t = getSensorTimerLocked(sensor, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010141 if (t != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010142 t.stopRunningLocked(elapsedRealtimeMs);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010143 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010144 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010145
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010146 public void noteStartGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -080010147 noteStartSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010148 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010149
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010150 public void noteStopGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -080010151 noteStopSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010152 }
10153
10154 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -080010155 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010156 }
10157 }
10158
Sudheer Shanka9b735c52017-05-09 18:26:18 -070010159 public long[] getCpuFreqs() {
10160 return mCpuFreqs;
10161 }
10162
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010163 public BatteryStatsImpl(File systemDir, Handler handler, PlatformIdleStateCallback cb,
10164 UserInfoProvider userInfoProvider) {
10165 this(new SystemClocks(), systemDir, handler, cb, userInfoProvider);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010166 }
10167
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010168 private BatteryStatsImpl(Clocks clocks, File systemDir, Handler handler,
10169 PlatformIdleStateCallback cb,
10170 UserInfoProvider userInfoProvider) {
Joe Onoratoabded112016-02-08 16:49:39 -080010171 init(clocks);
10172
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010173 if (systemDir != null) {
10174 mFile = new JournaledFile(new File(systemDir, "batterystats.bin"),
10175 new File(systemDir, "batterystats.bin.tmp"));
10176 } else {
10177 mFile = null;
10178 }
10179 mCheckinFile = new AtomicFile(new File(systemDir, "batterystats-checkin.bin"));
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010180 mDailyFile = new AtomicFile(new File(systemDir, "batterystats-daily.xml"));
Jeff Brown6f357d32014-01-15 20:40:55 -080010181 mHandler = new MyHandler(handler.getLooper());
Sudheer Shanka5c19b892018-01-05 17:25:46 -080010182 mConstants = new Constants(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010183 mStartCount++;
Joe Onoratoabded112016-02-08 16:49:39 -080010184 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -070010185 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -070010186 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010187 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010188 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010189 }
Joe Onoratoabded112016-02-08 16:49:39 -080010190 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase);
10191 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
10192 mOnBatteryTimeBase);
10193 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -11, null,
10194 mOnBatteryTimeBase);
10195 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
10196 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null, mOnBatteryTimeBase);
10197 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase);
10198 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase);
10199 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
10200 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i, null,
10201 mOnBatteryTimeBase);
10202 }
10203 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
10204 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010205 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010206 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010207 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010208 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010209 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010210 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
10211 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010212 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010213 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase, NUM_WIFI_TX_LEVELS);
10214 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
10215 NUM_BT_TX_LEVELS);
10216 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
10217 ModemActivityInfo.TX_POWER_LEVELS);
Joe Onoratoabded112016-02-08 16:49:39 -080010218 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null, mOnBatteryTimeBase);
10219 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
10220 mOnBatteryTimeBase);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010221 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010222 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase);
10223 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080010224 mWifiMulticastWakelockTimer = new StopwatchTimer(mClocks, null,
10225 WIFI_AGGREGATE_MULTICAST_ENABLED, null, mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -080010226 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase);
10227 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null, mOnBatteryTimeBase);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010228 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010229 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i, null,
Dianne Hackborn3251b902014-06-20 14:40:53 -070010230 mOnBatteryTimeBase);
10231 }
Joe Onoratoabded112016-02-08 16:49:39 -080010232 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
10233 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i, null,
10234 mOnBatteryTimeBase);
10235 }
10236 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
10237 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i, null,
10238 mOnBatteryTimeBase);
10239 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080010240 mWifiActiveTimer = new StopwatchTimer(mClocks, null, -900, null, mOnBatteryTimeBase);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080010241 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
10242 mGpsSignalQualityTimer[i] = new StopwatchTimer(mClocks, null, -1000-i, null,
10243 mOnBatteryTimeBase);
10244 }
Joe Onoratoabded112016-02-08 16:49:39 -080010245 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
10246 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
10247 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase);
10248 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase);
10249 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010250 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -070010251 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Mike Ma15313c92017-11-15 17:58:21 -080010252 mDischargeLightDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
10253 mDischargeDeepDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010254 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010255 mOnBattery = mOnBatteryInternal = false;
Joe Onoratoabded112016-02-08 16:49:39 -080010256 long uptime = mClocks.uptimeMillis() * 1000;
10257 long realtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010258 initTimes(uptime, realtime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070010259 mStartPlatformVersion = mEndPlatformVersion = Build.ID;
Evan Millar633a1742009-04-02 16:36:33 -070010260 mDischargeStartLevel = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010261 mDischargeUnplugLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010262 mDischargePlugLevel = -1;
Evan Millar633a1742009-04-02 16:36:33 -070010263 mDischargeCurrentLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010264 mCurrentBatteryLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010265 initDischarge();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010266 clearHistoryLocked();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010267 updateDailyDeadlineLocked();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010268 mPlatformIdleStateCallback = cb;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010269 mUserInfoProvider = userInfoProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010270 }
10271
Mathew Inwoodc185f082018-08-20 14:28:54 +010010272 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010273 public BatteryStatsImpl(Parcel p) {
Joe Onoratoabded112016-02-08 16:49:39 -080010274 this(new SystemClocks(), p);
10275 }
10276
10277 public BatteryStatsImpl(Clocks clocks, Parcel p) {
10278 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070010279 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010280 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010281 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -070010282 mHandler = null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010283 mExternalSync = null;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080010284 mConstants = new Constants(mHandler);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010285 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010286 readFromParcel(p);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010287 mPlatformIdleStateCallback = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010288 }
10289
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010290 public void setPowerProfileLocked(PowerProfile profile) {
10291 mPowerProfile = profile;
Adam Lesinski6832f392015-09-05 18:05:40 -070010292
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010293 // We need to initialize the KernelCpuSpeedReaders to read from
10294 // the first cpu of each core. Once we have the PowerProfile, we have access to this
10295 // information.
10296 final int numClusters = mPowerProfile.getNumCpuClusters();
10297 mKernelCpuSpeedReaders = new KernelCpuSpeedReader[numClusters];
10298 int firstCpuOfCluster = 0;
10299 for (int i = 0; i < numClusters; i++) {
10300 final int numSpeedSteps = mPowerProfile.getNumSpeedStepsInCpuCluster(i);
10301 mKernelCpuSpeedReaders[i] = new KernelCpuSpeedReader(firstCpuOfCluster,
10302 numSpeedSteps);
10303 firstCpuOfCluster += mPowerProfile.getNumCoresInCpuCluster(i);
10304 }
Adam Lesinskif9b20a92016-06-17 17:30:01 -070010305
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010306 if (mEstimatedBatteryCapacity == -1) {
10307 // Initialize the estimated battery capacity to a known preset one.
10308 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
Adam Lesinskie08af192015-03-25 16:42:59 -070010309 }
10310 }
10311
Dianne Hackborn0d903a82010-09-07 23:51:03 -070010312 public void setCallback(BatteryCallback cb) {
10313 mCallback = cb;
10314 }
10315
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010316 public void setRadioScanningTimeoutLocked(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -070010317 if (mPhoneSignalScanningTimer != null) {
10318 mPhoneSignalScanningTimer.setTimeout(timeout);
10319 }
10320 }
10321
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070010322 public void setExternalStatsSyncLocked(ExternalStatsSync sync) {
10323 mExternalSync = sync;
10324 }
10325
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010326 public void updateDailyDeadlineLocked() {
10327 // Get the current time.
10328 long currentTime = mDailyStartTime = System.currentTimeMillis();
10329 Calendar calDeadline = Calendar.getInstance();
10330 calDeadline.setTimeInMillis(currentTime);
10331
10332 // Move time up to the next day, ranging from 1am to 3pm.
10333 calDeadline.set(Calendar.DAY_OF_YEAR, calDeadline.get(Calendar.DAY_OF_YEAR) + 1);
10334 calDeadline.set(Calendar.MILLISECOND, 0);
10335 calDeadline.set(Calendar.SECOND, 0);
10336 calDeadline.set(Calendar.MINUTE, 0);
10337 calDeadline.set(Calendar.HOUR_OF_DAY, 1);
10338 mNextMinDailyDeadline = calDeadline.getTimeInMillis();
10339 calDeadline.set(Calendar.HOUR_OF_DAY, 3);
10340 mNextMaxDailyDeadline = calDeadline.getTimeInMillis();
10341 }
10342
10343 public void recordDailyStatsIfNeededLocked(boolean settled) {
10344 long currentTime = System.currentTimeMillis();
10345 if (currentTime >= mNextMaxDailyDeadline) {
10346 recordDailyStatsLocked();
10347 } else if (settled && currentTime >= mNextMinDailyDeadline) {
10348 recordDailyStatsLocked();
10349 } else if (currentTime < (mDailyStartTime-(1000*60*60*24))) {
10350 recordDailyStatsLocked();
10351 }
10352 }
10353
10354 public void recordDailyStatsLocked() {
10355 DailyItem item = new DailyItem();
10356 item.mStartTime = mDailyStartTime;
10357 item.mEndTime = System.currentTimeMillis();
10358 boolean hasData = false;
10359 if (mDailyDischargeStepTracker.mNumStepDurations > 0) {
10360 hasData = true;
10361 item.mDischargeSteps = new LevelStepTracker(
10362 mDailyDischargeStepTracker.mNumStepDurations,
10363 mDailyDischargeStepTracker.mStepDurations);
10364 }
10365 if (mDailyChargeStepTracker.mNumStepDurations > 0) {
10366 hasData = true;
10367 item.mChargeSteps = new LevelStepTracker(
10368 mDailyChargeStepTracker.mNumStepDurations,
10369 mDailyChargeStepTracker.mStepDurations);
10370 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010371 if (mDailyPackageChanges != null) {
10372 hasData = true;
10373 item.mPackageChanges = mDailyPackageChanges;
10374 mDailyPackageChanges = null;
10375 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010376 mDailyDischargeStepTracker.init();
10377 mDailyChargeStepTracker.init();
10378 updateDailyDeadlineLocked();
10379
10380 if (hasData) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080010381 final long startTime = SystemClock.uptimeMillis();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010382 mDailyItems.add(item);
10383 while (mDailyItems.size() > MAX_DAILY_ITEMS) {
10384 mDailyItems.remove(0);
10385 }
10386 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
10387 try {
10388 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010010389 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010390 writeDailyItemsLocked(out);
Dianne Hackborne17b4452018-01-10 13:15:40 -080010391 final long initialTime = SystemClock.uptimeMillis() - startTime;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010392 BackgroundThread.getHandler().post(new Runnable() {
10393 @Override
10394 public void run() {
10395 synchronized (mCheckinFile) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080010396 final long startTime2 = SystemClock.uptimeMillis();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010397 FileOutputStream stream = null;
10398 try {
10399 stream = mDailyFile.startWrite();
10400 memStream.writeTo(stream);
10401 stream.flush();
10402 FileUtils.sync(stream);
10403 stream.close();
10404 mDailyFile.finishWrite(stream);
Dianne Hackborne17b4452018-01-10 13:15:40 -080010405 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
10406 "batterystats-daily",
10407 initialTime + SystemClock.uptimeMillis() - startTime2);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010408 } catch (IOException e) {
10409 Slog.w("BatteryStats",
10410 "Error writing battery daily items", e);
10411 mDailyFile.failWrite(stream);
10412 }
10413 }
10414 }
10415 });
10416 } catch (IOException e) {
10417 }
10418 }
10419 }
10420
10421 private void writeDailyItemsLocked(XmlSerializer out) throws IOException {
10422 StringBuilder sb = new StringBuilder(64);
10423 out.startDocument(null, true);
10424 out.startTag(null, "daily-items");
10425 for (int i=0; i<mDailyItems.size(); i++) {
10426 final DailyItem dit = mDailyItems.get(i);
10427 out.startTag(null, "item");
10428 out.attribute(null, "start", Long.toString(dit.mStartTime));
10429 out.attribute(null, "end", Long.toString(dit.mEndTime));
10430 writeDailyLevelSteps(out, "dis", dit.mDischargeSteps, sb);
10431 writeDailyLevelSteps(out, "chg", dit.mChargeSteps, sb);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010432 if (dit.mPackageChanges != null) {
10433 for (int j=0; j<dit.mPackageChanges.size(); j++) {
10434 PackageChange pc = dit.mPackageChanges.get(j);
10435 if (pc.mUpdate) {
10436 out.startTag(null, "upd");
10437 out.attribute(null, "pkg", pc.mPackageName);
Dianne Hackborn3accca02013-09-20 09:32:11 -070010438 out.attribute(null, "ver", Long.toString(pc.mVersionCode));
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010439 out.endTag(null, "upd");
10440 } else {
10441 out.startTag(null, "rem");
10442 out.attribute(null, "pkg", pc.mPackageName);
10443 out.endTag(null, "rem");
10444 }
10445 }
10446 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010447 out.endTag(null, "item");
10448 }
10449 out.endTag(null, "daily-items");
10450 out.endDocument();
10451 }
10452
10453 private void writeDailyLevelSteps(XmlSerializer out, String tag, LevelStepTracker steps,
10454 StringBuilder tmpBuilder) throws IOException {
10455 if (steps != null) {
10456 out.startTag(null, tag);
10457 out.attribute(null, "n", Integer.toString(steps.mNumStepDurations));
10458 for (int i=0; i<steps.mNumStepDurations; i++) {
10459 out.startTag(null, "s");
10460 tmpBuilder.setLength(0);
10461 steps.encodeEntryAt(i, tmpBuilder);
10462 out.attribute(null, "v", tmpBuilder.toString());
10463 out.endTag(null, "s");
10464 }
10465 out.endTag(null, tag);
10466 }
10467 }
10468
10469 public void readDailyStatsLocked() {
10470 Slog.d(TAG, "Reading daily items from " + mDailyFile.getBaseFile());
10471 mDailyItems.clear();
10472 FileInputStream stream;
10473 try {
10474 stream = mDailyFile.openRead();
10475 } catch (FileNotFoundException e) {
10476 return;
10477 }
10478 try {
10479 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010010480 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010481 readDailyItemsLocked(parser);
10482 } catch (XmlPullParserException e) {
10483 } finally {
10484 try {
10485 stream.close();
10486 } catch (IOException e) {
10487 }
10488 }
10489 }
10490
10491 private void readDailyItemsLocked(XmlPullParser parser) {
10492 try {
10493 int type;
10494 while ((type = parser.next()) != XmlPullParser.START_TAG
10495 && type != XmlPullParser.END_DOCUMENT) {
10496 ;
10497 }
10498
10499 if (type != XmlPullParser.START_TAG) {
10500 throw new IllegalStateException("no start tag found");
10501 }
10502
10503 int outerDepth = parser.getDepth();
10504 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10505 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10506 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10507 continue;
10508 }
10509
10510 String tagName = parser.getName();
10511 if (tagName.equals("item")) {
10512 readDailyItemTagLocked(parser);
10513 } else {
10514 Slog.w(TAG, "Unknown element under <daily-items>: "
10515 + parser.getName());
10516 XmlUtils.skipCurrentTag(parser);
10517 }
10518 }
10519
10520 } catch (IllegalStateException e) {
10521 Slog.w(TAG, "Failed parsing daily " + e);
10522 } catch (NullPointerException e) {
10523 Slog.w(TAG, "Failed parsing daily " + e);
10524 } catch (NumberFormatException e) {
10525 Slog.w(TAG, "Failed parsing daily " + e);
10526 } catch (XmlPullParserException e) {
10527 Slog.w(TAG, "Failed parsing daily " + e);
10528 } catch (IOException e) {
10529 Slog.w(TAG, "Failed parsing daily " + e);
10530 } catch (IndexOutOfBoundsException e) {
10531 Slog.w(TAG, "Failed parsing daily " + e);
10532 }
10533 }
10534
10535 void readDailyItemTagLocked(XmlPullParser parser) throws NumberFormatException,
10536 XmlPullParserException, IOException {
10537 DailyItem dit = new DailyItem();
10538 String attr = parser.getAttributeValue(null, "start");
10539 if (attr != null) {
10540 dit.mStartTime = Long.parseLong(attr);
10541 }
10542 attr = parser.getAttributeValue(null, "end");
10543 if (attr != null) {
10544 dit.mEndTime = Long.parseLong(attr);
10545 }
10546 int outerDepth = parser.getDepth();
10547 int type;
10548 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10549 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10550 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10551 continue;
10552 }
10553
10554 String tagName = parser.getName();
10555 if (tagName.equals("dis")) {
10556 readDailyItemTagDetailsLocked(parser, dit, false, "dis");
10557 } else if (tagName.equals("chg")) {
10558 readDailyItemTagDetailsLocked(parser, dit, true, "chg");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010559 } else if (tagName.equals("upd")) {
10560 if (dit.mPackageChanges == null) {
10561 dit.mPackageChanges = new ArrayList<>();
10562 }
10563 PackageChange pc = new PackageChange();
10564 pc.mUpdate = true;
10565 pc.mPackageName = parser.getAttributeValue(null, "pkg");
10566 String verStr = parser.getAttributeValue(null, "ver");
Dianne Hackborn3accca02013-09-20 09:32:11 -070010567 pc.mVersionCode = verStr != null ? Long.parseLong(verStr) : 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010568 dit.mPackageChanges.add(pc);
10569 XmlUtils.skipCurrentTag(parser);
10570 } else if (tagName.equals("rem")) {
10571 if (dit.mPackageChanges == null) {
10572 dit.mPackageChanges = new ArrayList<>();
10573 }
10574 PackageChange pc = new PackageChange();
10575 pc.mUpdate = false;
10576 pc.mPackageName = parser.getAttributeValue(null, "pkg");
10577 dit.mPackageChanges.add(pc);
10578 XmlUtils.skipCurrentTag(parser);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010579 } else {
10580 Slog.w(TAG, "Unknown element under <item>: "
10581 + parser.getName());
10582 XmlUtils.skipCurrentTag(parser);
10583 }
10584 }
10585 mDailyItems.add(dit);
10586 }
10587
10588 void readDailyItemTagDetailsLocked(XmlPullParser parser, DailyItem dit, boolean isCharge,
10589 String tag)
10590 throws NumberFormatException, XmlPullParserException, IOException {
10591 final String numAttr = parser.getAttributeValue(null, "n");
10592 if (numAttr == null) {
10593 Slog.w(TAG, "Missing 'n' attribute at " + parser.getPositionDescription());
10594 XmlUtils.skipCurrentTag(parser);
10595 return;
10596 }
10597 final int num = Integer.parseInt(numAttr);
10598 LevelStepTracker steps = new LevelStepTracker(num);
10599 if (isCharge) {
10600 dit.mChargeSteps = steps;
10601 } else {
10602 dit.mDischargeSteps = steps;
10603 }
10604 int i = 0;
10605 int outerDepth = parser.getDepth();
10606 int type;
10607 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10608 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10609 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10610 continue;
10611 }
10612
10613 String tagName = parser.getName();
10614 if ("s".equals(tagName)) {
10615 if (i < num) {
10616 String valueAttr = parser.getAttributeValue(null, "v");
10617 if (valueAttr != null) {
10618 steps.decodeEntryAt(i, valueAttr);
10619 i++;
10620 }
10621 }
10622 } else {
10623 Slog.w(TAG, "Unknown element under <" + tag + ">: "
10624 + parser.getName());
10625 XmlUtils.skipCurrentTag(parser);
10626 }
10627 }
10628 steps.mNumStepDurations = i;
10629 }
10630
10631 @Override
10632 public DailyItem getDailyItemLocked(int daysAgo) {
10633 int index = mDailyItems.size()-1-daysAgo;
10634 return index >= 0 ? mDailyItems.get(index) : null;
10635 }
10636
10637 @Override
10638 public long getCurrentDailyStartTime() {
10639 return mDailyStartTime;
10640 }
10641
10642 @Override
10643 public long getNextMinDailyDeadline() {
10644 return mNextMinDailyDeadline;
10645 }
10646
10647 @Override
10648 public long getNextMaxDailyDeadline() {
10649 return mNextMaxDailyDeadline;
10650 }
10651
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010652 @Override
10653 public boolean startIteratingOldHistoryLocked() {
10654 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
10655 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010656 if ((mHistoryIterator = mHistory) == null) {
10657 return false;
10658 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010659 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010660 mHistoryReadTmp.clear();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010661 mReadOverflow = false;
10662 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010663 return true;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010664 }
10665
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010666 @Override
10667 public boolean getNextOldHistoryLocked(HistoryItem out) {
10668 boolean end = mHistoryBuffer.dataPosition() >= mHistoryBuffer.dataSize();
10669 if (!end) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010670 readHistoryDelta(mHistoryBuffer, mHistoryReadTmp);
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010671 mReadOverflow |= mHistoryReadTmp.cmd == HistoryItem.CMD_OVERFLOW;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010672 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010673 HistoryItem cur = mHistoryIterator;
10674 if (cur == null) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010675 if (!mReadOverflow && !end) {
10676 Slog.w(TAG, "Old history ends before new history!");
10677 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010678 return false;
10679 }
10680 out.setTo(cur);
10681 mHistoryIterator = cur.next;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010682 if (!mReadOverflow) {
10683 if (end) {
10684 Slog.w(TAG, "New history ends before old history!");
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010685 } else if (!out.same(mHistoryReadTmp)) {
Dianne Hackborn8c841092013-06-24 13:46:13 -070010686 PrintWriter pw = new FastPrintWriter(new LogWriter(android.util.Log.WARN, TAG));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010687 pw.println("Histories differ!");
10688 pw.println("Old history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010689 (new HistoryPrinter()).printNextItem(pw, out, 0, false, true);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010690 pw.println("New history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010691 (new HistoryPrinter()).printNextItem(pw, mHistoryReadTmp, 0, false,
10692 true);
Dianne Hackborn8c841092013-06-24 13:46:13 -070010693 pw.flush();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010694 }
10695 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010696 return true;
10697 }
10698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010699 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010700 public void finishIteratingOldHistoryLocked() {
10701 mIteratingHistory = false;
10702 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010703 mHistoryIterator = null;
10704 }
10705
10706 public int getHistoryTotalSize() {
10707 return MAX_HISTORY_BUFFER;
10708 }
10709
10710 public int getHistoryUsedSize() {
10711 return mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010712 }
10713
10714 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +010010715 @UnsupportedAppUsage
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010716 public boolean startIteratingHistoryLocked() {
10717 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
10718 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010719 if (mHistoryBuffer.dataSize() <= 0) {
10720 return false;
10721 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010722 mHistoryBuffer.setDataPosition(0);
10723 mReadOverflow = false;
10724 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010725 mReadHistoryStrings = new String[mHistoryTagPool.size()];
10726 mReadHistoryUids = new int[mHistoryTagPool.size()];
10727 mReadHistoryChars = 0;
10728 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
10729 final HistoryTag tag = ent.getKey();
10730 final int idx = ent.getValue();
10731 mReadHistoryStrings[idx] = tag.string;
10732 mReadHistoryUids[idx] = tag.uid;
10733 mReadHistoryChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080010734 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010735 return true;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010736 }
10737
10738 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -080010739 public int getHistoryStringPoolSize() {
10740 return mReadHistoryStrings.length;
10741 }
10742
10743 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010744 public int getHistoryStringPoolBytes() {
10745 // Each entry is a fixed 12 bytes: 4 for index, 4 for uid, 4 for string size
10746 // Each string character is 2 bytes.
10747 return (mReadHistoryStrings.length * 12) + (mReadHistoryChars * 2);
10748 }
10749
10750 @Override
10751 public String getHistoryTagPoolString(int index) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080010752 return mReadHistoryStrings[index];
10753 }
10754
10755 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010756 public int getHistoryTagPoolUid(int index) {
10757 return mReadHistoryUids[index];
10758 }
10759
10760 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +010010761 @UnsupportedAppUsage
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010762 public boolean getNextHistoryLocked(HistoryItem out) {
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010763 final int pos = mHistoryBuffer.dataPosition();
10764 if (pos == 0) {
10765 out.clear();
10766 }
10767 boolean end = pos >= mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010768 if (end) {
10769 return false;
10770 }
10771
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010772 final long lastRealtime = out.time;
10773 final long lastWalltime = out.currentTime;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010774 readHistoryDelta(mHistoryBuffer, out);
Dianne Hackborn37de0982014-05-09 09:32:18 -070010775 if (out.cmd != HistoryItem.CMD_CURRENT_TIME
10776 && out.cmd != HistoryItem.CMD_RESET && lastWalltime != 0) {
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010777 out.currentTime = lastWalltime + (out.time - lastRealtime);
10778 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010779 return true;
10780 }
10781
10782 @Override
10783 public void finishIteratingHistoryLocked() {
10784 mIteratingHistory = false;
10785 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn099bc622014-01-22 13:39:16 -080010786 mReadHistoryStrings = null;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010787 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010788
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010789 @Override
Dianne Hackbornb5e31652010-09-07 12:13:55 -070010790 public long getHistoryBaseTime() {
10791 return mHistoryBaseTime;
10792 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010793
Dianne Hackbornb5e31652010-09-07 12:13:55 -070010794 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010795 public int getStartCount() {
10796 return mStartCount;
10797 }
10798
Mathew Inwoodc185f082018-08-20 14:28:54 +010010799 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010800 public boolean isOnBattery() {
10801 return mOnBattery;
10802 }
10803
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010804 public boolean isCharging() {
10805 return mCharging;
10806 }
10807
Mike Mac2f518a2017-09-19 16:06:03 -070010808 public boolean isScreenOn(int state) {
Chris Phoenix10a4a642017-09-25 13:21:00 -070010809 return state == Display.STATE_ON || state == Display.STATE_VR
10810 || state == Display.STATE_ON_SUSPEND;
Mike Mac2f518a2017-09-19 16:06:03 -070010811 }
10812
10813 public boolean isScreenOff(int state) {
10814 return state == Display.STATE_OFF;
10815 }
10816
10817 public boolean isScreenDoze(int state) {
10818 return state == Display.STATE_DOZE || state == Display.STATE_DOZE_SUSPEND;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010819 }
10820
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010821 void initTimes(long uptime, long realtime) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080010822 mStartClockTime = System.currentTimeMillis();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010823 mOnBatteryTimeBase.init(uptime, realtime);
10824 mOnBatteryScreenOffTimeBase.init(uptime, realtime);
Dianne Hackborn4590e522014-03-24 13:36:46 -070010825 mRealtime = 0;
10826 mUptime = 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010827 mRealtimeStart = realtime;
Dianne Hackborn4590e522014-03-24 13:36:46 -070010828 mUptimeStart = uptime;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010829 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010830
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010831 void initDischarge() {
10832 mLowDischargeAmountSinceCharge = 0;
10833 mHighDischargeAmountSinceCharge = 0;
10834 mDischargeAmountScreenOn = 0;
10835 mDischargeAmountScreenOnSinceCharge = 0;
10836 mDischargeAmountScreenOff = 0;
10837 mDischargeAmountScreenOffSinceCharge = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010838 mDischargeAmountScreenDoze = 0;
10839 mDischargeAmountScreenDozeSinceCharge = 0;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010840 mDischargeStepTracker.init();
10841 mChargeStepTracker.init();
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010842 mDischargeScreenOffCounter.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -070010843 mDischargeScreenDozeCounter.reset(false);
Mike Ma15313c92017-11-15 17:58:21 -080010844 mDischargeLightDozeCounter.reset(false);
10845 mDischargeDeepDozeCounter.reset(false);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010846 mDischargeCounter.reset(false);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010847 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010848
10849 public void resetAllStatsCmdLocked() {
10850 resetAllStatsLocked();
Joe Onoratoabded112016-02-08 16:49:39 -080010851 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -070010852 long uptime = mSecUptime * 1000;
Joe Onoratoabded112016-02-08 16:49:39 -080010853 long mSecRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010854 long realtime = mSecRealtime * 1000;
10855 mDischargeStartLevel = mHistoryCur.batteryLevel;
10856 pullPendingStateUpdatesLocked();
Dianne Hackborn40c87252014-03-19 16:55:40 -070010857 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010858 mDischargeCurrentLevel = mDischargeUnplugLevel = mDischargePlugLevel
10859 = mCurrentBatteryLevel = mHistoryCur.batteryLevel;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010860 mOnBatteryTimeBase.reset(uptime, realtime);
10861 mOnBatteryScreenOffTimeBase.reset(uptime, realtime);
10862 if ((mHistoryCur.states&HistoryItem.STATE_BATTERY_PLUGGED_FLAG) == 0) {
Mike Mac2f518a2017-09-19 16:06:03 -070010863 if (isScreenOn(mScreenState)) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010864 mDischargeScreenOnUnplugLevel = mHistoryCur.batteryLevel;
Mike Mac2f518a2017-09-19 16:06:03 -070010865 mDischargeScreenDozeUnplugLevel = 0;
10866 mDischargeScreenOffUnplugLevel = 0;
10867 } else if (isScreenDoze(mScreenState)) {
10868 mDischargeScreenOnUnplugLevel = 0;
10869 mDischargeScreenDozeUnplugLevel = mHistoryCur.batteryLevel;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010870 mDischargeScreenOffUnplugLevel = 0;
10871 } else {
10872 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010873 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010874 mDischargeScreenOffUnplugLevel = mHistoryCur.batteryLevel;
10875 }
10876 mDischargeAmountScreenOn = 0;
10877 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010878 mDischargeAmountScreenDoze = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010879 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070010880 initActiveHistoryEventsLocked(mSecRealtime, mSecUptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010881 }
10882
10883 private void resetAllStatsLocked() {
Adam Lesinski8ce36942016-05-26 16:05:35 -070010884 final long uptimeMillis = mClocks.uptimeMillis();
10885 final long elapsedRealtimeMillis = mClocks.elapsedRealtime();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010886 mStartCount = 0;
Adam Lesinski8ce36942016-05-26 16:05:35 -070010887 initTimes(uptimeMillis * 1000, elapsedRealtimeMillis * 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010888 mScreenOnTimer.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -070010889 mScreenDozeTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010890 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010891 mScreenBrightnessTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010892 }
Adam Lesinski1a76a622016-06-22 10:28:47 -070010893
10894 if (mPowerProfile != null) {
10895 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
10896 } else {
10897 mEstimatedBatteryCapacity = -1;
10898 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070010899 mMinLearnedBatteryCapacity = -1;
10900 mMaxLearnedBatteryCapacity = -1;
Jeff Browne95c3cd2014-05-02 16:59:26 -070010901 mInteractiveTimer.reset(false);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070010902 mPowerSaveModeEnabledTimer.reset(false);
Adam Lesinski8ce36942016-05-26 16:05:35 -070010903 mLastIdleTimeStart = elapsedRealtimeMillis;
Dianne Hackborn08c47a52015-10-15 12:38:14 -070010904 mLongestLightIdleTime = 0;
10905 mLongestFullIdleTime = 0;
10906 mDeviceIdleModeLightTimer.reset(false);
10907 mDeviceIdleModeFullTimer.reset(false);
10908 mDeviceLightIdlingTimer.reset(false);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010909 mDeviceIdlingTimer.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010910 mPhoneOnTimer.reset(false);
10911 mAudioOnTimer.reset(false);
10912 mVideoOnTimer.reset(false);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070010913 mFlashlightOnTimer.reset(false);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070010914 mCameraOnTimer.reset(false);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010915 mBluetoothScanTimer.reset(false);
Wink Saville52840902011-02-18 12:40:47 -080010916 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010917 mPhoneSignalStrengthsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010918 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010919 mPhoneSignalScanningTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010920 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010921 mPhoneDataConnectionsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010922 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010923 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010924 mNetworkByteActivityCounters[i].reset(false);
10925 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010926 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010927 mMobileRadioActiveTimer.reset(false);
10928 mMobileRadioActivePerAppTimer.reset(false);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010929 mMobileRadioActiveAdjustedTime.reset(false);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080010930 mMobileRadioActiveUnknownTime.reset(false);
10931 mMobileRadioActiveUnknownCount.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010932 mWifiOnTimer.reset(false);
10933 mGlobalWifiRunningTimer.reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010934 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010935 mWifiStateTimer[i].reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010936 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070010937 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
10938 mWifiSupplStateTimer[i].reset(false);
10939 }
10940 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
10941 mWifiSignalStrengthsTimer[i].reset(false);
10942 }
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080010943 mWifiMulticastWakelockTimer.reset(false);
Siddharth Rayb50a6842017-12-14 15:15:28 -080010944 mWifiActiveTimer.reset(false);
10945 mWifiActivity.reset(false);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080010946 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
10947 mGpsSignalQualityTimer[i].reset(false);
10948 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010949 mBluetoothActivity.reset(false);
10950 mModemActivity.reset(false);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080010951 mNumConnectivityChange = mLoadedNumConnectivityChange = mUnpluggedNumConnectivityChange = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010952
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010953 for (int i=0; i<mUidStats.size(); i++) {
Bookatz993a0be2017-07-21 09:03:23 -070010954 if (mUidStats.valueAt(i).reset(uptimeMillis * 1000, elapsedRealtimeMillis * 1000)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010955 mUidStats.remove(mUidStats.keyAt(i));
10956 i--;
10957 }
10958 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010959
Bookatz50df7112017-08-04 14:53:26 -070010960 if (mRpmStats.size() > 0) {
10961 for (SamplingTimer timer : mRpmStats.values()) {
10962 mOnBatteryTimeBase.remove(timer);
10963 }
10964 mRpmStats.clear();
10965 }
10966 if (mScreenOffRpmStats.size() > 0) {
10967 for (SamplingTimer timer : mScreenOffRpmStats.values()) {
10968 mOnBatteryScreenOffTimeBase.remove(timer);
10969 }
10970 mScreenOffRpmStats.clear();
10971 }
10972
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010973 if (mKernelWakelockStats.size() > 0) {
10974 for (SamplingTimer timer : mKernelWakelockStats.values()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010975 mOnBatteryScreenOffTimeBase.remove(timer);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010976 }
10977 mKernelWakelockStats.clear();
10978 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010979
James Carr3a226052016-07-01 14:49:52 -070010980 if (mKernelMemoryStats.size() > 0) {
10981 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
10982 mOnBatteryTimeBase.remove(mKernelMemoryStats.valueAt(i));
10983 }
10984 mKernelMemoryStats.clear();
10985 }
10986
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010987 if (mWakeupReasonStats.size() > 0) {
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070010988 for (SamplingTimer timer : mWakeupReasonStats.values()) {
10989 mOnBatteryTimeBase.remove(timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010990 }
10991 mWakeupReasonStats.clear();
10992 }
10993
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080010994 mLastHistoryStepDetails = null;
10995 mLastStepCpuUserTime = mLastStepCpuSystemTime = 0;
10996 mCurStepCpuUserTime = mCurStepCpuSystemTime = 0;
10997 mLastStepCpuUserTime = mCurStepCpuUserTime = 0;
10998 mLastStepCpuSystemTime = mCurStepCpuSystemTime = 0;
10999 mLastStepStatUserTime = mCurStepStatUserTime = 0;
11000 mLastStepStatSystemTime = mCurStepStatSystemTime = 0;
11001 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime = 0;
11002 mLastStepStatIrqTime = mCurStepStatIrqTime = 0;
11003 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime = 0;
11004 mLastStepStatIdleTime = mCurStepStatIdleTime = 0;
11005
Mike Ma234d1822018-03-13 18:53:21 -070011006 mNumAllUidCpuTimeReads = 0;
11007 mNumUidsRemoved = 0;
11008
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011009 initDischarge();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011010
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011011 clearHistoryLocked();
Fyodor Kupolov8aa51242018-04-23 12:44:51 -070011012 mHandler.sendEmptyMessage(MSG_REPORT_RESET_STATS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011013 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011014
Dianne Hackborn40c87252014-03-19 16:55:40 -070011015 private void initActiveHistoryEventsLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080011016 for (int i=0; i<HistoryItem.EVENT_COUNT; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011017 if (!mRecordAllHistory && i == HistoryItem.EVENT_PROC) {
11018 // Not recording process starts/stops.
11019 continue;
11020 }
Dianne Hackborn37de0982014-05-09 09:32:18 -070011021 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(i);
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080011022 if (active == null) {
11023 continue;
11024 }
Dianne Hackborn37de0982014-05-09 09:32:18 -070011025 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
11026 SparseIntArray uids = ent.getValue();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080011027 for (int j=0; j<uids.size(); j++) {
Dianne Hackborn37de0982014-05-09 09:32:18 -070011028 addHistoryEventLocked(elapsedRealtimeMs, uptimeMs, i, ent.getKey(),
11029 uids.keyAt(j));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080011030 }
11031 }
11032 }
11033 }
11034
Mike Mac2f518a2017-09-19 16:06:03 -070011035 void updateDischargeScreenLevelsLocked(int oldState, int newState) {
11036 updateOldDischargeScreenLevelLocked(oldState);
11037 updateNewDischargeScreenLevelLocked(newState);
11038 }
11039
11040 private void updateOldDischargeScreenLevelLocked(int state) {
11041 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011042 int diff = mDischargeScreenOnUnplugLevel - mDischargeCurrentLevel;
11043 if (diff > 0) {
11044 mDischargeAmountScreenOn += diff;
11045 mDischargeAmountScreenOnSinceCharge += diff;
11046 }
Mike Mac2f518a2017-09-19 16:06:03 -070011047 } else if (isScreenDoze(state)) {
11048 int diff = mDischargeScreenDozeUnplugLevel - mDischargeCurrentLevel;
11049 if (diff > 0) {
11050 mDischargeAmountScreenDoze += diff;
11051 mDischargeAmountScreenDozeSinceCharge += diff;
11052 }
11053 } else if (isScreenOff(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011054 int diff = mDischargeScreenOffUnplugLevel - mDischargeCurrentLevel;
11055 if (diff > 0) {
11056 mDischargeAmountScreenOff += diff;
11057 mDischargeAmountScreenOffSinceCharge += diff;
11058 }
11059 }
Mike Mac2f518a2017-09-19 16:06:03 -070011060 }
11061
11062 private void updateNewDischargeScreenLevelLocked(int state) {
11063 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011064 mDischargeScreenOnUnplugLevel = mDischargeCurrentLevel;
11065 mDischargeScreenOffUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070011066 mDischargeScreenDozeUnplugLevel = 0;
11067 } else if (isScreenDoze(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011068 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070011069 mDischargeScreenDozeUnplugLevel = mDischargeCurrentLevel;
11070 mDischargeScreenOffUnplugLevel = 0;
11071 } else if (isScreenOff(state)) {
11072 mDischargeScreenOnUnplugLevel = 0;
11073 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011074 mDischargeScreenOffUnplugLevel = mDischargeCurrentLevel;
11075 }
11076 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011077
Dianne Hackborna7c837f2014-01-15 16:20:44 -080011078 public void pullPendingStateUpdatesLocked() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -080011079 if (mOnBatteryInternal) {
Mike Mac2f518a2017-09-19 16:06:03 -070011080 updateDischargeScreenLevelsLocked(mScreenState, mScreenState);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080011081 }
Dianne Hackborna7c837f2014-01-15 16:20:44 -080011082 }
11083
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011084 private final NetworkStatsFactory mNetworkStatsFactory = new NetworkStatsFactory();
11085 private final Pools.Pool<NetworkStats> mNetworkStatsPool = new Pools.SynchronizedPool<>(6);
11086
11087 private final Object mWifiNetworkLock = new Object();
11088
11089 @GuardedBy("mWifiNetworkLock")
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011090 private String[] mWifiIfaces = EmptyArray.STRING;
11091
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011092 @GuardedBy("mWifiNetworkLock")
11093 private NetworkStats mLastWifiNetworkStats = new NetworkStats(0, -1);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011094
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011095 private final Object mModemNetworkLock = new Object();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011096
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011097 @GuardedBy("mModemNetworkLock")
11098 private String[] mModemIfaces = EmptyArray.STRING;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011099
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011100 @GuardedBy("mModemNetworkLock")
11101 private NetworkStats mLastModemNetworkStats = new NetworkStats(0, -1);
11102
11103 private NetworkStats readNetworkStatsLocked(String[] ifaces) {
11104 try {
11105 if (!ArrayUtils.isEmpty(ifaces)) {
11106 return mNetworkStatsFactory.readNetworkStatsDetail(NetworkStats.UID_ALL, ifaces,
11107 NetworkStats.TAG_NONE, mNetworkStatsPool.acquire());
11108 }
11109 } catch (IOException e) {
11110 Slog.e(TAG, "failed to read network stats for ifaces: " + Arrays.toString(ifaces));
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011111 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011112 return null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011113 }
11114
Chenjie Yu89083392018-01-11 14:53:31 -080011115 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011116 * Distribute WiFi energy info and network traffic to apps.
11117 * @param info The energy information from the WiFi controller.
11118 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011119 public void updateWifiState(@Nullable final WifiActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011120 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011121 Slog.d(TAG, "Updating wifi stats: " + Arrays.toString(mWifiIfaces));
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011122 }
11123
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011124 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070011125 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011126 synchronized (mWifiNetworkLock) {
11127 final NetworkStats latestStats = readNetworkStatsLocked(mWifiIfaces);
11128 if (latestStats != null) {
11129 delta = NetworkStats.subtract(latestStats, mLastWifiNetworkStats, null, null,
11130 mNetworkStatsPool.acquire());
11131 mNetworkStatsPool.release(mLastWifiNetworkStats);
11132 mLastWifiNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070011133 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011134 }
11135
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011136 synchronized (this) {
11137 if (!mOnBatteryInternal) {
11138 if (delta != null) {
11139 mNetworkStatsPool.release(delta);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011140 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011141 return;
11142 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011143
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011144 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
11145 SparseLongArray rxPackets = new SparseLongArray();
11146 SparseLongArray txPackets = new SparseLongArray();
11147 long totalTxPackets = 0;
11148 long totalRxPackets = 0;
11149 if (delta != null) {
11150 NetworkStats.Entry entry = new NetworkStats.Entry();
11151 final int size = delta.size();
11152 for (int i = 0; i < size; i++) {
11153 entry = delta.getValues(i, entry);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011154
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011155 if (DEBUG_ENERGY) {
11156 Slog.d(TAG, "Wifi uid " + entry.uid + ": delta rx=" + entry.rxBytes
11157 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
11158 + " txPackets=" + entry.txPackets);
11159 }
11160
11161 if (entry.rxBytes == 0 && entry.txBytes == 0) {
11162 // Skip the lookup below since there is no work to do.
11163 continue;
11164 }
11165
11166 final Uid u = getUidStatsLocked(mapUid(entry.uid));
11167 if (entry.rxBytes != 0) {
11168 u.noteNetworkActivityLocked(NETWORK_WIFI_RX_DATA, entry.rxBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -080011169 entry.rxPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011170 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11171 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_RX_DATA, entry.rxBytes,
11172 entry.rxPackets);
11173 }
11174 mNetworkByteActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
11175 entry.rxBytes);
11176 mNetworkPacketActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
11177 entry.rxPackets);
11178
11179 rxPackets.put(u.getUid(), entry.rxPackets);
11180
11181 // Sum the total number of packets so that the Rx Power can
11182 // be evenly distributed amongst the apps.
11183 totalRxPackets += entry.rxPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -080011184 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011185
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011186 if (entry.txBytes != 0) {
11187 u.noteNetworkActivityLocked(NETWORK_WIFI_TX_DATA, entry.txBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -080011188 entry.txPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011189 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11190 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_TX_DATA, entry.txBytes,
11191 entry.txPackets);
11192 }
11193 mNetworkByteActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
11194 entry.txBytes);
11195 mNetworkPacketActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
11196 entry.txPackets);
11197
11198 txPackets.put(u.getUid(), entry.txPackets);
11199
11200 // Sum the total number of packets so that the Tx Power can
11201 // be evenly distributed amongst the apps.
11202 totalTxPackets += entry.txPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -080011203 }
Adam Lesinskiba88e682015-12-08 12:06:55 -080011204 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011205 mNetworkStatsPool.release(delta);
11206 delta = null;
Adam Lesinskie08af192015-03-25 16:42:59 -070011207 }
11208
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011209 if (info != null) {
11210 mHasWifiReporting = true;
Adam Lesinskie08af192015-03-25 16:42:59 -070011211
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011212 // Measured in mAms
11213 final long txTimeMs = info.getControllerTxTimeMillis();
11214 final long rxTimeMs = info.getControllerRxTimeMillis();
Siddharth Rayb50a6842017-12-14 15:15:28 -080011215 final long scanTimeMs = info.getControllerScanTimeMillis();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011216 final long idleTimeMs = info.getControllerIdleTimeMillis();
11217 final long totalTimeMs = txTimeMs + rxTimeMs + idleTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -070011218
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011219 long leftOverRxTimeMs = rxTimeMs;
11220 long leftOverTxTimeMs = txTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -070011221
Adam Lesinskie08af192015-03-25 16:42:59 -070011222 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011223 Slog.d(TAG, "------ BEGIN WiFi power blaming ------");
11224 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
11225 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
11226 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms");
11227 Slog.d(TAG, " Total Time: " + totalTimeMs + " ms");
Siddharth Rayb50a6842017-12-14 15:15:28 -080011228 Slog.d(TAG, " Scan Time: " + scanTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070011229 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011230
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011231 long totalWifiLockTimeMs = 0;
11232 long totalScanTimeMs = 0;
11233
11234 // On the first pass, collect some totals so that we can normalize power
11235 // calculations if we need to.
11236 final int uidStatsSize = mUidStats.size();
11237 for (int i = 0; i < uidStatsSize; i++) {
11238 final Uid uid = mUidStats.valueAt(i);
11239
11240 // Sum the total scan power for all apps.
11241 totalScanTimeMs += uid.mWifiScanTimer.getTimeSinceMarkLocked(
11242 elapsedRealtimeMs * 1000) / 1000;
11243
11244 // Sum the total time holding wifi lock for all apps.
11245 totalWifiLockTimeMs += uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
11246 elapsedRealtimeMs * 1000) / 1000;
11247 }
11248
11249 if (DEBUG_ENERGY && totalScanTimeMs > rxTimeMs) {
11250 Slog.d(TAG,
11251 " !Estimated scan time > Actual rx time (" + totalScanTimeMs + " ms > "
11252 + rxTimeMs + " ms). Normalizing scan time.");
11253 }
11254 if (DEBUG_ENERGY && totalScanTimeMs > txTimeMs) {
11255 Slog.d(TAG,
11256 " !Estimated scan time > Actual tx time (" + totalScanTimeMs + " ms > "
11257 + txTimeMs + " ms). Normalizing scan time.");
11258 }
11259
11260 // Actually assign and distribute power usage to apps.
11261 for (int i = 0; i < uidStatsSize; i++) {
11262 final Uid uid = mUidStats.valueAt(i);
11263
11264 long scanTimeSinceMarkMs = uid.mWifiScanTimer.getTimeSinceMarkLocked(
11265 elapsedRealtimeMs * 1000) / 1000;
11266 if (scanTimeSinceMarkMs > 0) {
11267 // Set the new mark so that next time we get new data since this point.
11268 uid.mWifiScanTimer.setMark(elapsedRealtimeMs);
11269
11270 long scanRxTimeSinceMarkMs = scanTimeSinceMarkMs;
11271 long scanTxTimeSinceMarkMs = scanTimeSinceMarkMs;
11272
11273 // Our total scan time is more than the reported Tx/Rx time.
11274 // This is possible because the cost of a scan is approximate.
11275 // Let's normalize the result so that we evenly blame each app
11276 // scanning.
11277 //
11278 // This means that we may have apps that transmitted/received packets not be
11279 // blamed for this, but this is fine as scans are relatively more expensive.
11280 if (totalScanTimeMs > rxTimeMs) {
11281 scanRxTimeSinceMarkMs = (rxTimeMs * scanRxTimeSinceMarkMs) /
11282 totalScanTimeMs;
11283 }
11284 if (totalScanTimeMs > txTimeMs) {
11285 scanTxTimeSinceMarkMs = (txTimeMs * scanTxTimeSinceMarkMs) /
11286 totalScanTimeMs;
11287 }
11288
11289 if (DEBUG_ENERGY) {
11290 Slog.d(TAG, " ScanTime for UID " + uid.getUid() + ": Rx:"
11291 + scanRxTimeSinceMarkMs + " ms Tx:"
11292 + scanTxTimeSinceMarkMs + " ms)");
11293 }
11294
11295 ControllerActivityCounterImpl activityCounter =
11296 uid.getOrCreateWifiControllerActivityLocked();
11297 activityCounter.getRxTimeCounter().addCountLocked(scanRxTimeSinceMarkMs);
11298 activityCounter.getTxTimeCounters()[0].addCountLocked(
11299 scanTxTimeSinceMarkMs);
11300 leftOverRxTimeMs -= scanRxTimeSinceMarkMs;
11301 leftOverTxTimeMs -= scanTxTimeSinceMarkMs;
11302 }
11303
11304 // Distribute evenly the power consumed while Idle to each app holding a WiFi
11305 // lock.
11306 final long wifiLockTimeSinceMarkMs =
11307 uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
11308 elapsedRealtimeMs * 1000) / 1000;
11309 if (wifiLockTimeSinceMarkMs > 0) {
11310 // Set the new mark so that next time we get new data since this point.
11311 uid.mFullWifiLockTimer.setMark(elapsedRealtimeMs);
11312
11313 final long myIdleTimeMs = (wifiLockTimeSinceMarkMs * idleTimeMs)
11314 / totalWifiLockTimeMs;
11315 if (DEBUG_ENERGY) {
11316 Slog.d(TAG, " IdleTime for UID " + uid.getUid() + ": "
11317 + myIdleTimeMs + " ms");
11318 }
11319 uid.getOrCreateWifiControllerActivityLocked().getIdleTimeCounter()
11320 .addCountLocked(myIdleTimeMs);
11321 }
11322 }
11323
Adam Lesinskie08af192015-03-25 16:42:59 -070011324 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011325 Slog.d(TAG, " New RxPower: " + leftOverRxTimeMs + " ms");
11326 Slog.d(TAG, " New TxPower: " + leftOverTxTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070011327 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011328
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011329 // Distribute the remaining Tx power appropriately between all apps that transmitted
11330 // packets.
11331 for (int i = 0; i < txPackets.size(); i++) {
11332 final Uid uid = getUidStatsLocked(txPackets.keyAt(i));
11333 final long myTxTimeMs = (txPackets.valueAt(i) * leftOverTxTimeMs)
11334 / totalTxPackets;
11335 if (DEBUG_ENERGY) {
11336 Slog.d(TAG, " TxTime for UID " + uid.getUid() + ": " + myTxTimeMs + " ms");
11337 }
11338 uid.getOrCreateWifiControllerActivityLocked().getTxTimeCounters()[0]
11339 .addCountLocked(myTxTimeMs);
11340 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011341
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011342 // Distribute the remaining Rx power appropriately between all apps that received
11343 // packets.
11344 for (int i = 0; i < rxPackets.size(); i++) {
11345 final Uid uid = getUidStatsLocked(rxPackets.keyAt(i));
11346 final long myRxTimeMs = (rxPackets.valueAt(i) * leftOverRxTimeMs)
11347 / totalRxPackets;
11348 if (DEBUG_ENERGY) {
11349 Slog.d(TAG, " RxTime for UID " + uid.getUid() + ": " + myRxTimeMs + " ms");
11350 }
11351 uid.getOrCreateWifiControllerActivityLocked().getRxTimeCounter()
11352 .addCountLocked(myRxTimeMs);
11353 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011354
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011355 // Any left over power use will be picked up by the WiFi category in BatteryStatsHelper.
11356
11357
11358 // Update WiFi controller stats.
11359 mWifiActivity.getRxTimeCounter().addCountLocked(info.getControllerRxTimeMillis());
11360 mWifiActivity.getTxTimeCounters()[0].addCountLocked(
11361 info.getControllerTxTimeMillis());
Siddharth Rayb50a6842017-12-14 15:15:28 -080011362 mWifiActivity.getScanTimeCounter().addCountLocked(
11363 info.getControllerScanTimeMillis());
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011364 mWifiActivity.getIdleTimeCounter().addCountLocked(
11365 info.getControllerIdleTimeMillis());
11366
11367 // POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11368 final double opVolt = mPowerProfile.getAveragePower(
11369 PowerProfile.POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11370 if (opVolt != 0) {
11371 // We store the power drain as mAms.
11372 mWifiActivity.getPowerCounter().addCountLocked(
11373 (long) (info.getControllerEnergyUsed() / opVolt));
11374 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011375 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011376 }
11377 }
11378
Chenjie Yu89083392018-01-11 14:53:31 -080011379 private ModemActivityInfo mLastModemActivityInfo =
11380 new ModemActivityInfo(0, 0, 0, new int[0], 0, 0);
11381
Chenjie Yua54e54d2018-02-14 20:12:52 -080011382 private ModemActivityInfo getDeltaModemActivityInfo(ModemActivityInfo activityInfo) {
11383 if (activityInfo == null) {
11384 return null;
11385 }
11386 int[] txTimeMs = new int[ModemActivityInfo.TX_POWER_LEVELS];
11387 for (int i = 0; i < ModemActivityInfo.TX_POWER_LEVELS; i++) {
11388 txTimeMs[i] = activityInfo.getTxTimeMillis()[i]
11389 - mLastModemActivityInfo.getTxTimeMillis()[i];
11390 }
11391 ModemActivityInfo deltaInfo = new ModemActivityInfo(activityInfo.getTimestamp(),
11392 activityInfo.getSleepTimeMillis() - mLastModemActivityInfo.getSleepTimeMillis(),
11393 activityInfo.getIdleTimeMillis() - mLastModemActivityInfo.getIdleTimeMillis(),
11394 txTimeMs,
11395 activityInfo.getRxTimeMillis() - mLastModemActivityInfo.getRxTimeMillis(),
11396 activityInfo.getEnergyUsed() - mLastModemActivityInfo.getEnergyUsed());
11397 mLastModemActivityInfo = activityInfo;
11398 return deltaInfo;
11399 }
11400
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011401 /**
11402 * Distribute Cell radio energy info and network traffic to apps.
11403 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011404 public void updateMobileRadioState(@Nullable final ModemActivityInfo activityInfo) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011405 if (DEBUG_ENERGY) {
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011406 Slog.d(TAG, "Updating mobile radio stats with " + activityInfo);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011407 }
Chenjie Yua54e54d2018-02-14 20:12:52 -080011408 ModemActivityInfo deltaInfo = getDeltaModemActivityInfo(activityInfo);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011409
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011410 // Add modem tx power to history.
Chenjie Yua54e54d2018-02-14 20:12:52 -080011411 addModemTxPowerToHistory(deltaInfo);
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011412
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011413 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070011414 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011415 synchronized (mModemNetworkLock) {
11416 final NetworkStats latestStats = readNetworkStatsLocked(mModemIfaces);
11417 if (latestStats != null) {
11418 delta = NetworkStats.subtract(latestStats, mLastModemNetworkStats, null, null,
11419 mNetworkStatsPool.acquire());
11420 mNetworkStatsPool.release(mLastModemNetworkStats);
11421 mLastModemNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070011422 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011423 }
11424
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011425 synchronized (this) {
11426 if (!mOnBatteryInternal) {
11427 if (delta != null) {
11428 mNetworkStatsPool.release(delta);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011429 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011430 return;
Adam Lesinskie08af192015-03-25 16:42:59 -070011431 }
11432
Chenjie Yua54e54d2018-02-14 20:12:52 -080011433 if (deltaInfo != null) {
Siddharth Ray2038af82018-01-17 17:40:26 -080011434 mHasModemReporting = true;
11435 mModemActivity.getIdleTimeCounter().addCountLocked(
Chenjie Yua54e54d2018-02-14 20:12:52 -080011436 deltaInfo.getIdleTimeMillis());
Siddharth Rayed754702018-02-15 12:44:37 -080011437 mModemActivity.getSleepTimeCounter().addCountLocked(
11438 deltaInfo.getSleepTimeMillis());
Chenjie Yua54e54d2018-02-14 20:12:52 -080011439 mModemActivity.getRxTimeCounter().addCountLocked(deltaInfo.getRxTimeMillis());
Siddharth Ray2038af82018-01-17 17:40:26 -080011440 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
11441 mModemActivity.getTxTimeCounters()[lvl]
Chenjie Yua54e54d2018-02-14 20:12:52 -080011442 .addCountLocked(deltaInfo.getTxTimeMillis()[lvl]);
Siddharth Ray2038af82018-01-17 17:40:26 -080011443 }
11444
11445 // POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11446 final double opVolt = mPowerProfile.getAveragePower(
11447 PowerProfile.POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11448 if (opVolt != 0) {
11449 double energyUsed =
Chenjie Yua54e54d2018-02-14 20:12:52 -080011450 deltaInfo.getSleepTimeMillis() *
Siddharth Ray2038af82018-01-17 17:40:26 -080011451 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_SLEEP)
Chenjie Yua54e54d2018-02-14 20:12:52 -080011452 + deltaInfo.getIdleTimeMillis() *
Siddharth Ray2038af82018-01-17 17:40:26 -080011453 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_IDLE)
Chenjie Yua54e54d2018-02-14 20:12:52 -080011454 + deltaInfo.getRxTimeMillis() *
Siddharth Ray2038af82018-01-17 17:40:26 -080011455 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_RX);
Chenjie Yua54e54d2018-02-14 20:12:52 -080011456 int[] txTimeMs = deltaInfo.getTxTimeMillis();
Chenjie Yu89083392018-01-11 14:53:31 -080011457 for (int i = 0; i < Math.min(txTimeMs.length,
Chenjie Yua54e54d2018-02-14 20:12:52 -080011458 SignalStrength.NUM_SIGNAL_STRENGTH_BINS); i++) {
Chenjie Yu89083392018-01-11 14:53:31 -080011459 energyUsed += txTimeMs[i] * mPowerProfile.getAveragePower(
Chenjie Yua54e54d2018-02-14 20:12:52 -080011460 PowerProfile.POWER_MODEM_CONTROLLER_TX, i);
Siddharth Ray2038af82018-01-17 17:40:26 -080011461 }
11462
11463 // We store the power drain as mAms.
11464 mModemActivity.getPowerCounter().addCountLocked((long) energyUsed);
11465 }
11466 }
11467
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070011468 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011469 long radioTime = mMobileRadioActivePerAppTimer.getTimeSinceMarkLocked(
11470 elapsedRealtimeMs * 1000);
11471 mMobileRadioActivePerAppTimer.setMark(elapsedRealtimeMs);
11472
11473 long totalRxPackets = 0;
11474 long totalTxPackets = 0;
11475 if (delta != null) {
11476 NetworkStats.Entry entry = new NetworkStats.Entry();
11477 final int size = delta.size();
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011478 for (int i = 0; i < size; i++) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011479 entry = delta.getValues(i, entry);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011480 if (entry.rxPackets == 0 && entry.txPackets == 0) {
11481 continue;
11482 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011483
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011484 if (DEBUG_ENERGY) {
11485 Slog.d(TAG, "Mobile uid " + entry.uid + ": delta rx=" + entry.rxBytes
11486 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
11487 + " txPackets=" + entry.txPackets);
11488 }
11489
11490 totalRxPackets += entry.rxPackets;
11491 totalTxPackets += entry.txPackets;
11492
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011493 final Uid u = getUidStatsLocked(mapUid(entry.uid));
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011494 u.noteNetworkActivityLocked(NETWORK_MOBILE_RX_DATA, entry.rxBytes,
11495 entry.rxPackets);
11496 u.noteNetworkActivityLocked(NETWORK_MOBILE_TX_DATA, entry.txBytes,
11497 entry.txPackets);
11498 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11499 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_RX_DATA,
11500 entry.rxBytes, entry.rxPackets);
11501 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_TX_DATA,
11502 entry.txBytes, entry.txPackets);
11503 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011504
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011505 mNetworkByteActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
11506 entry.rxBytes);
11507 mNetworkByteActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
11508 entry.txBytes);
11509 mNetworkPacketActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
11510 entry.rxPackets);
11511 mNetworkPacketActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
11512 entry.txPackets);
11513 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011514
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011515 // Now distribute proportional blame to the apps that did networking.
11516 long totalPackets = totalRxPackets + totalTxPackets;
11517 if (totalPackets > 0) {
11518 for (int i = 0; i < size; i++) {
11519 entry = delta.getValues(i, entry);
11520 if (entry.rxPackets == 0 && entry.txPackets == 0) {
11521 continue;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011522 }
11523
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011524 final Uid u = getUidStatsLocked(mapUid(entry.uid));
11525
11526 // Distribute total radio active time in to this app.
11527 final long appPackets = entry.rxPackets + entry.txPackets;
11528 final long appRadioTime = (radioTime * appPackets) / totalPackets;
11529 u.noteMobileRadioActiveTimeLocked(appRadioTime);
11530
11531 // Remove this app from the totals, so that we don't lose any time
11532 // due to rounding.
11533 radioTime -= appRadioTime;
11534 totalPackets -= appPackets;
11535
Chenjie Yua54e54d2018-02-14 20:12:52 -080011536 if (deltaInfo != null) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011537 ControllerActivityCounterImpl activityCounter =
11538 u.getOrCreateModemControllerActivityLocked();
11539 if (totalRxPackets > 0 && entry.rxPackets > 0) {
Chenjie Yua54e54d2018-02-14 20:12:52 -080011540 final long rxMs = (entry.rxPackets * deltaInfo.getRxTimeMillis())
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011541 / totalRxPackets;
11542 activityCounter.getRxTimeCounter().addCountLocked(rxMs);
11543 }
11544
11545 if (totalTxPackets > 0 && entry.txPackets > 0) {
11546 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
11547 long txMs =
Chenjie Yua54e54d2018-02-14 20:12:52 -080011548 entry.txPackets * deltaInfo.getTxTimeMillis()[lvl];
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011549 txMs /= totalTxPackets;
11550 activityCounter.getTxTimeCounters()[lvl].addCountLocked(txMs);
11551 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011552 }
11553 }
11554 }
11555 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011556
11557 if (radioTime > 0) {
11558 // Whoops, there is some radio time we can't blame on an app!
11559 mMobileRadioActiveUnknownTime.addCountLocked(radioTime);
11560 mMobileRadioActiveUnknownCount.addCountLocked(1);
11561 }
11562
11563 mNetworkStatsPool.release(delta);
11564 delta = null;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011565 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011566 }
11567 }
11568
11569 /**
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011570 * Add modem tx power to history
11571 * Device is said to be in high cellular transmit power when it has spent most of the transmit
11572 * time at the highest power level.
11573 * @param activityInfo
11574 */
Siddharth Raya67fb562018-02-28 13:46:16 -080011575 private synchronized void addModemTxPowerToHistory(final ModemActivityInfo activityInfo) {
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011576 if (activityInfo == null) {
11577 return;
11578 }
11579 int[] txTimeMs = activityInfo.getTxTimeMillis();
11580 if (txTimeMs == null || txTimeMs.length != ModemActivityInfo.TX_POWER_LEVELS) {
11581 return;
11582 }
11583 final long elapsedRealtime = mClocks.elapsedRealtime();
11584 final long uptime = mClocks.uptimeMillis();
11585 int levelMaxTimeSpent = 0;
11586 for (int i = 1; i < txTimeMs.length; i++) {
11587 if (txTimeMs[i] > txTimeMs[levelMaxTimeSpent]) {
11588 levelMaxTimeSpent = i;
11589 }
11590 }
11591 if (levelMaxTimeSpent == ModemActivityInfo.TX_POWER_LEVELS - 1) {
11592 if (!mIsCellularTxPowerHigh) {
11593 mHistoryCur.states2 |= HistoryItem.STATE2_CELLULAR_HIGH_TX_POWER_FLAG;
11594 addHistoryRecordLocked(elapsedRealtime, uptime);
11595 mIsCellularTxPowerHigh = true;
11596 }
11597 return;
11598 }
11599 if (mIsCellularTxPowerHigh) {
11600 mHistoryCur.states2 &= ~HistoryItem.STATE2_CELLULAR_HIGH_TX_POWER_FLAG;
11601 addHistoryRecordLocked(elapsedRealtime, uptime);
11602 mIsCellularTxPowerHigh = false;
11603 }
11604 return;
11605 }
11606
Mike Ma561a8d92018-03-20 18:24:05 -070011607 private final class BluetoothActivityInfoCache {
11608 long idleTimeMs;
11609 long rxTimeMs;
11610 long txTimeMs;
11611 long energy;
11612
11613 SparseLongArray uidRxBytes = new SparseLongArray();
11614 SparseLongArray uidTxBytes = new SparseLongArray();
11615
11616 void set(BluetoothActivityEnergyInfo info) {
11617 idleTimeMs = info.getControllerIdleTimeMillis();
11618 rxTimeMs = info.getControllerRxTimeMillis();
11619 txTimeMs = info.getControllerTxTimeMillis();
11620 energy = info.getControllerEnergyUsed();
11621 if (info.getUidTraffic() != null) {
11622 for (UidTraffic traffic : info.getUidTraffic()) {
11623 uidRxBytes.put(traffic.getUid(), traffic.getRxBytes());
11624 uidTxBytes.put(traffic.getUid(), traffic.getTxBytes());
11625 }
11626 }
11627 }
11628 }
11629
11630 private final BluetoothActivityInfoCache mLastBluetoothActivityInfo
11631 = new BluetoothActivityInfoCache();
11632
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011633 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011634 * Distribute Bluetooth energy info and network traffic to apps.
Mike Ma561a8d92018-03-20 18:24:05 -070011635 *
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011636 * @param info The energy information from the bluetooth controller.
11637 */
11638 public void updateBluetoothStateLocked(@Nullable final BluetoothActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011639 if (DEBUG_ENERGY) {
Adam Lesinski50e47602015-12-04 17:04:54 -080011640 Slog.d(TAG, "Updating bluetooth stats: " + info);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011641 }
11642
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011643 if (info == null || !mOnBatteryInternal) {
11644 return;
11645 }
Adam Lesinskie283d332015-04-16 12:29:25 -070011646
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011647 mHasBluetoothReporting = true;
11648
Bookatz867c0d72017-03-07 18:23:42 -080011649 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Mike Ma561a8d92018-03-20 18:24:05 -070011650 final long rxTimeMs =
11651 info.getControllerRxTimeMillis() - mLastBluetoothActivityInfo.rxTimeMs;
11652 final long txTimeMs =
11653 info.getControllerTxTimeMillis() - mLastBluetoothActivityInfo.txTimeMs;
11654 final long idleTimeMs =
11655 info.getControllerIdleTimeMillis() - mLastBluetoothActivityInfo.idleTimeMs;
11656
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011657 if (DEBUG_ENERGY) {
11658 Slog.d(TAG, "------ BEGIN BLE power blaming ------");
11659 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
11660 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
Chenjie Yu89083392018-01-11 14:53:31 -080011661 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms");
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011662 }
11663
11664 long totalScanTimeMs = 0;
11665
11666 final int uidCount = mUidStats.size();
11667 for (int i = 0; i < uidCount; i++) {
11668 final Uid u = mUidStats.valueAt(i);
11669 if (u.mBluetoothScanTimer == null) {
11670 continue;
Adam Lesinskie283d332015-04-16 12:29:25 -070011671 }
Adam Lesinski50e47602015-12-04 17:04:54 -080011672
Bookatzaa4594a2017-03-24 12:39:56 -070011673 totalScanTimeMs += u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011674 elapsedRealtimeMs * 1000) / 1000;
11675 }
11676
11677 final boolean normalizeScanRxTime = (totalScanTimeMs > rxTimeMs);
11678 final boolean normalizeScanTxTime = (totalScanTimeMs > txTimeMs);
11679
11680 if (DEBUG_ENERGY) {
11681 Slog.d(TAG, "Normalizing scan power for RX=" + normalizeScanRxTime
11682 + " TX=" + normalizeScanTxTime);
11683 }
11684
11685 long leftOverRxTimeMs = rxTimeMs;
11686 long leftOverTxTimeMs = txTimeMs;
11687
11688 for (int i = 0; i < uidCount; i++) {
11689 final Uid u = mUidStats.valueAt(i);
11690 if (u.mBluetoothScanTimer == null) {
11691 continue;
11692 }
11693
Bookatzaa4594a2017-03-24 12:39:56 -070011694 long scanTimeSinceMarkMs = u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011695 elapsedRealtimeMs * 1000) / 1000;
11696 if (scanTimeSinceMarkMs > 0) {
11697 // Set the new mark so that next time we get new data since this point.
11698 u.mBluetoothScanTimer.setMark(elapsedRealtimeMs);
11699
11700 long scanTimeRxSinceMarkMs = scanTimeSinceMarkMs;
11701 long scanTimeTxSinceMarkMs = scanTimeSinceMarkMs;
11702
11703 if (normalizeScanRxTime) {
11704 // Scan time is longer than the total rx time in the controller,
11705 // so distribute the scan time proportionately. This means regular traffic
11706 // will not blamed, but scans are more expensive anyways.
11707 scanTimeRxSinceMarkMs = (rxTimeMs * scanTimeRxSinceMarkMs) / totalScanTimeMs;
11708 }
11709
11710 if (normalizeScanTxTime) {
11711 // Scan time is longer than the total tx time in the controller,
11712 // so distribute the scan time proportionately. This means regular traffic
11713 // will not blamed, but scans are more expensive anyways.
11714 scanTimeTxSinceMarkMs = (txTimeMs * scanTimeTxSinceMarkMs) / totalScanTimeMs;
11715 }
11716
11717 final ControllerActivityCounterImpl counter =
11718 u.getOrCreateBluetoothControllerActivityLocked();
11719 counter.getRxTimeCounter().addCountLocked(scanTimeRxSinceMarkMs);
11720 counter.getTxTimeCounters()[0].addCountLocked(scanTimeTxSinceMarkMs);
11721
11722 leftOverRxTimeMs -= scanTimeRxSinceMarkMs;
11723 leftOverTxTimeMs -= scanTimeTxSinceMarkMs;
11724 }
11725 }
11726
11727 if (DEBUG_ENERGY) {
Mike Ma561a8d92018-03-20 18:24:05 -070011728 Slog.d(TAG, "Left over time for traffic RX=" + leftOverRxTimeMs + " TX="
11729 + leftOverTxTimeMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011730 }
11731
11732 //
11733 // Now distribute blame to apps that did bluetooth traffic.
11734 //
11735
11736 long totalTxBytes = 0;
11737 long totalRxBytes = 0;
11738
11739 final UidTraffic[] uidTraffic = info.getUidTraffic();
Mike Ma561a8d92018-03-20 18:24:05 -070011740 final int numUids = uidTraffic != null ? uidTraffic.length : 0;
11741 for (int i = 0; i < numUids; i++) {
11742 final UidTraffic traffic = uidTraffic[i];
11743 final long rxBytes = traffic.getRxBytes() - mLastBluetoothActivityInfo.uidRxBytes.get(
11744 traffic.getUid());
11745 final long txBytes = traffic.getTxBytes() - mLastBluetoothActivityInfo.uidTxBytes.get(
11746 traffic.getUid());
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011747
11748 // Add to the global counters.
Mike Ma561a8d92018-03-20 18:24:05 -070011749 mNetworkByteActivityCounters[NETWORK_BT_RX_DATA].addCountLocked(rxBytes);
11750 mNetworkByteActivityCounters[NETWORK_BT_TX_DATA].addCountLocked(txBytes);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011751
11752 // Add to the UID counters.
11753 final Uid u = getUidStatsLocked(mapUid(traffic.getUid()));
Mike Ma561a8d92018-03-20 18:24:05 -070011754 u.noteNetworkActivityLocked(NETWORK_BT_RX_DATA, rxBytes, 0);
11755 u.noteNetworkActivityLocked(NETWORK_BT_TX_DATA, txBytes, 0);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011756
11757 // Calculate the total traffic.
Mike Ma561a8d92018-03-20 18:24:05 -070011758 totalRxBytes += rxBytes;
11759 totalTxBytes += txBytes;
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011760 }
11761
Mike Ma561a8d92018-03-20 18:24:05 -070011762 if ((totalTxBytes != 0 || totalRxBytes != 0) && (leftOverRxTimeMs != 0
11763 || leftOverTxTimeMs != 0)) {
11764 for (int i = 0; i < numUids; i++) {
11765 final UidTraffic traffic = uidTraffic[i];
11766 final int uid = traffic.getUid();
11767 final long rxBytes =
11768 traffic.getRxBytes() - mLastBluetoothActivityInfo.uidRxBytes.get(uid);
11769 final long txBytes =
11770 traffic.getTxBytes() - mLastBluetoothActivityInfo.uidTxBytes.get(uid);
Adam Lesinski50e47602015-12-04 17:04:54 -080011771
Mike Ma561a8d92018-03-20 18:24:05 -070011772 final Uid u = getUidStatsLocked(mapUid(uid));
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011773 final ControllerActivityCounterImpl counter =
11774 u.getOrCreateBluetoothControllerActivityLocked();
11775
Mike Ma561a8d92018-03-20 18:24:05 -070011776 if (totalRxBytes > 0 && rxBytes > 0) {
11777 final long timeRxMs = (leftOverRxTimeMs * rxBytes) / totalRxBytes;
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011778 if (DEBUG_ENERGY) {
Mike Ma561a8d92018-03-20 18:24:05 -070011779 Slog.d(TAG, "UID=" + uid + " rx_bytes=" + rxBytes + " rx_time=" + timeRxMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011780 }
11781 counter.getRxTimeCounter().addCountLocked(timeRxMs);
11782 leftOverRxTimeMs -= timeRxMs;
11783 }
11784
Mike Ma561a8d92018-03-20 18:24:05 -070011785 if (totalTxBytes > 0 && txBytes > 0) {
11786 final long timeTxMs = (leftOverTxTimeMs * txBytes) / totalTxBytes;
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011787 if (DEBUG_ENERGY) {
Mike Ma561a8d92018-03-20 18:24:05 -070011788 Slog.d(TAG, "UID=" + uid + " tx_bytes=" + txBytes + " tx_time=" + timeTxMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011789 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011790 counter.getTxTimeCounters()[0].addCountLocked(timeTxMs);
11791 leftOverTxTimeMs -= timeTxMs;
11792 }
Adam Lesinski50e47602015-12-04 17:04:54 -080011793 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011794 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011795
Chenjie Yu89083392018-01-11 14:53:31 -080011796 mBluetoothActivity.getRxTimeCounter().addCountLocked(rxTimeMs);
11797 mBluetoothActivity.getTxTimeCounters()[0].addCountLocked(txTimeMs);
11798 mBluetoothActivity.getIdleTimeCounter().addCountLocked(idleTimeMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011799
11800 // POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11801 final double opVolt = mPowerProfile.getAveragePower(
11802 PowerProfile.POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11803 if (opVolt != 0) {
11804 // We store the power drain as mAms.
11805 mBluetoothActivity.getPowerCounter().addCountLocked(
Mike Ma561a8d92018-03-20 18:24:05 -070011806 (long) ((info.getControllerEnergyUsed() - mLastBluetoothActivityInfo.energy)
11807 / opVolt));
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011808 }
Mike Ma561a8d92018-03-20 18:24:05 -070011809 mLastBluetoothActivityInfo.set(info);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011810 }
11811
11812 /**
Bookatz0b8a0502017-09-13 11:51:52 -070011813 * Read and record Resource Power Manager (RPM) state and voter times.
11814 * If RPM stats were fetched more recently than RPM_STATS_UPDATE_FREQ_MS ago, uses the old data
11815 * instead of fetching it anew.
Bookatz50df7112017-08-04 14:53:26 -070011816 */
11817 public void updateRpmStatsLocked() {
11818 if (mPlatformIdleStateCallback == null) return;
Bookatz0b8a0502017-09-13 11:51:52 -070011819 long now = SystemClock.elapsedRealtime();
11820 if (now - mLastRpmStatsUpdateTimeMs >= RPM_STATS_UPDATE_FREQ_MS) {
11821 mPlatformIdleStateCallback.fillLowPowerStats(mTmpRpmStats);
11822 mLastRpmStatsUpdateTimeMs = now;
11823 }
Bookatz50df7112017-08-04 14:53:26 -070011824
11825 for (Map.Entry<String, RpmStats.PowerStatePlatformSleepState> pstate
11826 : mTmpRpmStats.mPlatformLowPowerStats.entrySet()) {
11827
11828 // Update values for this platform state.
11829 final String pName = pstate.getKey();
11830 final long pTimeUs = pstate.getValue().mTimeMs * 1000;
11831 final int pCount = pstate.getValue().mCount;
11832 getRpmTimerLocked(pName).update(pTimeUs, pCount);
Bookatz82b341172017-09-07 19:06:08 -070011833 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11834 getScreenOffRpmTimerLocked(pName).update(pTimeUs, pCount);
11835 }
Bookatz50df7112017-08-04 14:53:26 -070011836
11837 // Update values for each voter of this platform state.
11838 for (Map.Entry<String, RpmStats.PowerStateElement> voter
11839 : pstate.getValue().mVoters.entrySet()) {
11840 final String vName = pName + "." + voter.getKey();
11841 final long vTimeUs = voter.getValue().mTimeMs * 1000;
11842 final int vCount = voter.getValue().mCount;
11843 getRpmTimerLocked(vName).update(vTimeUs, vCount);
Bookatz82b341172017-09-07 19:06:08 -070011844 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11845 getScreenOffRpmTimerLocked(vName).update(vTimeUs, vCount);
11846 }
Bookatz50df7112017-08-04 14:53:26 -070011847 }
11848 }
11849
11850 for (Map.Entry<String, RpmStats.PowerStateSubsystem> subsys
11851 : mTmpRpmStats.mSubsystemLowPowerStats.entrySet()) {
11852
11853 final String subsysName = subsys.getKey();
11854 for (Map.Entry<String, RpmStats.PowerStateElement> sstate
11855 : subsys.getValue().mStates.entrySet()) {
11856 final String name = subsysName + "." + sstate.getKey();
11857 final long timeUs = sstate.getValue().mTimeMs * 1000;
11858 final int count = sstate.getValue().mCount;
11859 getRpmTimerLocked(name).update(timeUs, count);
Bookatz82b341172017-09-07 19:06:08 -070011860 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11861 getScreenOffRpmTimerLocked(name).update(timeUs, count);
11862 }
Bookatz50df7112017-08-04 14:53:26 -070011863 }
11864 }
11865 }
11866
11867 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011868 * Read and distribute kernel wake lock use across apps.
11869 */
11870 public void updateKernelWakelocksLocked() {
11871 final KernelWakelockStats wakelockStats = mKernelWakelockReader.readKernelWakelockStats(
11872 mTmpWakelockStats);
11873 if (wakelockStats == null) {
11874 // Not crashing might make board bringup easier.
11875 Slog.w(TAG, "Couldn't get kernel wake lock stats");
11876 return;
11877 }
11878
11879 for (Map.Entry<String, KernelWakelockStats.Entry> ent : wakelockStats.entrySet()) {
11880 String name = ent.getKey();
11881 KernelWakelockStats.Entry kws = ent.getValue();
11882
11883 SamplingTimer kwlt = mKernelWakelockStats.get(name);
11884 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -070011885 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011886 mKernelWakelockStats.put(name, kwlt);
11887 }
Adam Lesinskid84ad302016-05-17 18:31:02 -070011888
Adam Lesinski757c6ea2016-04-21 09:55:41 -070011889 kwlt.update(kws.mTotalTime, kws.mCount);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011890 kwlt.setUpdateVersion(kws.mVersion);
11891 }
11892
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011893 int numWakelocksSetStale = 0;
Adam Lesinskid84ad302016-05-17 18:31:02 -070011894 // Set timers to stale if they didn't appear in /d/wakeup_sources (or /proc/wakelocks)
11895 // this time.
11896 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
11897 SamplingTimer st = ent.getValue();
11898 if (st.getUpdateVersion() != wakelockStats.kernelWakelockVersion) {
11899 st.endSample();
11900 numWakelocksSetStale++;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011901 }
11902 }
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011903
Adam Lesinskid84ad302016-05-17 18:31:02 -070011904 // Record whether we've seen a non-zero time (for debugging b/22716723).
11905 if (wakelockStats.isEmpty()) {
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011906 Slog.wtf(TAG, "All kernel wakelocks had time of zero");
11907 }
11908
11909 if (numWakelocksSetStale == mKernelWakelockStats.size()) {
11910 Slog.wtf(TAG, "All kernel wakelocks were set stale. new version=" +
11911 wakelockStats.kernelWakelockVersion);
11912 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011913 }
11914
Adam Lesinski72478f02015-06-17 15:39:43 -070011915 // We use an anonymous class to access these variables,
11916 // so they can't live on the stack or they'd have to be
11917 // final MutableLong objects (more allocations).
11918 // Used in updateCpuTimeLocked().
11919 long mTempTotalCpuUserTimeUs;
11920 long mTempTotalCpuSystemTimeUs;
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011921 long[][] mWakeLockAllocationsUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070011922
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011923 /**
James Carr3a226052016-07-01 14:49:52 -070011924 * Reads the newest memory stats from the kernel.
11925 */
11926 public void updateKernelMemoryBandwidthLocked() {
11927 mKernelMemoryBandwidthStats.updateStats();
11928 LongSparseLongArray bandwidthEntries = mKernelMemoryBandwidthStats.getBandwidthEntries();
11929 final int bandwidthEntryCount = bandwidthEntries.size();
11930 int index;
11931 for (int i = 0; i < bandwidthEntryCount; i++) {
11932 SamplingTimer timer;
11933 if ((index = mKernelMemoryStats.indexOfKey(bandwidthEntries.keyAt(i))) >= 0) {
11934 timer = mKernelMemoryStats.valueAt(index);
11935 } else {
11936 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
11937 mKernelMemoryStats.put(bandwidthEntries.keyAt(i), timer);
11938 }
11939 timer.update(bandwidthEntries.valueAt(i), 1);
11940 if (DEBUG_MEMORY) {
11941 Slog.d(TAG, String.format("Added entry %d and updated timer to: "
11942 + "mUnpluggedReportedTotalTime %d size %d", bandwidthEntries.keyAt(i),
11943 mKernelMemoryStats.get(
11944 bandwidthEntries.keyAt(i)).mUnpluggedReportedTotalTime,
11945 mKernelMemoryStats.size()));
11946 }
11947 }
11948 }
11949
Sudheer Shankac57729a2018-02-09 15:44:42 -080011950 public boolean isOnBatteryLocked() {
11951 return mOnBatteryTimeBase.isRunning();
11952 }
11953
11954 public boolean isOnBatteryScreenOffLocked() {
11955 return mOnBatteryScreenOffTimeBase.isRunning();
11956 }
11957
James Carr3a226052016-07-01 14:49:52 -070011958 /**
Adam Lesinski72478f02015-06-17 15:39:43 -070011959 * Read and distribute CPU usage across apps. If their are partial wakelocks being held
11960 * and we are on battery with screen off, we give more of the cpu time to those apps holding
11961 * wakelocks. If the screen is on, we just assign the actual cpu time an app used.
Sudheer Shankac57729a2018-02-09 15:44:42 -080011962 * It's possible this will be invoked after the internal battery/screen states are updated, so
11963 * passing the appropriate battery/screen states to try attribute the cpu times to correct
11964 * buckets.
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011965 */
Andreas Gampe3f24e692018-02-05 13:24:28 -080011966 @GuardedBy("this")
Sudheer Shankac57729a2018-02-09 15:44:42 -080011967 public void updateCpuTimeLocked(boolean onBattery, boolean onBatteryScreenOff) {
Adam Lesinski52290c9c2015-09-21 16:54:52 -070011968 if (mPowerProfile == null) {
11969 return;
11970 }
11971
Adam Lesinski72478f02015-06-17 15:39:43 -070011972 if (DEBUG_ENERGY_CPU) {
11973 Slog.d(TAG, "!Cpu updating!");
11974 }
11975
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011976 if (mCpuFreqs == null) {
11977 mCpuFreqs = mKernelUidCpuFreqTimeReader.readFreqs(mPowerProfile);
11978 }
11979
Sudheer Shanka38383232017-07-25 09:55:03 -070011980 // Calculate the wakelocks we have to distribute amongst. The system is excluded as it is
11981 // usually holding the wakelock on behalf of an app.
11982 // And Only distribute cpu power to wakelocks if the screen is off and we're on battery.
11983 ArrayList<StopwatchTimer> partialTimersToConsider = null;
Sudheer Shankac57729a2018-02-09 15:44:42 -080011984 if (onBatteryScreenOff) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011985 partialTimersToConsider = new ArrayList<>();
11986 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070011987 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070011988 // Since the collection and blaming of wakelocks can be scheduled to run after
11989 // some delay, the mPartialTimers list may have new entries. We can't blame
11990 // the newly added timer for past cpu time, so we only consider timers that
11991 // were present for one round of collection. Once a timer has gone through
11992 // a round of collection, its mInList field is set to true.
Adam Lesinski72478f02015-06-17 15:39:43 -070011993 if (timer.mInList && timer.mUid != null && timer.mUid.mUid != Process.SYSTEM_UID) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011994 partialTimersToConsider.add(timer);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011995 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011996 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011997 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011998 markPartialTimersAsEligible();
Adam Lesinski72478f02015-06-17 15:39:43 -070011999
Sudheer Shanka38383232017-07-25 09:55:03 -070012000 // When the battery is not on, we don't attribute the cpu times to any timers but we still
12001 // need to take the snapshots.
Sudheer Shankac57729a2018-02-09 15:44:42 -080012002 if (!onBattery) {
Sudheer Shanka38383232017-07-25 09:55:03 -070012003 mKernelUidCpuTimeReader.readDelta(null);
12004 mKernelUidCpuFreqTimeReader.readDelta(null);
Mike Ma234d1822018-03-13 18:53:21 -070012005 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080012006 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
12007 mKernelUidCpuActiveTimeReader.readDelta(null);
12008 mKernelUidCpuClusterTimeReader.readDelta(null);
Mike Ma234d1822018-03-13 18:53:21 -070012009 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080012010 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012011 for (int cluster = mKernelCpuSpeedReaders.length - 1; cluster >= 0; --cluster) {
12012 mKernelCpuSpeedReaders[cluster].readDelta();
12013 }
12014 return;
12015 }
Adam Lesinski72478f02015-06-17 15:39:43 -070012016
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070012017 mUserInfoProvider.refreshUserIds();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012018 final SparseLongArray updatedUids = mKernelUidCpuFreqTimeReader.perClusterTimesAvailable()
12019 ? null : new SparseLongArray();
Sudheer Shankac57729a2018-02-09 15:44:42 -080012020 readKernelUidCpuTimesLocked(partialTimersToConsider, updatedUids, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012021 // updatedUids=null means /proc/uid_time_in_state provides snapshots of per-cluster cpu
12022 // freqs, so no need to approximate these values.
12023 if (updatedUids != null) {
Sudheer Shankac57729a2018-02-09 15:44:42 -080012024 updateClusterSpeedTimes(updatedUids, onBattery);
Sudheer Shanka671985f2017-05-19 11:33:42 -070012025 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080012026 readKernelUidCpuFreqTimesLocked(partialTimersToConsider, onBattery, onBatteryScreenOff);
Mike Ma234d1822018-03-13 18:53:21 -070012027 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080012028 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
Sudheer Shankac57729a2018-02-09 15:44:42 -080012029 readKernelUidCpuActiveTimesLocked(onBattery);
12030 readKernelUidCpuClusterTimesLocked(onBattery);
Mike Ma234d1822018-03-13 18:53:21 -070012031 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080012032 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012033 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012034
Sudheer Shanka38383232017-07-25 09:55:03 -070012035 /**
12036 * Mark the current partial timers as gone through a collection so that they will be
12037 * considered in the next cpu times distribution to wakelock holders.
12038 */
12039 @VisibleForTesting
12040 public void markPartialTimersAsEligible() {
12041 if (ArrayUtils.referenceEquals(mPartialTimers, mLastPartialTimers)) {
12042 // No difference, so each timer is now considered for the next collection.
12043 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
12044 mPartialTimers.get(i).mInList = true;
12045 }
12046 } else {
12047 // The lists are different, meaning we added (or removed a timer) since the last
12048 // collection.
12049 for (int i = mLastPartialTimers.size() - 1; i >= 0; --i) {
12050 mLastPartialTimers.get(i).mInList = false;
12051 }
12052 mLastPartialTimers.clear();
Adam Lesinski72478f02015-06-17 15:39:43 -070012053
Sudheer Shanka38383232017-07-25 09:55:03 -070012054 // Mark the current timers as gone through a collection.
12055 final int numPartialTimers = mPartialTimers.size();
12056 for (int i = 0; i < numPartialTimers; ++i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070012057 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070012058 timer.mInList = true;
12059 mLastPartialTimers.add(timer);
Adam Lesinski72478f02015-06-17 15:39:43 -070012060 }
12061 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012062 }
Adam Lesinski72478f02015-06-17 15:39:43 -070012063
Sudheer Shanka38383232017-07-25 09:55:03 -070012064 /**
12065 * Take snapshot of cpu times (aggregated over all uids) at different frequencies and
12066 * calculate cpu times spent by each uid at different frequencies.
12067 *
12068 * @param updatedUids The uids for which times spent at different frequencies are calculated.
12069 */
12070 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012071 public void updateClusterSpeedTimes(@NonNull SparseLongArray updatedUids, boolean onBattery) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070012072 long totalCpuClustersTimeMs = 0;
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012073 // Read the time spent for each cluster at various cpu frequencies.
Sudheer Shankaaf857412017-07-21 00:14:24 -070012074 final long[][] clusterSpeedTimesMs = new long[mKernelCpuSpeedReaders.length][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012075 for (int cluster = 0; cluster < mKernelCpuSpeedReaders.length; cluster++) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070012076 clusterSpeedTimesMs[cluster] = mKernelCpuSpeedReaders[cluster].readDelta();
12077 if (clusterSpeedTimesMs[cluster] != null) {
12078 for (int speed = clusterSpeedTimesMs[cluster].length - 1; speed >= 0; --speed) {
12079 totalCpuClustersTimeMs += clusterSpeedTimesMs[cluster][speed];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012080 }
12081 }
12082 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070012083 if (totalCpuClustersTimeMs != 0) {
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012084 // We have cpu times per freq aggregated over all uids but we need the times per uid.
12085 // So, we distribute total time spent by an uid to different cpu freqs based on the
12086 // amount of time cpu was running at that freq.
12087 final int updatedUidsCount = updatedUids.size();
12088 for (int i = 0; i < updatedUidsCount; ++i) {
12089 final Uid u = getUidStatsLocked(updatedUids.keyAt(i));
Sudheer Shankaaf857412017-07-21 00:14:24 -070012090 final long appCpuTimeUs = updatedUids.valueAt(i);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012091 // Add the cpu speeds to this UID.
12092 final int numClusters = mPowerProfile.getNumCpuClusters();
Sudheer Shanka38383232017-07-25 09:55:03 -070012093 if (u.mCpuClusterSpeedTimesUs == null ||
12094 u.mCpuClusterSpeedTimesUs.length != numClusters) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070012095 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012096 }
12097
Sudheer Shankaaf857412017-07-21 00:14:24 -070012098 for (int cluster = 0; cluster < clusterSpeedTimesMs.length; cluster++) {
12099 final int speedsInCluster = clusterSpeedTimesMs[cluster].length;
12100 if (u.mCpuClusterSpeedTimesUs[cluster] == null || speedsInCluster !=
12101 u.mCpuClusterSpeedTimesUs[cluster].length) {
12102 u.mCpuClusterSpeedTimesUs[cluster]
12103 = new LongSamplingCounter[speedsInCluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012104 }
12105
Sudheer Shankaaf857412017-07-21 00:14:24 -070012106 final LongSamplingCounter[] cpuSpeeds = u.mCpuClusterSpeedTimesUs[cluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012107 for (int speed = 0; speed < speedsInCluster; speed++) {
12108 if (cpuSpeeds[speed] == null) {
12109 cpuSpeeds[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
12110 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070012111 cpuSpeeds[speed].addCountLocked(appCpuTimeUs
12112 * clusterSpeedTimesMs[cluster][speed]
Sudheer Shankac57729a2018-02-09 15:44:42 -080012113 / totalCpuClustersTimeMs, onBattery);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012114 }
12115 }
12116 }
12117 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012118 }
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012119
Sudheer Shanka38383232017-07-25 09:55:03 -070012120 /**
12121 * Take a snapshot of the cpu times spent by each uid and update the corresponding counters.
12122 * If {@param partialTimers} is not null and empty, then we assign a portion of cpu times to
12123 * wakelock holders.
12124 *
12125 * @param partialTimers The wakelock holders among which the cpu times will be distributed.
12126 * @param updatedUids If not null, then the uids found in the snapshot will be added to this.
12127 */
12128 @VisibleForTesting
12129 public void readKernelUidCpuTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers,
Sudheer Shankac57729a2018-02-09 15:44:42 -080012130 @Nullable SparseLongArray updatedUids, boolean onBattery) {
Sudheer Shanka38383232017-07-25 09:55:03 -070012131 mTempTotalCpuUserTimeUs = mTempTotalCpuSystemTimeUs = 0;
12132 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
12133 final long startTimeMs = mClocks.uptimeMillis();
Adam Lesinski72478f02015-06-17 15:39:43 -070012134
Sudheer Shanka38383232017-07-25 09:55:03 -070012135 mKernelUidCpuTimeReader.readDelta((uid, userTimeUs, systemTimeUs) -> {
12136 uid = mapUid(uid);
12137 if (Process.isIsolated(uid)) {
12138 // This could happen if the isolated uid mapping was removed before that process
12139 // was actually killed.
12140 mKernelUidCpuTimeReader.removeUid(uid);
12141 Slog.d(TAG, "Got readings for an isolated uid with no mapping: " + uid);
12142 return;
12143 }
12144 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12145 Slog.d(TAG, "Got readings for an invalid user's uid " + uid);
12146 mKernelUidCpuTimeReader.removeUid(uid);
12147 return;
12148 }
12149 final Uid u = getUidStatsLocked(uid);
12150
12151 // Accumulate the total system and user time.
12152 mTempTotalCpuUserTimeUs += userTimeUs;
12153 mTempTotalCpuSystemTimeUs += systemTimeUs;
12154
12155 StringBuilder sb = null;
12156 if (DEBUG_ENERGY_CPU) {
12157 sb = new StringBuilder();
12158 sb.append(" got time for uid=").append(u.mUid).append(": u=");
12159 TimeUtils.formatDuration(userTimeUs / 1000, sb);
12160 sb.append(" s=");
12161 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
12162 sb.append("\n");
12163 }
12164
12165 if (numWakelocks > 0) {
12166 // We have wakelocks being held, so only give a portion of the
12167 // time to the process. The rest will be distributed among wakelock
12168 // holders.
12169 userTimeUs = (userTimeUs * WAKE_LOCK_WEIGHT) / 100;
12170 systemTimeUs = (systemTimeUs * WAKE_LOCK_WEIGHT) / 100;
12171 }
12172
12173 if (sb != null) {
12174 sb.append(" adding to uid=").append(u.mUid).append(": u=");
12175 TimeUtils.formatDuration(userTimeUs / 1000, sb);
12176 sb.append(" s=");
12177 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
12178 Slog.d(TAG, sb.toString());
12179 }
12180
Sudheer Shankac57729a2018-02-09 15:44:42 -080012181 u.mUserCpuTime.addCountLocked(userTimeUs, onBattery);
12182 u.mSystemCpuTime.addCountLocked(systemTimeUs, onBattery);
Sudheer Shanka38383232017-07-25 09:55:03 -070012183 if (updatedUids != null) {
12184 updatedUids.put(u.getUid(), userTimeUs + systemTimeUs);
12185 }
12186 });
12187
12188 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12189 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12190 Slog.d(TAG, "Reading cpu stats took " + elapsedTimeMs + "ms");
12191 }
12192
12193 if (numWakelocks > 0) {
12194 // Distribute a portion of the total cpu time to wakelock holders.
12195 mTempTotalCpuUserTimeUs = (mTempTotalCpuUserTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
12196 mTempTotalCpuSystemTimeUs =
12197 (mTempTotalCpuSystemTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
12198
12199 for (int i = 0; i < numWakelocks; ++i) {
12200 final StopwatchTimer timer = partialTimers.get(i);
12201 final int userTimeUs = (int) (mTempTotalCpuUserTimeUs / (numWakelocks - i));
12202 final int systemTimeUs = (int) (mTempTotalCpuSystemTimeUs / (numWakelocks - i));
12203
12204 if (DEBUG_ENERGY_CPU) {
12205 final StringBuilder sb = new StringBuilder();
12206 sb.append(" Distributing wakelock uid=").append(timer.mUid.mUid)
12207 .append(": u=");
12208 TimeUtils.formatDuration(userTimeUs / 1000, sb);
12209 sb.append(" s=");
12210 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
12211 Slog.d(TAG, sb.toString());
12212 }
12213
Sudheer Shankac57729a2018-02-09 15:44:42 -080012214 timer.mUid.mUserCpuTime.addCountLocked(userTimeUs, onBattery);
12215 timer.mUid.mSystemCpuTime.addCountLocked(systemTimeUs, onBattery);
Sudheer Shanka38383232017-07-25 09:55:03 -070012216 if (updatedUids != null) {
12217 final int uid = timer.mUid.getUid();
12218 updatedUids.put(uid, updatedUids.get(uid, 0) + userTimeUs + systemTimeUs);
12219 }
12220
12221 final Uid.Proc proc = timer.mUid.getProcessStatsLocked("*wakelock*");
Sudheer Shankac57729a2018-02-09 15:44:42 -080012222 proc.addCpuTimeLocked(userTimeUs / 1000, systemTimeUs / 1000, onBattery);
Sudheer Shanka38383232017-07-25 09:55:03 -070012223
12224 mTempTotalCpuUserTimeUs -= userTimeUs;
12225 mTempTotalCpuSystemTimeUs -= systemTimeUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070012226 }
12227 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070012228 }
12229
Sudheer Shanka38383232017-07-25 09:55:03 -070012230 /**
12231 * Take a snapshot of the cpu times spent by each uid in each freq and update the
12232 * corresponding counters.
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012233 *
12234 * @param partialTimers The wakelock holders among which the cpu freq times will be distributed.
Sudheer Shanka38383232017-07-25 09:55:03 -070012235 */
12236 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012237 public void readKernelUidCpuFreqTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers,
12238 boolean onBattery, boolean onBatteryScreenOff) {
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012239 final boolean perClusterTimesAvailable =
12240 mKernelUidCpuFreqTimeReader.perClusterTimesAvailable();
12241 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
12242 final int numClusters = mPowerProfile.getNumCpuClusters();
12243 mWakeLockAllocationsUs = null;
Sudheer Shankaac5b88f2017-12-11 15:36:35 -080012244 final long startTimeMs = mClocks.uptimeMillis();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012245 mKernelUidCpuFreqTimeReader.readDelta((uid, cpuFreqTimeMs) -> {
12246 uid = mapUid(uid);
12247 if (Process.isIsolated(uid)) {
12248 mKernelUidCpuFreqTimeReader.removeUid(uid);
12249 Slog.d(TAG, "Got freq readings for an isolated uid with no mapping: " + uid);
12250 return;
Sudheer Shanka38383232017-07-25 09:55:03 -070012251 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012252 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12253 Slog.d(TAG, "Got freq readings for an invalid user's uid " + uid);
12254 mKernelUidCpuFreqTimeReader.removeUid(uid);
12255 return;
12256 }
12257 final Uid u = getUidStatsLocked(uid);
12258 if (u.mCpuFreqTimeMs == null || u.mCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
12259 u.mCpuFreqTimeMs = new LongSamplingCounterArray(mOnBatteryTimeBase);
12260 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080012261 u.mCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012262 if (u.mScreenOffCpuFreqTimeMs == null ||
12263 u.mScreenOffCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
12264 u.mScreenOffCpuFreqTimeMs = new LongSamplingCounterArray(
12265 mOnBatteryScreenOffTimeBase);
12266 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080012267 u.mScreenOffCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs, onBatteryScreenOff);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012268
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012269 if (perClusterTimesAvailable) {
12270 if (u.mCpuClusterSpeedTimesUs == null ||
12271 u.mCpuClusterSpeedTimesUs.length != numClusters) {
12272 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070012273 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012274 if (numWakelocks > 0 && mWakeLockAllocationsUs == null) {
12275 mWakeLockAllocationsUs = new long[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070012276 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012277
12278 int freqIndex = 0;
12279 for (int cluster = 0; cluster < numClusters; ++cluster) {
12280 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
12281 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
12282 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
12283 u.mCpuClusterSpeedTimesUs[cluster]
12284 = new LongSamplingCounter[speedsInCluster];
12285 }
12286 if (numWakelocks > 0 && mWakeLockAllocationsUs[cluster] == null) {
12287 mWakeLockAllocationsUs[cluster] = new long[speedsInCluster];
12288 }
12289 final LongSamplingCounter[] cpuTimesUs = u.mCpuClusterSpeedTimesUs[cluster];
12290 for (int speed = 0; speed < speedsInCluster; ++speed) {
12291 if (cpuTimesUs[speed] == null) {
12292 cpuTimesUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
12293 }
12294 final long appAllocationUs;
12295 if (mWakeLockAllocationsUs != null) {
12296 appAllocationUs =
12297 (cpuFreqTimeMs[freqIndex] * 1000 * WAKE_LOCK_WEIGHT) / 100;
12298 mWakeLockAllocationsUs[cluster][speed] +=
12299 (cpuFreqTimeMs[freqIndex] * 1000 - appAllocationUs);
12300 } else {
12301 appAllocationUs = cpuFreqTimeMs[freqIndex] * 1000;
12302 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080012303 cpuTimesUs[speed].addCountLocked(appAllocationUs, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012304 freqIndex++;
12305 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012306 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012307 }
12308 });
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012309
Sudheer Shankaac5b88f2017-12-11 15:36:35 -080012310 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12311 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12312 Slog.d(TAG, "Reading cpu freq times took " + elapsedTimeMs + "ms");
12313 }
12314
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012315 if (mWakeLockAllocationsUs != null) {
12316 for (int i = 0; i < numWakelocks; ++i) {
12317 final Uid u = partialTimers.get(i).mUid;
12318 if (u.mCpuClusterSpeedTimesUs == null ||
12319 u.mCpuClusterSpeedTimesUs.length != numClusters) {
12320 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
12321 }
12322
12323 for (int cluster = 0; cluster < numClusters; ++cluster) {
12324 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
12325 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
12326 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
12327 u.mCpuClusterSpeedTimesUs[cluster]
12328 = new LongSamplingCounter[speedsInCluster];
12329 }
12330 final LongSamplingCounter[] cpuTimeUs = u.mCpuClusterSpeedTimesUs[cluster];
12331 for (int speed = 0; speed < speedsInCluster; ++speed) {
12332 if (cpuTimeUs[speed] == null) {
12333 cpuTimeUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
12334 }
12335 final long allocationUs =
12336 mWakeLockAllocationsUs[cluster][speed] / (numWakelocks - i);
Sudheer Shankac57729a2018-02-09 15:44:42 -080012337 cpuTimeUs[speed].addCountLocked(allocationUs, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012338 mWakeLockAllocationsUs[cluster][speed] -= allocationUs;
12339 }
12340 }
12341 }
12342 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012343 }
12344
Mike Ma3d422c32017-10-25 11:08:57 -070012345 /**
12346 * Take a snapshot of the cpu active times spent by each uid and update the corresponding
12347 * counters.
12348 */
12349 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012350 public void readKernelUidCpuActiveTimesLocked(boolean onBattery) {
Mike Ma3d422c32017-10-25 11:08:57 -070012351 final long startTimeMs = mClocks.uptimeMillis();
Mike Ma2ab01442018-02-13 14:22:47 -080012352 mKernelUidCpuActiveTimeReader.readDelta((uid, cpuActiveTimesMs) -> {
Mike Ma3d422c32017-10-25 11:08:57 -070012353 uid = mapUid(uid);
12354 if (Process.isIsolated(uid)) {
12355 mKernelUidCpuActiveTimeReader.removeUid(uid);
12356 Slog.w(TAG, "Got active times for an isolated uid with no mapping: " + uid);
12357 return;
12358 }
12359 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12360 Slog.w(TAG, "Got active times for an invalid user's uid " + uid);
12361 mKernelUidCpuActiveTimeReader.removeUid(uid);
12362 return;
12363 }
12364 final Uid u = getUidStatsLocked(uid);
Mike Ma2ab01442018-02-13 14:22:47 -080012365 u.mCpuActiveTimeMs.addCountLocked(cpuActiveTimesMs, onBattery);
Mike Ma3d422c32017-10-25 11:08:57 -070012366 });
12367
12368 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12369 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12370 Slog.d(TAG, "Reading cpu active times took " + elapsedTimeMs + "ms");
12371 }
12372 }
12373
12374 /**
12375 * Take a snapshot of the cpu cluster times spent by each uid and update the corresponding
12376 * counters.
12377 */
12378 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012379 public void readKernelUidCpuClusterTimesLocked(boolean onBattery) {
Mike Ma3d422c32017-10-25 11:08:57 -070012380 final long startTimeMs = mClocks.uptimeMillis();
Mike Ma2ab01442018-02-13 14:22:47 -080012381 mKernelUidCpuClusterTimeReader.readDelta((uid, cpuClusterTimesMs) -> {
Mike Ma3d422c32017-10-25 11:08:57 -070012382 uid = mapUid(uid);
12383 if (Process.isIsolated(uid)) {
12384 mKernelUidCpuClusterTimeReader.removeUid(uid);
12385 Slog.w(TAG, "Got cluster times for an isolated uid with no mapping: " + uid);
12386 return;
12387 }
12388 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12389 Slog.w(TAG, "Got cluster times for an invalid user's uid " + uid);
12390 mKernelUidCpuClusterTimeReader.removeUid(uid);
12391 return;
12392 }
12393 final Uid u = getUidStatsLocked(uid);
Mike Ma2ab01442018-02-13 14:22:47 -080012394 u.mCpuClusterTimesMs.addCountLocked(cpuClusterTimesMs, onBattery);
Mike Ma3d422c32017-10-25 11:08:57 -070012395 });
12396
12397 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12398 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12399 Slog.d(TAG, "Reading cpu cluster times took " + elapsedTimeMs + "ms");
12400 }
12401 }
12402
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012403 boolean setChargingLocked(boolean charging) {
12404 if (mCharging != charging) {
12405 mCharging = charging;
12406 if (charging) {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012407 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012408 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012409 mHistoryCur.states2 &= ~HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012410 }
12411 mHandler.sendEmptyMessage(MSG_REPORT_CHARGING);
12412 return true;
12413 }
12414 return false;
12415 }
12416
Andreas Gampe3f24e692018-02-05 13:24:28 -080012417 @GuardedBy("this")
Mike Mac2f518a2017-09-19 16:06:03 -070012418 protected void setOnBatteryLocked(final long mSecRealtime, final long mSecUptime,
12419 final boolean onBattery, final int oldStatus, final int level, final int chargeUAh) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012420 boolean doWrite = false;
12421 Message m = mHandler.obtainMessage(MSG_REPORT_POWER_CHANGE);
12422 m.arg1 = onBattery ? 1 : 0;
12423 mHandler.sendMessage(m);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012424
Dianne Hackborn40c87252014-03-19 16:55:40 -070012425 final long uptime = mSecUptime * 1000;
12426 final long realtime = mSecRealtime * 1000;
Mike Mac2f518a2017-09-19 16:06:03 -070012427 final int screenState = mScreenState;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012428 if (onBattery) {
12429 // We will reset our status if we are unplugging after the
12430 // battery was last full, or the level is at 100, or
12431 // we have gone through a significant charge (from a very low
12432 // level to a now very high level).
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080012433 boolean reset = false;
Dianne Hackborn9a755432014-05-15 17:05:22 -070012434 if (!mNoAutoReset && (oldStatus == BatteryManager.BATTERY_STATUS_FULL
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012435 || level >= 90
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070012436 || (mDischargeCurrentLevel < 20 && level >= 80)
12437 || (getHighDischargeAmountSinceCharge() >= 200
12438 && mHistoryBuffer.dataSize() >= MAX_HISTORY_BUFFER))) {
Dianne Hackborn73d6a822014-09-29 10:52:47 -070012439 Slog.i(TAG, "Resetting battery stats: level=" + level + " status=" + oldStatus
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070012440 + " dischargeLevel=" + mDischargeCurrentLevel
Dianne Hackborn73d6a822014-09-29 10:52:47 -070012441 + " lowAmount=" + getLowDischargeAmountSinceCharge()
12442 + " highAmount=" + getHighDischargeAmountSinceCharge());
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012443 // Before we write, collect a snapshot of the final aggregated
12444 // stats to be reported in the next checkin. Only do this if we have
12445 // a sufficient amount of data to make it interesting.
12446 if (getLowDischargeAmountSinceCharge() >= 20) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080012447 final long startTime = SystemClock.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012448 final Parcel parcel = Parcel.obtain();
12449 writeSummaryToParcel(parcel, true);
Dianne Hackborne17b4452018-01-10 13:15:40 -080012450 final long initialTime = SystemClock.uptimeMillis() - startTime;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012451 BackgroundThread.getHandler().post(new Runnable() {
12452 @Override public void run() {
12453 synchronized (mCheckinFile) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080012454 final long startTime2 = SystemClock.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012455 FileOutputStream stream = null;
12456 try {
12457 stream = mCheckinFile.startWrite();
12458 stream.write(parcel.marshall());
12459 stream.flush();
12460 FileUtils.sync(stream);
12461 stream.close();
12462 mCheckinFile.finishWrite(stream);
Dianne Hackborne17b4452018-01-10 13:15:40 -080012463 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
12464 "batterystats-checkin",
12465 initialTime + SystemClock.uptimeMillis() - startTime2);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012466 } catch (IOException e) {
12467 Slog.w("BatteryStats",
12468 "Error writing checkin battery statistics", e);
12469 mCheckinFile.failWrite(stream);
12470 } finally {
12471 parcel.recycle();
12472 }
12473 }
12474 }
12475 });
12476 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012477 doWrite = true;
12478 resetAllStatsLocked();
Ying Wai (Daniel) Fan442ab762017-01-31 22:00:10 -080012479 if (chargeUAh > 0 && level > 0) {
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012480 // Only use the reported coulomb charge value if it is supported and reported.
Ying Wai (Daniel) Fan9238b612017-01-18 15:50:19 -080012481 mEstimatedBatteryCapacity = (int) ((chargeUAh / 1000) / (level / 100.0));
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012482 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012483 mDischargeStartLevel = level;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080012484 reset = true;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012485 mDischargeStepTracker.init();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012486 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012487 if (mCharging) {
12488 setChargingLocked(false);
12489 }
12490 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080012491 mOnBattery = mOnBatteryInternal = true;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012492 mLastDischargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070012493 mMinDischargeStepLevel = level;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012494 mDischargeStepTracker.clearTime();
12495 mDailyDischargeStepTracker.clearTime();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012496 mInitStepMode = mCurStepMode;
12497 mModStepMode = 0;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012498 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012499 mHistoryCur.batteryLevel = (byte)level;
12500 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
12501 if (DEBUG_HISTORY) Slog.v(TAG, "Battery unplugged to: "
12502 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012503 if (reset) {
12504 mRecordingHistory = true;
12505 startRecordingHistory(mSecRealtime, mSecUptime, reset);
12506 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070012507 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012508 mDischargeCurrentLevel = mDischargeUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070012509 if (isScreenOn(screenState)) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012510 mDischargeScreenOnUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070012511 mDischargeScreenDozeUnplugLevel = 0;
12512 mDischargeScreenOffUnplugLevel = 0;
12513 } else if (isScreenDoze(screenState)) {
12514 mDischargeScreenOnUnplugLevel = 0;
12515 mDischargeScreenDozeUnplugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012516 mDischargeScreenOffUnplugLevel = 0;
12517 } else {
12518 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012519 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012520 mDischargeScreenOffUnplugLevel = level;
12521 }
12522 mDischargeAmountScreenOn = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012523 mDischargeAmountScreenDoze = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012524 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012525 updateTimeBasesLocked(true, screenState, uptime, realtime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012526 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012527 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080012528 mOnBattery = mOnBatteryInternal = false;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012529 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012530 mHistoryCur.batteryLevel = (byte)level;
12531 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
12532 if (DEBUG_HISTORY) Slog.v(TAG, "Battery plugged to: "
12533 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -070012534 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012535 mDischargeCurrentLevel = mDischargePlugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012536 if (level < mDischargeUnplugLevel) {
12537 mLowDischargeAmountSinceCharge += mDischargeUnplugLevel-level-1;
12538 mHighDischargeAmountSinceCharge += mDischargeUnplugLevel-level;
12539 }
Mike Mac2f518a2017-09-19 16:06:03 -070012540 updateDischargeScreenLevelsLocked(screenState, screenState);
12541 updateTimeBasesLocked(false, screenState, uptime, realtime);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012542 mChargeStepTracker.init();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012543 mLastChargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070012544 mMaxChargeStepLevel = level;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012545 mInitStepMode = mCurStepMode;
12546 mModStepMode = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012547 }
12548 if (doWrite || (mLastWriteTime + (60 * 1000)) < mSecRealtime) {
12549 if (mFile != null) {
12550 writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012551 }
12552 }
12553 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012554
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012555 private void startRecordingHistory(final long elapsedRealtimeMs, final long uptimeMs,
12556 boolean reset) {
12557 mRecordingHistory = true;
12558 mHistoryCur.currentTime = System.currentTimeMillis();
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012559 addHistoryBufferLocked(elapsedRealtimeMs,
Dianne Hackborn37de0982014-05-09 09:32:18 -070012560 reset ? HistoryItem.CMD_RESET : HistoryItem.CMD_CURRENT_TIME,
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012561 mHistoryCur);
12562 mHistoryCur.currentTime = 0;
12563 if (reset) {
12564 initActiveHistoryEventsLocked(elapsedRealtimeMs, uptimeMs);
12565 }
12566 }
12567
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012568 private void recordCurrentTimeChangeLocked(final long currentTime, final long elapsedRealtimeMs,
12569 final long uptimeMs) {
12570 if (mRecordingHistory) {
12571 mHistoryCur.currentTime = currentTime;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012572 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_CURRENT_TIME, mHistoryCur);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012573 mHistoryCur.currentTime = 0;
12574 }
12575 }
12576
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080012577 private void recordShutdownLocked(final long elapsedRealtimeMs, final long uptimeMs) {
12578 if (mRecordingHistory) {
12579 mHistoryCur.currentTime = System.currentTimeMillis();
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012580 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_SHUTDOWN, mHistoryCur);
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080012581 mHistoryCur.currentTime = 0;
12582 }
12583 }
12584
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012585 private void scheduleSyncExternalStatsLocked(String reason, int updateFlags) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012586 if (mExternalSync != null) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012587 mExternalSync.scheduleSync(reason, updateFlags);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070012588 }
12589 }
12590
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012591 // This should probably be exposed in the API, though it's not critical
Bookatz1a1b0462018-01-12 11:47:03 -080012592 public static final int BATTERY_PLUGGED_NONE = OsProtoEnums.BATTERY_PLUGGED_NONE; // = 0
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012593
Andreas Gampe3f24e692018-02-05 13:24:28 -080012594 @GuardedBy("this")
Bookatz8c6571b2017-10-24 15:04:41 -070012595 public void setBatteryStateLocked(final int status, final int health, final int plugType,
12596 final int level, /* not final */ int temp, final int volt, final int chargeUAh,
12597 final int chargeFullUAh) {
Adam Lesinski29ddfe52017-03-29 19:29:00 -070012598 // Temperature is encoded without the signed bit, so clamp any negative temperatures to 0.
12599 temp = Math.max(0, temp);
12600
Bookatz8c6571b2017-10-24 15:04:41 -070012601 reportChangesToStatsLog(mHaveBatteryLevel ? mHistoryCur : null,
Tej Singh40298312018-02-16 00:15:09 -080012602 status, plugType, level);
Bookatz8c6571b2017-10-24 15:04:41 -070012603
Sudheer Shankac57729a2018-02-09 15:44:42 -080012604 final boolean onBattery = isOnBattery(plugType, status);
Joe Onoratoabded112016-02-08 16:49:39 -080012605 final long uptime = mClocks.uptimeMillis();
12606 final long elapsedRealtime = mClocks.elapsedRealtime();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012607 if (!mHaveBatteryLevel) {
12608 mHaveBatteryLevel = true;
12609 // We start out assuming that the device is plugged in (not
12610 // on battery). If our first report is now that we are indeed
12611 // plugged in, then twiddle our state to correctly reflect that
12612 // since we won't be going through the full setOnBattery().
12613 if (onBattery == mOnBattery) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012614 if (onBattery) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012615 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012616 } else {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012617 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012618 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012619 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012620 // Always start out assuming charging, that will be updated later.
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012621 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012622 mHistoryCur.batteryStatus = (byte)status;
12623 mHistoryCur.batteryLevel = (byte)level;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012624 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012625 mMaxChargeStepLevel = mMinDischargeStepLevel =
12626 mLastChargeStepLevel = mLastDischargeStepLevel = level;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012627 mLastChargingStateLevel = level;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012628 } else if (mCurrentBatteryLevel != level || mOnBattery != onBattery) {
12629 recordDailyStatsIfNeededLocked(level >= 100 && onBattery);
12630 }
12631 int oldStatus = mHistoryCur.batteryStatus;
12632 if (onBattery) {
12633 mDischargeCurrentLevel = level;
12634 if (!mRecordingHistory) {
12635 mRecordingHistory = true;
12636 startRecordingHistory(elapsedRealtime, uptime, true);
12637 }
Todd Poynor1acf06a2017-12-07 19:19:35 -080012638 } else if (level < 96 &&
12639 status != BatteryManager.BATTERY_STATUS_UNKNOWN) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012640 if (!mRecordingHistory) {
12641 mRecordingHistory = true;
12642 startRecordingHistory(elapsedRealtime, uptime, true);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012643 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070012644 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012645 mCurrentBatteryLevel = level;
12646 if (mDischargePlugLevel < 0) {
12647 mDischargePlugLevel = level;
Marco Nelissend8593312009-04-30 14:45:06 -070012648 }
Adam Lesinski926969b2016-04-28 17:31:12 -070012649
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012650 if (onBattery != mOnBattery) {
12651 mHistoryCur.batteryLevel = (byte)level;
12652 mHistoryCur.batteryStatus = (byte)status;
12653 mHistoryCur.batteryHealth = (byte)health;
12654 mHistoryCur.batteryPlugType = (byte)plugType;
12655 mHistoryCur.batteryTemperature = (short)temp;
12656 mHistoryCur.batteryVoltage = (char)volt;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012657 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
12658 // Only record discharges
12659 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
12660 mDischargeCounter.addCountLocked(chargeDiff);
12661 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070012662 if (isScreenDoze(mScreenState)) {
12663 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
12664 }
Mike Ma15313c92017-11-15 17:58:21 -080012665 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
12666 mDischargeLightDozeCounter.addCountLocked(chargeDiff);
12667 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
12668 mDischargeDeepDozeCounter.addCountLocked(chargeDiff);
12669 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012670 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012671 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012672 setOnBatteryLocked(elapsedRealtime, uptime, onBattery, oldStatus, level, chargeUAh);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012673 } else {
12674 boolean changed = false;
12675 if (mHistoryCur.batteryLevel != level) {
12676 mHistoryCur.batteryLevel = (byte)level;
12677 changed = true;
Marco Nelissend8593312009-04-30 14:45:06 -070012678
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012679 // TODO(adamlesinski): Schedule the creation of a HistoryStepDetails record
12680 // which will pull external stats.
Sudheer Shanka0719c6a2018-04-24 11:12:11 -070012681 mExternalSync.scheduleSyncDueToBatteryLevelChange(
12682 mConstants.BATTERY_LEVEL_COLLECTION_DELAY_MS);
Evan Millarc64edde2009-04-18 12:26:32 -070012683 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012684 if (mHistoryCur.batteryStatus != status) {
12685 mHistoryCur.batteryStatus = (byte)status;
12686 changed = true;
12687 }
12688 if (mHistoryCur.batteryHealth != health) {
12689 mHistoryCur.batteryHealth = (byte)health;
12690 changed = true;
12691 }
12692 if (mHistoryCur.batteryPlugType != plugType) {
12693 mHistoryCur.batteryPlugType = (byte)plugType;
12694 changed = true;
12695 }
12696 if (temp >= (mHistoryCur.batteryTemperature+10)
12697 || temp <= (mHistoryCur.batteryTemperature-10)) {
12698 mHistoryCur.batteryTemperature = (short)temp;
12699 changed = true;
12700 }
12701 if (volt > (mHistoryCur.batteryVoltage+20)
12702 || volt < (mHistoryCur.batteryVoltage-20)) {
12703 mHistoryCur.batteryVoltage = (char)volt;
12704 changed = true;
12705 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012706 if (chargeUAh >= (mHistoryCur.batteryChargeUAh+10)
12707 || chargeUAh <= (mHistoryCur.batteryChargeUAh-10)) {
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012708 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
12709 // Only record discharges
12710 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
12711 mDischargeCounter.addCountLocked(chargeDiff);
12712 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070012713 if (isScreenDoze(mScreenState)) {
12714 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
12715 }
Mike Ma15313c92017-11-15 17:58:21 -080012716 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
12717 mDischargeLightDozeCounter.addCountLocked(chargeDiff);
12718 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
12719 mDischargeDeepDozeCounter.addCountLocked(chargeDiff);
12720 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012721 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012722 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski926969b2016-04-28 17:31:12 -070012723 changed = true;
12724 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012725 long modeBits = (((long)mInitStepMode) << STEP_LEVEL_INITIAL_MODE_SHIFT)
12726 | (((long)mModStepMode) << STEP_LEVEL_MODIFIED_MODE_SHIFT)
12727 | (((long)(level&0xff)) << STEP_LEVEL_LEVEL_SHIFT);
12728 if (onBattery) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012729 changed |= setChargingLocked(false);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012730 if (mLastDischargeStepLevel != level && mMinDischargeStepLevel > level) {
12731 mDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
12732 modeBits, elapsedRealtime);
12733 mDailyDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
12734 modeBits, elapsedRealtime);
12735 mLastDischargeStepLevel = level;
12736 mMinDischargeStepLevel = level;
12737 mInitStepMode = mCurStepMode;
12738 mModStepMode = 0;
12739 }
12740 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012741 if (level >= 90) {
12742 // If the battery level is at least 90%, always consider the device to be
12743 // charging even if it happens to go down a level.
12744 changed |= setChargingLocked(true);
12745 mLastChargeStepLevel = level;
12746 } if (!mCharging) {
12747 if (mLastChargeStepLevel < level) {
12748 // We have not reporting that we are charging, but the level has now
12749 // gone up, so consider the state to be charging.
12750 changed |= setChargingLocked(true);
12751 mLastChargeStepLevel = level;
12752 }
12753 } else {
12754 if (mLastChargeStepLevel > level) {
12755 // We had reported that the device was charging, but here we are with
12756 // power connected and the level going down. Looks like the current
12757 // power supplied isn't enough, so consider the device to now be
12758 // discharging.
12759 changed |= setChargingLocked(false);
12760 mLastChargeStepLevel = level;
12761 }
12762 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012763 if (mLastChargeStepLevel != level && mMaxChargeStepLevel < level) {
12764 mChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
12765 modeBits, elapsedRealtime);
12766 mDailyChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
12767 modeBits, elapsedRealtime);
12768 mLastChargeStepLevel = level;
12769 mMaxChargeStepLevel = level;
12770 mInitStepMode = mCurStepMode;
12771 mModStepMode = 0;
Evan Millarc64edde2009-04-18 12:26:32 -070012772 }
12773 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012774 if (changed) {
12775 addHistoryRecordLocked(elapsedRealtime, uptime);
12776 }
Evan Millarc64edde2009-04-18 12:26:32 -070012777 }
Todd Poynor1acf06a2017-12-07 19:19:35 -080012778 if (!onBattery &&
12779 (status == BatteryManager.BATTERY_STATUS_FULL ||
12780 status == BatteryManager.BATTERY_STATUS_UNKNOWN)) {
12781 // We don't record history while we are plugged in and fully charged
12782 // (or when battery is not present). The next time we are
12783 // unplugged, history will be cleared.
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012784 mRecordingHistory = DEBUG;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080012785 }
Adam Lesinski041d9172016-12-12 12:03:56 -080012786
Jocelyn Dangc627d102017-04-14 13:15:14 -070012787 if (mMinLearnedBatteryCapacity == -1) {
12788 mMinLearnedBatteryCapacity = chargeFullUAh;
12789 } else {
12790 Math.min(mMinLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski041d9172016-12-12 12:03:56 -080012791 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070012792 mMaxLearnedBatteryCapacity = Math.max(mMaxLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski33dac552015-03-09 15:24:48 -070012793 }
12794
Sudheer Shankac57729a2018-02-09 15:44:42 -080012795 public static boolean isOnBattery(int plugType, int status) {
12796 return plugType == BATTERY_PLUGGED_NONE && status != BatteryManager.BATTERY_STATUS_UNKNOWN;
12797 }
12798
Bookatz8c6571b2017-10-24 15:04:41 -070012799 // Inform StatsLog of setBatteryState changes.
12800 // If this is the first reporting, pass in recentPast == null.
12801 private void reportChangesToStatsLog(HistoryItem recentPast,
Tej Singh40298312018-02-16 00:15:09 -080012802 final int status, final int plugType, final int level) {
Bookatz8c6571b2017-10-24 15:04:41 -070012803
12804 if (recentPast == null || recentPast.batteryStatus != status) {
12805 StatsLog.write(StatsLog.CHARGING_STATE_CHANGED, status);
12806 }
12807 if (recentPast == null || recentPast.batteryPlugType != plugType) {
12808 StatsLog.write(StatsLog.PLUGGED_STATE_CHANGED, plugType);
12809 }
12810 if (recentPast == null || recentPast.batteryLevel != level) {
12811 StatsLog.write(StatsLog.BATTERY_LEVEL_CHANGED, level);
12812 }
Bookatz8c6571b2017-10-24 15:04:41 -070012813 }
12814
Mathew Inwoodc185f082018-08-20 14:28:54 +010012815 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012816 public long getAwakeTimeBattery() {
12817 return computeBatteryUptime(getBatteryUptimeLocked(), STATS_CURRENT);
12818 }
12819
Mathew Inwoodc185f082018-08-20 14:28:54 +010012820 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012821 public long getAwakeTimePlugged() {
Joe Onoratoabded112016-02-08 16:49:39 -080012822 return (mClocks.uptimeMillis() * 1000) - getAwakeTimeBattery();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012823 }
12824
12825 @Override
12826 public long computeUptime(long curTime, int which) {
12827 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012828 case STATS_SINCE_CHARGED: return mUptime + (curTime-mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012829 case STATS_CURRENT: return (curTime-mUptimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070012830 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getUptimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012831 }
12832 return 0;
12833 }
12834
12835 @Override
12836 public long computeRealtime(long curTime, int which) {
12837 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012838 case STATS_SINCE_CHARGED: return mRealtime + (curTime-mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012839 case STATS_CURRENT: return (curTime-mRealtimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070012840 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getRealtimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012841 }
12842 return 0;
12843 }
12844
12845 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +010012846 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012847 public long computeBatteryUptime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012848 return mOnBatteryTimeBase.computeUptime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012849 }
12850
12851 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +010012852 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012853 public long computeBatteryRealtime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012854 return mOnBatteryTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012855 }
12856
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012857 @Override
12858 public long computeBatteryScreenOffUptime(long curTime, int which) {
12859 return mOnBatteryScreenOffTimeBase.computeUptime(curTime, which);
12860 }
12861
12862 @Override
12863 public long computeBatteryScreenOffRealtime(long curTime, int which) {
12864 return mOnBatteryScreenOffTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012865 }
12866
Dianne Hackborn260c5022014-04-29 11:23:16 -070012867 private long computeTimePerLevel(long[] steps, int numSteps) {
12868 // For now we'll do a simple average across all steps.
12869 if (numSteps <= 0) {
12870 return -1;
12871 }
12872 long total = 0;
12873 for (int i=0; i<numSteps; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012874 total += steps[i] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012875 }
12876 return total / numSteps;
12877 /*
12878 long[] buckets = new long[numSteps];
12879 int numBuckets = 0;
12880 int numToAverage = 4;
12881 int i = 0;
12882 while (i < numSteps) {
12883 long totalTime = 0;
12884 int num = 0;
12885 for (int j=0; j<numToAverage && (i+j)<numSteps; j++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012886 totalTime += steps[i+j] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012887 num++;
12888 }
12889 buckets[numBuckets] = totalTime / num;
12890 numBuckets++;
12891 numToAverage *= 2;
12892 i += num;
12893 }
12894 if (numBuckets < 1) {
12895 return -1;
12896 }
12897 long averageTime = buckets[numBuckets-1];
12898 for (i=numBuckets-2; i>=0; i--) {
12899 averageTime = (averageTime + buckets[i]) / 2;
12900 }
12901 return averageTime;
12902 */
12903 }
12904
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012905 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +010012906 @UnsupportedAppUsage
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012907 public long computeBatteryTimeRemaining(long curTime) {
12908 if (!mOnBattery) {
12909 return -1;
12910 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070012911 /* Simple implementation just looks at the average discharge per level across the
12912 entire sample period.
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012913 int discharge = (getLowDischargeAmountSinceCharge()+getHighDischargeAmountSinceCharge())/2;
12914 if (discharge < 2) {
12915 return -1;
12916 }
12917 long duration = computeBatteryRealtime(curTime, STATS_SINCE_CHARGED);
12918 if (duration < 1000*1000) {
12919 return -1;
12920 }
12921 long usPerLevel = duration/discharge;
12922 return usPerLevel * mCurrentBatteryLevel;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012923 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012924 if (mDischargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012925 return -1;
12926 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012927 long msPerLevel = mDischargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012928 if (msPerLevel <= 0) {
12929 return -1;
12930 }
12931 return (msPerLevel * mCurrentBatteryLevel) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012932 }
12933
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012934 @Override
12935 public LevelStepTracker getDischargeLevelStepTracker() {
12936 return mDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012937 }
12938
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012939 @Override
12940 public LevelStepTracker getDailyDischargeLevelStepTracker() {
12941 return mDailyDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012942 }
12943
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012944 @Override
12945 public long computeChargeTimeRemaining(long curTime) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012946 if (mOnBattery) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012947 // Not yet working.
12948 return -1;
12949 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070012950 /* Broken
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012951 int curLevel = mCurrentBatteryLevel;
12952 int plugLevel = mDischargePlugLevel;
12953 if (plugLevel < 0 || curLevel < (plugLevel+1)) {
12954 return -1;
12955 }
12956 long duration = computeBatteryRealtime(curTime, STATS_SINCE_UNPLUGGED);
12957 if (duration < 1000*1000) {
12958 return -1;
12959 }
12960 long usPerLevel = duration/(curLevel-plugLevel);
12961 return usPerLevel * (100-curLevel);
Dianne Hackborn260c5022014-04-29 11:23:16 -070012962 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012963 if (mChargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012964 return -1;
12965 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012966 long msPerLevel = mChargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012967 if (msPerLevel <= 0) {
12968 return -1;
12969 }
12970 return (msPerLevel * (100-mCurrentBatteryLevel)) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012971 }
12972
Siddharth Raya1fd0572017-11-13 14:20:47 -080012973 /*@hide */
12974 public CellularBatteryStats getCellularBatteryStats() {
12975 CellularBatteryStats s = new CellularBatteryStats();
12976 final int which = STATS_SINCE_CHARGED;
12977 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12978 final ControllerActivityCounter counter = getModemControllerActivity();
Siddharth Rayed754702018-02-15 12:44:37 -080012979 final long sleepTimeMs = counter.getSleepTimeCounter().getCountLocked(which);
Siddharth Raya1fd0572017-11-13 14:20:47 -080012980 final long idleTimeMs = counter.getIdleTimeCounter().getCountLocked(which);
12981 final long rxTimeMs = counter.getRxTimeCounter().getCountLocked(which);
12982 final long energyConsumedMaMs = counter.getPowerCounter().getCountLocked(which);
12983 long[] timeInRatMs = new long[BatteryStats.NUM_DATA_CONNECTION_TYPES];
12984 for (int i = 0; i < timeInRatMs.length; i++) {
12985 timeInRatMs[i] = getPhoneDataConnectionTime(i, rawRealTime, which) / 1000;
12986 }
12987 long[] timeInRxSignalStrengthLevelMs = new long[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
12988 for (int i = 0; i < timeInRxSignalStrengthLevelMs.length; i++) {
12989 timeInRxSignalStrengthLevelMs[i]
12990 = getPhoneSignalStrengthTime(i, rawRealTime, which) / 1000;
12991 }
12992 long[] txTimeMs = new long[Math.min(ModemActivityInfo.TX_POWER_LEVELS,
12993 counter.getTxTimeCounters().length)];
12994 long totalTxTimeMs = 0;
12995 for (int i = 0; i < txTimeMs.length; i++) {
12996 txTimeMs[i] = counter.getTxTimeCounters()[i].getCountLocked(which);
12997 totalTxTimeMs += txTimeMs[i];
12998 }
Siddharth Raya1fd0572017-11-13 14:20:47 -080012999 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
13000 s.setKernelActiveTimeMs(getMobileRadioActiveTime(rawRealTime, which) / 1000);
13001 s.setNumPacketsTx(getNetworkActivityPackets(NETWORK_MOBILE_TX_DATA, which));
13002 s.setNumBytesTx(getNetworkActivityBytes(NETWORK_MOBILE_TX_DATA, which));
13003 s.setNumPacketsRx(getNetworkActivityPackets(NETWORK_MOBILE_RX_DATA, which));
13004 s.setNumBytesRx(getNetworkActivityBytes(NETWORK_MOBILE_RX_DATA, which));
13005 s.setSleepTimeMs(sleepTimeMs);
13006 s.setIdleTimeMs(idleTimeMs);
13007 s.setRxTimeMs(rxTimeMs);
13008 s.setEnergyConsumedMaMs(energyConsumedMaMs);
13009 s.setTimeInRatMs(timeInRatMs);
13010 s.setTimeInRxSignalStrengthLevelMs(timeInRxSignalStrengthLevelMs);
13011 s.setTxTimeMs(txTimeMs);
13012 return s;
13013 }
13014
Siddharth Rayb50a6842017-12-14 15:15:28 -080013015 /*@hide */
13016 public WifiBatteryStats getWifiBatteryStats() {
13017 WifiBatteryStats s = new WifiBatteryStats();
13018 final int which = STATS_SINCE_CHARGED;
13019 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
13020 final ControllerActivityCounter counter = getWifiControllerActivity();
13021 final long idleTimeMs = counter.getIdleTimeCounter().getCountLocked(which);
13022 final long scanTimeMs = counter.getScanTimeCounter().getCountLocked(which);
13023 final long rxTimeMs = counter.getRxTimeCounter().getCountLocked(which);
13024 final long txTimeMs = counter.getTxTimeCounters()[0].getCountLocked(which);
13025 final long totalControllerActivityTimeMs
13026 = computeBatteryRealtime(SystemClock.elapsedRealtime() * 1000, which) / 1000;
13027 final long sleepTimeMs
13028 = totalControllerActivityTimeMs - (idleTimeMs + rxTimeMs + txTimeMs);
13029 final long energyConsumedMaMs = counter.getPowerCounter().getCountLocked(which);
13030 long numAppScanRequest = 0;
13031 for (int i = 0; i < mUidStats.size(); i++) {
13032 numAppScanRequest += mUidStats.valueAt(i).mWifiScanTimer.getCountLocked(which);
13033 }
13034 long[] timeInStateMs = new long[NUM_WIFI_STATES];
13035 for (int i=0; i<NUM_WIFI_STATES; i++) {
13036 timeInStateMs[i] = getWifiStateTime(i, rawRealTime, which) / 1000;
13037 }
13038 long[] timeInSupplStateMs = new long[NUM_WIFI_SUPPL_STATES];
13039 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
13040 timeInSupplStateMs[i] = getWifiSupplStateTime(i, rawRealTime, which) / 1000;
13041 }
13042 long[] timeSignalStrengthTimeMs = new long[NUM_WIFI_SIGNAL_STRENGTH_BINS];
13043 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
13044 timeSignalStrengthTimeMs[i] = getWifiSignalStrengthTime(i, rawRealTime, which) / 1000;
13045 }
13046 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
13047 s.setKernelActiveTimeMs(getWifiActiveTime(rawRealTime, which) / 1000);
13048 s.setNumPacketsTx(getNetworkActivityPackets(NETWORK_WIFI_TX_DATA, which));
13049 s.setNumBytesTx(getNetworkActivityBytes(NETWORK_WIFI_TX_DATA, which));
13050 s.setNumPacketsRx(getNetworkActivityPackets(NETWORK_WIFI_RX_DATA, which));
13051 s.setNumBytesRx(getNetworkActivityBytes(NETWORK_WIFI_RX_DATA, which));
13052 s.setSleepTimeMs(sleepTimeMs);
13053 s.setIdleTimeMs(idleTimeMs);
13054 s.setRxTimeMs(rxTimeMs);
13055 s.setTxTimeMs(txTimeMs);
13056 s.setScanTimeMs(scanTimeMs);
13057 s.setEnergyConsumedMaMs(energyConsumedMaMs);
13058 s.setNumAppScanRequest(numAppScanRequest);
13059 s.setTimeInStateMs(timeInStateMs);
13060 s.setTimeInSupplicantStateMs(timeInSupplStateMs);
13061 s.setTimeInRxSignalStrengthLevelMs(timeSignalStrengthTimeMs);
13062 return s;
13063 }
13064
Siddharth Ray78ccaf52017-12-23 16:16:21 -080013065 /*@hide */
13066 public GpsBatteryStats getGpsBatteryStats() {
13067 GpsBatteryStats s = new GpsBatteryStats();
13068 final int which = STATS_SINCE_CHARGED;
13069 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
13070 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
13071 s.setEnergyConsumedMaMs(getGpsBatteryDrainMaMs());
13072 long[] time = new long[GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS];
13073 for (int i=0; i<time.length; i++) {
13074 time[i] = getGpsSignalQualityTime(i, rawRealTime, which) / 1000;
13075 }
13076 s.setTimeInGpsSignalQualityLevel(time);
13077 return s;
13078 }
13079
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013080 @Override
13081 public LevelStepTracker getChargeLevelStepTracker() {
13082 return mChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070013083 }
13084
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013085 @Override
13086 public LevelStepTracker getDailyChargeLevelStepTracker() {
13087 return mDailyChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070013088 }
13089
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013090 @Override
13091 public ArrayList<PackageChange> getDailyPackageChanges() {
13092 return mDailyPackageChanges;
13093 }
13094
Joe Onoratoe1acd632016-02-23 13:25:10 -080013095 protected long getBatteryUptimeLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080013096 return mOnBatteryTimeBase.getUptime(mClocks.uptimeMillis() * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013097 }
13098
13099 @Override
13100 public long getBatteryUptime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013101 return mOnBatteryTimeBase.getUptime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013102 }
13103
13104 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +010013105 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013106 public long getBatteryRealtime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013107 return mOnBatteryTimeBase.getRealtime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013108 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -070013109
The Android Open Source Project10592532009-03-18 17:39:46 -070013110 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +010013111 @UnsupportedAppUsage
Evan Millar633a1742009-04-02 16:36:33 -070013112 public int getDischargeStartLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070013113 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070013114 return getDischargeStartLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070013115 }
13116 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013117
Evan Millar633a1742009-04-02 16:36:33 -070013118 public int getDischargeStartLevelLocked() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013119 return mDischargeUnplugLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070013120 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013121
The Android Open Source Project10592532009-03-18 17:39:46 -070013122 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +010013123 @UnsupportedAppUsage
Evan Millar633a1742009-04-02 16:36:33 -070013124 public int getDischargeCurrentLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070013125 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070013126 return getDischargeCurrentLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070013127 }
13128 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013129
Evan Millar633a1742009-04-02 16:36:33 -070013130 public int getDischargeCurrentLevelLocked() {
Dianne Hackborne4a59512010-12-07 11:08:07 -080013131 return mDischargeCurrentLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070013132 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013133
Amith Yamasanie43530a2009-08-21 13:11:37 -070013134 @Override
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013135 public int getLowDischargeAmountSinceCharge() {
13136 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080013137 int val = mLowDischargeAmountSinceCharge;
13138 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
13139 val += mDischargeUnplugLevel-mDischargeCurrentLevel-1;
13140 }
13141 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013142 }
13143 }
13144
13145 @Override
13146 public int getHighDischargeAmountSinceCharge() {
13147 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080013148 int val = mHighDischargeAmountSinceCharge;
13149 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
13150 val += mDischargeUnplugLevel-mDischargeCurrentLevel;
13151 }
13152 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013153 }
13154 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070013155
13156 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +010013157 @UnsupportedAppUsage
Dianne Hackborn40c87252014-03-19 16:55:40 -070013158 public int getDischargeAmount(int which) {
13159 int dischargeAmount = which == STATS_SINCE_CHARGED
13160 ? getHighDischargeAmountSinceCharge()
13161 : (getDischargeStartLevel() - getDischargeCurrentLevel());
13162 if (dischargeAmount < 0) {
13163 dischargeAmount = 0;
13164 }
13165 return dischargeAmount;
13166 }
13167
Mike Mac2f518a2017-09-19 16:06:03 -070013168 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +010013169 @UnsupportedAppUsage
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013170 public int getDischargeAmountScreenOn() {
13171 synchronized(this) {
13172 int val = mDischargeAmountScreenOn;
Mike Mac2f518a2017-09-19 16:06:03 -070013173 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013174 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
13175 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
13176 }
13177 return val;
13178 }
13179 }
13180
Mike Mac2f518a2017-09-19 16:06:03 -070013181 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013182 public int getDischargeAmountScreenOnSinceCharge() {
13183 synchronized(this) {
13184 int val = mDischargeAmountScreenOnSinceCharge;
Mike Mac2f518a2017-09-19 16:06:03 -070013185 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013186 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
13187 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
13188 }
13189 return val;
13190 }
13191 }
13192
Mike Mac2f518a2017-09-19 16:06:03 -070013193 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +010013194 @UnsupportedAppUsage
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013195 public int getDischargeAmountScreenOff() {
13196 synchronized(this) {
13197 int val = mDischargeAmountScreenOff;
Mike Mac2f518a2017-09-19 16:06:03 -070013198 if (mOnBattery && isScreenOff(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013199 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
13200 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
13201 }
Mike Mac2f518a2017-09-19 16:06:03 -070013202 // For backward compatibility, doze discharge is counted into screen off.
13203 return val + getDischargeAmountScreenDoze();
13204 }
13205 }
13206
13207 @Override
13208 public int getDischargeAmountScreenOffSinceCharge() {
13209 synchronized(this) {
13210 int val = mDischargeAmountScreenOffSinceCharge;
13211 if (mOnBattery && isScreenOff(mScreenState)
13212 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
13213 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
13214 }
13215 // For backward compatibility, doze discharge is counted into screen off.
13216 return val + getDischargeAmountScreenDozeSinceCharge();
13217 }
13218 }
13219
13220 @Override
13221 public int getDischargeAmountScreenDoze() {
13222 synchronized(this) {
13223 int val = mDischargeAmountScreenDoze;
13224 if (mOnBattery && isScreenDoze(mScreenState)
13225 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
13226 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
13227 }
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013228 return val;
13229 }
13230 }
13231
Mike Mac2f518a2017-09-19 16:06:03 -070013232 @Override
13233 public int getDischargeAmountScreenDozeSinceCharge() {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013234 synchronized(this) {
Mike Mac2f518a2017-09-19 16:06:03 -070013235 int val = mDischargeAmountScreenDozeSinceCharge;
13236 if (mOnBattery && isScreenDoze(mScreenState)
13237 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
13238 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013239 }
13240 return val;
13241 }
13242 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013244 /**
13245 * Retrieve the statistics object for a particular uid, creating if needed.
13246 */
Mathew Inwoodc185f082018-08-20 14:28:54 +010013247 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013248 public Uid getUidStatsLocked(int uid) {
13249 Uid u = mUidStats.get(uid);
13250 if (u == null) {
Joe Onoratoabded112016-02-08 16:49:39 -080013251 u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013252 mUidStats.put(uid, u);
13253 }
13254 return u;
13255 }
13256
Sudheer Shankab2f83c12017-11-13 19:25:01 -080013257 /**
13258 * Retrieve the statistics object for a particular uid. Returns null if the object is not
13259 * available.
13260 */
13261 public Uid getAvailableUidStatsLocked(int uid) {
13262 Uid u = mUidStats.get(uid);
13263 return u;
13264 }
13265
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070013266 public void onCleanupUserLocked(int userId) {
13267 final int firstUidForUser = UserHandle.getUid(userId, 0);
13268 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
Mike Ma234d1822018-03-13 18:53:21 -070013269 mPendingRemovedUids.add(
13270 new UidToRemove(firstUidForUser, lastUidForUser, mClocks.elapsedRealtime()));
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070013271 }
13272
13273 public void onUserRemovedLocked(int userId) {
13274 final int firstUidForUser = UserHandle.getUid(userId, 0);
13275 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
13276 mUidStats.put(firstUidForUser, null);
13277 mUidStats.put(lastUidForUser, null);
13278 final int firstIndex = mUidStats.indexOfKey(firstUidForUser);
13279 final int lastIndex = mUidStats.indexOfKey(lastUidForUser);
13280 mUidStats.removeAtRange(firstIndex, lastIndex - firstIndex + 1);
13281 }
13282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013283 /**
13284 * Remove the statistics object for a particular uid.
13285 */
Mathew Inwoodc185f082018-08-20 14:28:54 +010013286 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013287 public void removeUidStatsLocked(int uid) {
13288 mUidStats.remove(uid);
Mike Ma234d1822018-03-13 18:53:21 -070013289 mPendingRemovedUids.add(new UidToRemove(uid, mClocks.elapsedRealtime()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013290 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -070013291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013292 /**
13293 * Retrieve the statistics object for a particular process, creating
13294 * if needed.
13295 */
Mathew Inwoodc185f082018-08-20 14:28:54 +010013296 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013297 public Uid.Proc getProcessStatsLocked(int uid, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013298 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013299 Uid u = getUidStatsLocked(uid);
13300 return u.getProcessStatsLocked(name);
13301 }
13302
13303 /**
13304 * Retrieve the statistics object for a particular process, creating
13305 * if needed.
13306 */
Mathew Inwoodc185f082018-08-20 14:28:54 +010013307 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013308 public Uid.Pkg getPackageStatsLocked(int uid, String pkg) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013309 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013310 Uid u = getUidStatsLocked(uid);
13311 return u.getPackageStatsLocked(pkg);
13312 }
13313
13314 /**
13315 * Retrieve the statistics object for a particular service, creating
13316 * if needed.
13317 */
Mathew Inwoodc185f082018-08-20 14:28:54 +010013318 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013319 public Uid.Pkg.Serv getServiceStatsLocked(int uid, String pkg, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013320 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013321 Uid u = getUidStatsLocked(uid);
13322 return u.getServiceStatsLocked(pkg, name);
13323 }
13324
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013325 public void shutdownLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080013326 recordShutdownLocked(mClocks.elapsedRealtime(), mClocks.uptimeMillis());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013327 writeSyncLocked();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013328 mShuttingDown = true;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013329 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013330
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013331 public boolean trackPerProcStateCpuTimes() {
13332 return mConstants.TRACK_CPU_TIMES_BY_PROC_STATE && mPerProcStateCpuTimesAvailable;
13333 }
13334
13335 public void systemServicesReady(Context context) {
13336 mConstants.startObserving(context.getContentResolver());
Mike Mafbc01fc2018-04-02 10:28:28 -070013337 registerUsbStateReceiver(context);
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013338 }
13339
13340 @VisibleForTesting
13341 public final class Constants extends ContentObserver {
13342 public static final String KEY_TRACK_CPU_TIMES_BY_PROC_STATE
13343 = "track_cpu_times_by_proc_state";
Mike Mafae87da2018-01-19 20:07:20 -080013344 public static final String KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME
13345 = "track_cpu_active_cluster_time";
Sudheer Shankac20379e2018-02-15 00:06:21 -080013346 public static final String KEY_PROC_STATE_CPU_TIMES_READ_DELAY_MS
13347 = "proc_state_cpu_times_read_delay_ms";
Mike Ma2ab01442018-02-13 14:22:47 -080013348 public static final String KEY_KERNEL_UID_READERS_THROTTLE_TIME
13349 = "kernel_uid_readers_throttle_time";
Mike Ma234d1822018-03-13 18:53:21 -070013350 public static final String KEY_UID_REMOVE_DELAY_MS
13351 = "uid_remove_delay_ms";
Sudheer Shankae56013a2018-04-23 11:22:15 -070013352 public static final String KEY_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS
13353 = "external_stats_collection_rate_limit_ms";
Sudheer Shanka0719c6a2018-04-24 11:12:11 -070013354 public static final String KEY_BATTERY_LEVEL_COLLECTION_DELAY_MS
13355 = "battery_level_collection_delay_ms";
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013356
13357 private static final boolean DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE = true;
Mike Mafae87da2018-01-19 20:07:20 -080013358 private static final boolean DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME = true;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013359 private static final long DEFAULT_PROC_STATE_CPU_TIMES_READ_DELAY_MS = 5_000;
Mike Ma2ab01442018-02-13 14:22:47 -080013360 private static final long DEFAULT_KERNEL_UID_READERS_THROTTLE_TIME = 10_000;
Mike Ma234d1822018-03-13 18:53:21 -070013361 private static final long DEFAULT_UID_REMOVE_DELAY_MS = 5L * 60L * 1000L;
Sudheer Shankae56013a2018-04-23 11:22:15 -070013362 private static final long DEFAULT_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS = 600_000;
Sudheer Shanka0719c6a2018-04-24 11:12:11 -070013363 private static final long DEFAULT_BATTERY_LEVEL_COLLECTION_DELAY_MS = 300_000;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013364
13365 public boolean TRACK_CPU_TIMES_BY_PROC_STATE = DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE;
Mike Mafae87da2018-01-19 20:07:20 -080013366 public boolean TRACK_CPU_ACTIVE_CLUSTER_TIME = DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013367 public long PROC_STATE_CPU_TIMES_READ_DELAY_MS = DEFAULT_PROC_STATE_CPU_TIMES_READ_DELAY_MS;
Mike Ma2ab01442018-02-13 14:22:47 -080013368 public long KERNEL_UID_READERS_THROTTLE_TIME = DEFAULT_KERNEL_UID_READERS_THROTTLE_TIME;
Mike Ma234d1822018-03-13 18:53:21 -070013369 public long UID_REMOVE_DELAY_MS = DEFAULT_UID_REMOVE_DELAY_MS;
Sudheer Shankae56013a2018-04-23 11:22:15 -070013370 public long EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS
13371 = DEFAULT_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS;
Sudheer Shanka0719c6a2018-04-24 11:12:11 -070013372 public long BATTERY_LEVEL_COLLECTION_DELAY_MS
13373 = DEFAULT_BATTERY_LEVEL_COLLECTION_DELAY_MS;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013374
13375 private ContentResolver mResolver;
13376 private final KeyValueListParser mParser = new KeyValueListParser(',');
13377
13378 public Constants(Handler handler) {
13379 super(handler);
13380 }
13381
13382 public void startObserving(ContentResolver resolver) {
13383 mResolver = resolver;
13384 mResolver.registerContentObserver(
13385 Settings.Global.getUriFor(Settings.Global.BATTERY_STATS_CONSTANTS),
13386 false /* notifyForDescendants */, this);
13387 updateConstants();
13388 }
13389
13390 @Override
13391 public void onChange(boolean selfChange, Uri uri) {
13392 updateConstants();
13393 }
13394
13395 private void updateConstants() {
13396 synchronized (BatteryStatsImpl.this) {
13397 try {
13398 mParser.setString(Settings.Global.getString(mResolver,
13399 Settings.Global.BATTERY_STATS_CONSTANTS));
13400 } catch (IllegalArgumentException e) {
13401 // Failed to parse the settings string, log this and move on
13402 // with defaults.
13403 Slog.e(TAG, "Bad batterystats settings", e);
13404 }
13405
13406 updateTrackCpuTimesByProcStateLocked(TRACK_CPU_TIMES_BY_PROC_STATE,
13407 mParser.getBoolean(KEY_TRACK_CPU_TIMES_BY_PROC_STATE,
13408 DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE));
Mike Mafae87da2018-01-19 20:07:20 -080013409 TRACK_CPU_ACTIVE_CLUSTER_TIME = mParser.getBoolean(
13410 KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME, DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME);
Sudheer Shankac20379e2018-02-15 00:06:21 -080013411 updateProcStateCpuTimesReadDelayMs(PROC_STATE_CPU_TIMES_READ_DELAY_MS,
13412 mParser.getLong(KEY_PROC_STATE_CPU_TIMES_READ_DELAY_MS,
Mike Ma2ab01442018-02-13 14:22:47 -080013413 DEFAULT_PROC_STATE_CPU_TIMES_READ_DELAY_MS));
13414 updateKernelUidReadersThrottleTime(KERNEL_UID_READERS_THROTTLE_TIME,
13415 mParser.getLong(KEY_KERNEL_UID_READERS_THROTTLE_TIME,
13416 DEFAULT_KERNEL_UID_READERS_THROTTLE_TIME));
Mike Ma234d1822018-03-13 18:53:21 -070013417 updateUidRemoveDelay(
13418 mParser.getLong(KEY_UID_REMOVE_DELAY_MS, DEFAULT_UID_REMOVE_DELAY_MS));
Sudheer Shankae56013a2018-04-23 11:22:15 -070013419 EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS = mParser.getLong(
13420 KEY_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS,
13421 DEFAULT_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS);
Sudheer Shanka0719c6a2018-04-24 11:12:11 -070013422 BATTERY_LEVEL_COLLECTION_DELAY_MS = mParser.getLong(
13423 KEY_BATTERY_LEVEL_COLLECTION_DELAY_MS,
13424 DEFAULT_BATTERY_LEVEL_COLLECTION_DELAY_MS);
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013425 }
13426 }
13427
13428 private void updateTrackCpuTimesByProcStateLocked(boolean wasEnabled, boolean isEnabled) {
13429 TRACK_CPU_TIMES_BY_PROC_STATE = isEnabled;
13430 if (isEnabled && !wasEnabled) {
13431 mKernelSingleUidTimeReader.markDataAsStale(true);
13432 mExternalSync.scheduleCpuSyncDueToSettingChange();
Sudheer Shankac20379e2018-02-15 00:06:21 -080013433
Mike Ma234d1822018-03-13 18:53:21 -070013434 mNumSingleUidCpuTimeReads = 0;
13435 mNumBatchedSingleUidCpuTimeReads = 0;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013436 mCpuTimeReadsTrackingStartTime = mClocks.uptimeMillis();
13437 }
13438 }
13439
13440 private void updateProcStateCpuTimesReadDelayMs(long oldDelayMillis, long newDelayMillis) {
13441 PROC_STATE_CPU_TIMES_READ_DELAY_MS = newDelayMillis;
13442 if (oldDelayMillis != newDelayMillis) {
Mike Ma234d1822018-03-13 18:53:21 -070013443 mNumSingleUidCpuTimeReads = 0;
13444 mNumBatchedSingleUidCpuTimeReads = 0;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013445 mCpuTimeReadsTrackingStartTime = mClocks.uptimeMillis();
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013446 }
13447 }
13448
Mike Ma2ab01442018-02-13 14:22:47 -080013449 private void updateKernelUidReadersThrottleTime(long oldTimeMs, long newTimeMs) {
13450 KERNEL_UID_READERS_THROTTLE_TIME = newTimeMs;
13451 if (oldTimeMs != newTimeMs) {
Mike Ma69d8b3e2018-02-23 14:51:26 -080013452 mKernelUidCpuTimeReader.setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
Mike Ma2ab01442018-02-13 14:22:47 -080013453 mKernelUidCpuFreqTimeReader.setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
13454 mKernelUidCpuActiveTimeReader.setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
13455 mKernelUidCpuClusterTimeReader
13456 .setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
13457 }
13458 }
13459
Mike Ma234d1822018-03-13 18:53:21 -070013460 private void updateUidRemoveDelay(long newTimeMs) {
13461 UID_REMOVE_DELAY_MS = newTimeMs;
13462 clearPendingRemovedUids();
13463 }
13464
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013465 public void dumpLocked(PrintWriter pw) {
13466 pw.print(KEY_TRACK_CPU_TIMES_BY_PROC_STATE); pw.print("=");
13467 pw.println(TRACK_CPU_TIMES_BY_PROC_STATE);
Mike Mafae87da2018-01-19 20:07:20 -080013468 pw.print(KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME); pw.print("=");
13469 pw.println(TRACK_CPU_ACTIVE_CLUSTER_TIME);
Sudheer Shankac20379e2018-02-15 00:06:21 -080013470 pw.print(KEY_PROC_STATE_CPU_TIMES_READ_DELAY_MS); pw.print("=");
13471 pw.println(PROC_STATE_CPU_TIMES_READ_DELAY_MS);
Mike Ma2ab01442018-02-13 14:22:47 -080013472 pw.print(KEY_KERNEL_UID_READERS_THROTTLE_TIME); pw.print("=");
13473 pw.println(KERNEL_UID_READERS_THROTTLE_TIME);
Sudheer Shankae56013a2018-04-23 11:22:15 -070013474 pw.print(KEY_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS); pw.print("=");
13475 pw.println(EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS);
Sudheer Shanka0719c6a2018-04-24 11:12:11 -070013476 pw.print(KEY_BATTERY_LEVEL_COLLECTION_DELAY_MS); pw.print("=");
13477 pw.println(BATTERY_LEVEL_COLLECTION_DELAY_MS);
Sudheer Shankae56013a2018-04-23 11:22:15 -070013478 }
13479 }
13480
13481 public long getExternalStatsCollectionRateLimitMs() {
13482 synchronized (this) {
13483 return mConstants.EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013484 }
13485 }
13486
Andreas Gampe3f24e692018-02-05 13:24:28 -080013487 @GuardedBy("this")
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013488 public void dumpConstantsLocked(PrintWriter pw) {
13489 mConstants.dumpLocked(pw);
13490 }
13491
Mike Ma234d1822018-03-13 18:53:21 -070013492 @GuardedBy("this")
13493 public void dumpCpuStatsLocked(PrintWriter pw) {
13494 int size = mUidStats.size();
13495 pw.println("Per UID CPU user & system time in ms:");
13496 for (int i = 0; i < size; i++) {
13497 int u = mUidStats.keyAt(i);
13498 Uid uid = mUidStats.get(u);
13499 pw.print(" "); pw.print(u); pw.print(": ");
13500 pw.print(uid.getUserCpuTimeUs(STATS_SINCE_CHARGED) / 1000); pw.print(" ");
13501 pw.println(uid.getSystemCpuTimeUs(STATS_SINCE_CHARGED) / 1000);
13502 }
13503 pw.println("Per UID CPU active time in ms:");
13504 for (int i = 0; i < size; i++) {
13505 int u = mUidStats.keyAt(i);
13506 Uid uid = mUidStats.get(u);
13507 if (uid.getCpuActiveTime() > 0) {
13508 pw.print(" "); pw.print(u); pw.print(": "); pw.println(uid.getCpuActiveTime());
13509 }
13510 }
13511 pw.println("Per UID CPU cluster time in ms:");
13512 for (int i = 0; i < size; i++) {
13513 int u = mUidStats.keyAt(i);
13514 long[] times = mUidStats.get(u).getCpuClusterTimes();
13515 if (times != null) {
13516 pw.print(" "); pw.print(u); pw.print(": "); pw.println(Arrays.toString(times));
13517 }
13518 }
13519 pw.println("Per UID CPU frequency time in ms:");
13520 for (int i = 0; i < size; i++) {
13521 int u = mUidStats.keyAt(i);
13522 long[] times = mUidStats.get(u).getCpuFreqTimes(STATS_SINCE_CHARGED);
13523 if (times != null) {
13524 pw.print(" "); pw.print(u); pw.print(": "); pw.println(Arrays.toString(times));
13525 }
13526 }
13527 }
13528
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013529 Parcel mPendingWrite = null;
13530 final ReentrantLock mWriteLock = new ReentrantLock();
13531
13532 public void writeAsyncLocked() {
13533 writeLocked(false);
13534 }
13535
13536 public void writeSyncLocked() {
13537 writeLocked(true);
13538 }
13539
13540 void writeLocked(boolean sync) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013541 if (mFile == null) {
13542 Slog.w("BatteryStats", "writeLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013543 return;
13544 }
13545
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013546 if (mShuttingDown) {
13547 return;
13548 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013549
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013550 Parcel out = Parcel.obtain();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013551 writeSummaryToParcel(out, true);
Joe Onoratoabded112016-02-08 16:49:39 -080013552 mLastWriteTime = mClocks.elapsedRealtime();
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013553
13554 if (mPendingWrite != null) {
13555 mPendingWrite.recycle();
13556 }
13557 mPendingWrite = out;
13558
13559 if (sync) {
13560 commitPendingDataToDisk();
13561 } else {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013562 BackgroundThread.getHandler().post(new Runnable() {
13563 @Override public void run() {
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013564 commitPendingDataToDisk();
13565 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013566 });
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013567 }
13568 }
13569
Mathew Inwoodc185f082018-08-20 14:28:54 +010013570 @UnsupportedAppUsage
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013571 public void commitPendingDataToDisk() {
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070013572 final Parcel next;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013573 synchronized (this) {
13574 next = mPendingWrite;
13575 mPendingWrite = null;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070013576 if (next == null) {
13577 return;
13578 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013579 }
13580
Amith Yamasanid2450862017-02-07 15:58:24 -080013581 mWriteLock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013582 try {
Dianne Hackborne17b4452018-01-10 13:15:40 -080013583 final long startTime = SystemClock.uptimeMillis();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013584 FileOutputStream stream = new FileOutputStream(mFile.chooseForWrite());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013585 stream.write(next.marshall());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013586 stream.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070013587 FileUtils.sync(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013588 stream.close();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013589 mFile.commit();
Dianne Hackborne17b4452018-01-10 13:15:40 -080013590 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
13591 "batterystats", SystemClock.uptimeMillis() - startTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013592 } catch (IOException e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013593 Slog.w("BatteryStats", "Error writing battery statistics", e);
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013594 mFile.rollback();
13595 } finally {
13596 next.recycle();
13597 mWriteLock.unlock();
Suchi Amalapurapu8550f252009-09-29 15:20:32 -070013598 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013599 }
13600
Mathew Inwoodc185f082018-08-20 14:28:54 +010013601 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013602 public void readLocked() {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013603 if (mDailyFile != null) {
13604 readDailyStatsLocked();
13605 }
13606
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013607 if (mFile == null) {
13608 Slog.w("BatteryStats", "readLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013609 return;
13610 }
13611
13612 mUidStats.clear();
13613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013614 try {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013615 File file = mFile.chooseForRead();
13616 if (!file.exists()) {
13617 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013618 }
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013619 FileInputStream stream = new FileInputStream(file);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013620
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013621 byte[] raw = BatteryStatsHelper.readFully(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013622 Parcel in = Parcel.obtain();
13623 in.unmarshall(raw, 0, raw.length);
13624 in.setDataPosition(0);
13625 stream.close();
13626
13627 readSummaryFromParcel(in);
Dianne Hackborn00e25212014-02-19 10:49:24 -080013628 } catch(Exception e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013629 Slog.e("BatteryStats", "Error reading battery statistics", e);
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013630 resetAllStatsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013631 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013632
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013633 mEndPlatformVersion = Build.ID;
13634
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013635 if (mHistoryBuffer.dataPosition() > 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013636 mRecordingHistory = true;
Joe Onoratoabded112016-02-08 16:49:39 -080013637 final long elapsedRealtime = mClocks.elapsedRealtime();
13638 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013639 if (USE_OLD_HISTORY) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013640 addHistoryRecordLocked(elapsedRealtime, uptime, HistoryItem.CMD_START, mHistoryCur);
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013641 }
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000013642 addHistoryBufferLocked(elapsedRealtime, HistoryItem.CMD_START, mHistoryCur);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013643 startRecordingHistory(elapsedRealtime, uptime, false);
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013644 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013645
13646 recordDailyStatsIfNeededLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013647 }
13648
13649 public int describeContents() {
13650 return 0;
13651 }
13652
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013653 void readHistory(Parcel in, boolean andOldHistory) throws ParcelFormatException {
Dianne Hackbornae384452011-06-28 12:33:48 -070013654 final long historyBaseTime = in.readLong();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013655
13656 mHistoryBuffer.setDataSize(0);
13657 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013658 mHistoryTagPool.clear();
13659 mNextHistoryTagIdx = 0;
13660 mNumHistoryTagChars = 0;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013661
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013662 int numTags = in.readInt();
13663 for (int i=0; i<numTags; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080013664 int idx = in.readInt();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013665 String str = in.readString();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013666 if (str == null) {
13667 throw new ParcelFormatException("null history tag string");
13668 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013669 int uid = in.readInt();
13670 HistoryTag tag = new HistoryTag();
13671 tag.string = str;
13672 tag.uid = uid;
13673 tag.poolIdx = idx;
13674 mHistoryTagPool.put(tag, idx);
13675 if (idx >= mNextHistoryTagIdx) {
13676 mNextHistoryTagIdx = idx+1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013677 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013678 mNumHistoryTagChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013679 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013680
13681 int bufSize = in.readInt();
13682 int curPos = in.dataPosition();
13683 if (bufSize >= (MAX_MAX_HISTORY_BUFFER*3)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013684 throw new ParcelFormatException("File corrupt: history data buffer too large " +
13685 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013686 } else if ((bufSize&~3) != bufSize) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013687 throw new ParcelFormatException("File corrupt: history data buffer not aligned " +
13688 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013689 } else {
13690 if (DEBUG_HISTORY) Slog.i(TAG, "***************** READING NEW HISTORY: " + bufSize
13691 + " bytes at " + curPos);
13692 mHistoryBuffer.appendFrom(in, curPos, bufSize);
13693 in.setDataPosition(curPos + bufSize);
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013694 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013695
Dianne Hackbornae384452011-06-28 12:33:48 -070013696 if (andOldHistory) {
13697 readOldHistory(in);
13698 }
13699
13700 if (DEBUG_HISTORY) {
13701 StringBuilder sb = new StringBuilder(128);
13702 sb.append("****************** OLD mHistoryBaseTime: ");
13703 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13704 Slog.i(TAG, sb.toString());
13705 }
13706 mHistoryBaseTime = historyBaseTime;
13707 if (DEBUG_HISTORY) {
13708 StringBuilder sb = new StringBuilder(128);
13709 sb.append("****************** NEW mHistoryBaseTime: ");
13710 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13711 Slog.i(TAG, sb.toString());
13712 }
13713
13714 // We are just arbitrarily going to insert 1 minute from the sample of
13715 // the last run until samples in this run.
13716 if (mHistoryBaseTime > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -080013717 long oldnow = mClocks.elapsedRealtime();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013718 mHistoryBaseTime = mHistoryBaseTime - oldnow + 1;
Dianne Hackbornae384452011-06-28 12:33:48 -070013719 if (DEBUG_HISTORY) {
13720 StringBuilder sb = new StringBuilder(128);
13721 sb.append("****************** ADJUSTED mHistoryBaseTime: ");
13722 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13723 Slog.i(TAG, sb.toString());
13724 }
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -070013725 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013726 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013727
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013728 void readOldHistory(Parcel in) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013729 if (!USE_OLD_HISTORY) {
13730 return;
13731 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013732 mHistory = mHistoryEnd = mHistoryCache = null;
13733 long time;
Conley Owens5e3357f2011-05-02 09:59:30 -070013734 while (in.dataAvail() > 0 && (time=in.readLong()) >= 0) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013735 HistoryItem rec = new HistoryItem(time, in);
13736 addHistoryRecordLocked(rec);
13737 }
13738 }
13739
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013740 void writeHistory(Parcel out, boolean inclData, boolean andOldHistory) {
Dianne Hackbornae384452011-06-28 12:33:48 -070013741 if (DEBUG_HISTORY) {
13742 StringBuilder sb = new StringBuilder(128);
13743 sb.append("****************** WRITING mHistoryBaseTime: ");
13744 TimeUtils.formatDuration(mHistoryBaseTime, sb);
Dianne Hackborn40c87252014-03-19 16:55:40 -070013745 sb.append(" mLastHistoryElapsedRealtime: ");
13746 TimeUtils.formatDuration(mLastHistoryElapsedRealtime, sb);
Dianne Hackbornae384452011-06-28 12:33:48 -070013747 Slog.i(TAG, sb.toString());
13748 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070013749 out.writeLong(mHistoryBaseTime + mLastHistoryElapsedRealtime);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013750 if (!inclData) {
13751 out.writeInt(0);
13752 out.writeInt(0);
13753 return;
13754 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013755 out.writeInt(mHistoryTagPool.size());
13756 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
13757 HistoryTag tag = ent.getKey();
Dianne Hackborn099bc622014-01-22 13:39:16 -080013758 out.writeInt(ent.getValue());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013759 out.writeString(tag.string);
13760 out.writeInt(tag.uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -080013761 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013762 out.writeInt(mHistoryBuffer.dataSize());
13763 if (DEBUG_HISTORY) Slog.i(TAG, "***************** WRITING HISTORY: "
13764 + mHistoryBuffer.dataSize() + " bytes at " + out.dataPosition());
13765 out.appendFrom(mHistoryBuffer, 0, mHistoryBuffer.dataSize());
Dianne Hackbornae384452011-06-28 12:33:48 -070013766
13767 if (andOldHistory) {
13768 writeOldHistory(out);
13769 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013770 }
13771
13772 void writeOldHistory(Parcel out) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013773 if (!USE_OLD_HISTORY) {
13774 return;
13775 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013776 HistoryItem rec = mHistory;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013777 while (rec != null) {
13778 if (rec.time >= 0) rec.writeToParcel(out, 0);
13779 rec = rec.next;
13780 }
13781 out.writeLong(-1);
13782 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013783
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013784 public void readSummaryFromParcel(Parcel in) throws ParcelFormatException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013785 final int version = in.readInt();
13786 if (version != VERSION) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013787 Slog.w("BatteryStats", "readFromParcel: version got " + version
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013788 + ", expected " + VERSION + "; erasing old stats");
13789 return;
13790 }
13791
Dianne Hackbornae384452011-06-28 12:33:48 -070013792 readHistory(in, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013794 mStartCount = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013795 mUptime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013796 mRealtime = in.readLong();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080013797 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013798 mStartPlatformVersion = in.readString();
13799 mEndPlatformVersion = in.readString();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013800 mOnBatteryTimeBase.readSummaryFromParcel(in);
13801 mOnBatteryScreenOffTimeBase.readSummaryFromParcel(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013802 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013803 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070013804 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013805 mCurrentBatteryLevel = in.readInt();
Adam Lesinskif9b20a92016-06-17 17:30:01 -070013806 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070013807 mMinLearnedBatteryCapacity = in.readInt();
13808 mMaxLearnedBatteryCapacity = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013809 mLowDischargeAmountSinceCharge = in.readInt();
13810 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013811 mDischargeAmountScreenOnSinceCharge = in.readInt();
13812 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070013813 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013814 mDischargeStepTracker.readFromParcel(in);
13815 mChargeStepTracker.readFromParcel(in);
13816 mDailyDischargeStepTracker.readFromParcel(in);
13817 mDailyChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070013818 mDischargeCounter.readSummaryFromParcelLocked(in);
13819 mDischargeScreenOffCounter.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070013820 mDischargeScreenDozeCounter.readSummaryFromParcelLocked(in);
Mike Ma15313c92017-11-15 17:58:21 -080013821 mDischargeLightDozeCounter.readSummaryFromParcelLocked(in);
13822 mDischargeDeepDozeCounter.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013823 int NPKG = in.readInt();
13824 if (NPKG > 0) {
13825 mDailyPackageChanges = new ArrayList<>(NPKG);
13826 while (NPKG > 0) {
13827 NPKG--;
13828 PackageChange pc = new PackageChange();
13829 pc.mPackageName = in.readString();
13830 pc.mUpdate = in.readInt() != 0;
Dianne Hackborn3accca02013-09-20 09:32:11 -070013831 pc.mVersionCode = in.readLong();
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013832 mDailyPackageChanges.add(pc);
13833 }
13834 } else {
13835 mDailyPackageChanges = null;
13836 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013837 mDailyStartTime = in.readLong();
13838 mNextMinDailyDeadline = in.readLong();
13839 mNextMaxDailyDeadline = in.readLong();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013840
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013841 mStartCount++;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013842
Jeff Browne95c3cd2014-05-02 16:59:26 -070013843 mScreenState = Display.STATE_UNKNOWN;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013844 mScreenOnTimer.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070013845 mScreenDozeTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn617f8772009-03-31 15:04:46 -070013846 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
13847 mScreenBrightnessTimer[i].readSummaryFromParcelLocked(in);
13848 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070013849 mInteractive = false;
13850 mInteractiveTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013851 mPhoneOn = false;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070013852 mPowerSaveModeEnabledTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070013853 mLongestLightIdleTime = in.readLong();
13854 mLongestFullIdleTime = in.readLong();
13855 mDeviceIdleModeLightTimer.readSummaryFromParcelLocked(in);
13856 mDeviceIdleModeFullTimer.readSummaryFromParcelLocked(in);
13857 mDeviceLightIdlingTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013858 mDeviceIdlingTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013859 mPhoneOnTimer.readSummaryFromParcelLocked(in);
Wink Saville52840902011-02-18 12:40:47 -080013860 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn627bba72009-03-24 22:32:56 -070013861 mPhoneSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
13862 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070013863 mPhoneSignalScanningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013864 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
13865 mPhoneDataConnectionsTimer[i].readSummaryFromParcelLocked(in);
13866 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013867 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013868 mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
13869 mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013870 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013871 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborne13c4c02014-02-11 17:18:35 -080013872 mMobileRadioActiveTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080013873 mMobileRadioActivePerAppTimer.readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013874 mMobileRadioActiveAdjustedTime.readSummaryFromParcelLocked(in);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013875 mMobileRadioActiveUnknownTime.readSummaryFromParcelLocked(in);
13876 mMobileRadioActiveUnknownCount.readSummaryFromParcelLocked(in);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080013877 mWifiMulticastWakelockTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070013878 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
The Android Open Source Project10592532009-03-18 17:39:46 -070013879 mWifiOn = false;
13880 mWifiOnTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013881 mGlobalWifiRunning = false;
13882 mGlobalWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080013883 for (int i=0; i<NUM_WIFI_STATES; i++) {
13884 mWifiStateTimer[i].readSummaryFromParcelLocked(in);
13885 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070013886 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
13887 mWifiSupplStateTimer[i].readSummaryFromParcelLocked(in);
13888 }
13889 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
13890 mWifiSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
13891 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080013892 mWifiActiveTimer.readSummaryFromParcelLocked(in);
13893 mWifiActivity.readSummaryFromParcel(in);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080013894 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
13895 mGpsSignalQualityTimer[i].readSummaryFromParcelLocked(in);
13896 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080013897 mBluetoothActivity.readSummaryFromParcel(in);
13898 mModemActivity.readSummaryFromParcel(in);
13899 mHasWifiReporting = in.readInt() != 0;
13900 mHasBluetoothReporting = in.readInt() != 0;
13901 mHasModemReporting = in.readInt() != 0;
Adam Lesinski33dac552015-03-09 15:24:48 -070013902
Dianne Hackborn1e01d162014-12-04 17:46:42 -080013903 mNumConnectivityChange = mLoadedNumConnectivityChange = in.readInt();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013904 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -070013905 mFlashlightOnTimer.readSummaryFromParcelLocked(in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013906 mCameraOnNesting = 0;
13907 mCameraOnTimer.readSummaryFromParcelLocked(in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013908 mBluetoothScanNesting = 0;
13909 mBluetoothScanTimer.readSummaryFromParcelLocked(in);
Siddharth Rayf5e796a2018-01-22 18:18:17 -080013910 mIsCellularTxPowerHigh = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013911
Bookatz50df7112017-08-04 14:53:26 -070013912 int NRPMS = in.readInt();
13913 if (NRPMS > 10000) {
13914 throw new ParcelFormatException("File corrupt: too many rpm stats " + NRPMS);
13915 }
13916 for (int irpm = 0; irpm < NRPMS; irpm++) {
13917 if (in.readInt() != 0) {
13918 String rpmName = in.readString();
13919 getRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
13920 }
13921 }
13922 int NSORPMS = in.readInt();
13923 if (NSORPMS > 10000) {
13924 throw new ParcelFormatException("File corrupt: too many screen-off rpm stats " + NSORPMS);
13925 }
13926 for (int irpm = 0; irpm < NSORPMS; irpm++) {
13927 if (in.readInt() != 0) {
13928 String rpmName = in.readString();
13929 getScreenOffRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
13930 }
13931 }
13932
Evan Millarc64edde2009-04-18 12:26:32 -070013933 int NKW = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013934 if (NKW > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013935 throw new ParcelFormatException("File corrupt: too many kernel wake locks " + NKW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013936 }
Evan Millarc64edde2009-04-18 12:26:32 -070013937 for (int ikw = 0; ikw < NKW; ikw++) {
13938 if (in.readInt() != 0) {
13939 String kwltName = in.readString();
13940 getKernelWakelockTimerLocked(kwltName).readSummaryFromParcelLocked(in);
13941 }
13942 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070013943
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013944 int NWR = in.readInt();
13945 if (NWR > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013946 throw new ParcelFormatException("File corrupt: too many wakeup reasons " + NWR);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013947 }
13948 for (int iwr = 0; iwr < NWR; iwr++) {
13949 if (in.readInt() != 0) {
13950 String reasonName = in.readString();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070013951 getWakeupReasonTimerLocked(reasonName).readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013952 }
13953 }
13954
James Carr3a226052016-07-01 14:49:52 -070013955 int NMS = in.readInt();
13956 for (int ims = 0; ims < NMS; ims++) {
13957 if (in.readInt() != 0) {
13958 long kmstName = in.readLong();
13959 getKernelMemoryTimerLocked(kmstName).readSummaryFromParcelLocked(in);
13960 }
13961 }
13962
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013963 final int NU = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013964 if (NU > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013965 throw new ParcelFormatException("File corrupt: too many uids " + NU);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013966 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013967 for (int iu = 0; iu < NU; iu++) {
13968 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080013969 Uid u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013970 mUidStats.put(uid, u);
13971
Bookatz867c0d72017-03-07 18:23:42 -080013972 u.mOnBatteryBackgroundTimeBase.readSummaryFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -070013973 u.mOnBatteryScreenOffBackgroundTimeBase.readSummaryFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -080013974
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013975 u.mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013976 if (in.readInt() != 0) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013977 u.mWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013978 }
The Android Open Source Project10592532009-03-18 17:39:46 -070013979 u.mFullWifiLockOut = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013980 if (in.readInt() != 0) {
13981 u.mFullWifiLockTimer.readSummaryFromParcelLocked(in);
13982 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070013983 u.mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013984 if (in.readInt() != 0) {
Nick Pelly6ccaa542012-06-15 15:22:47 -070013985 u.mWifiScanTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013986 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070013987 u.mWifiBatchedScanBinStarted = Uid.NO_BATCHED_SCAN_STARTED;
13988 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
13989 if (in.readInt() != 0) {
13990 u.makeWifiBatchedScanBin(i, null);
13991 u.mWifiBatchedScanTimer[i].readSummaryFromParcelLocked(in);
13992 }
13993 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070013994 u.mWifiMulticastEnabled = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013995 if (in.readInt() != 0) {
13996 u.mWifiMulticastTimer.readSummaryFromParcelLocked(in);
13997 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013998 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013999 u.createAudioTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014000 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014001 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014002 u.createVideoTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
14003 }
14004 if (in.readInt() != 0) {
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014005 u.createFlashlightTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
14006 }
14007 if (in.readInt() != 0) {
14008 u.createCameraTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
14009 }
14010 if (in.readInt() != 0) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014011 u.createForegroundActivityTimerLocked().readSummaryFromParcelLocked(in);
14012 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014013 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070014014 u.createForegroundServiceTimerLocked().readSummaryFromParcelLocked(in);
14015 }
14016 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -070014017 u.createAggregatedPartialWakelockTimerLocked().readSummaryFromParcelLocked(in);
14018 }
14019 if (in.readInt() != 0) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014020 u.createBluetoothScanTimerLocked().readSummaryFromParcelLocked(in);
14021 }
Bookatz956f36bf2017-04-28 09:48:17 -070014022 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -070014023 u.createBluetoothUnoptimizedScanTimerLocked().readSummaryFromParcelLocked(in);
14024 }
14025 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -070014026 u.createBluetoothScanResultCounterLocked().readSummaryFromParcelLocked(in);
14027 }
Bookatzb1f04f32017-05-19 13:57:32 -070014028 if (in.readInt() != 0) {
14029 u.createBluetoothScanResultBgCounterLocked().readSummaryFromParcelLocked(in);
14030 }
Dianne Hackborna8d10942015-11-19 17:55:19 -080014031 u.mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -070014032 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
14033 if (in.readInt() != 0) {
14034 u.makeProcessState(i, null);
14035 u.mProcessStateTimer[i].readSummaryFromParcelLocked(in);
14036 }
14037 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014038 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014039 u.createVibratorOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014040 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070014041
Dianne Hackborn617f8772009-03-31 15:04:46 -070014042 if (in.readInt() != 0) {
14043 if (u.mUserActivityCounters == null) {
14044 u.initUserActivityLocked();
14045 }
14046 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
14047 u.mUserActivityCounters[i].readSummaryFromParcelLocked(in);
14048 }
14049 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014050
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014051 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014052 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014053 u.initNetworkActivityLocked();
14054 }
14055 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014056 u.mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
14057 u.mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014058 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080014059 u.mMobileRadioActiveTime.readSummaryFromParcelLocked(in);
14060 u.mMobileRadioActiveCount.readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014061 }
14062
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014063 u.mUserCpuTime.readSummaryFromParcelLocked(in);
14064 u.mSystemCpuTime.readSummaryFromParcelLocked(in);
14065
Adam Lesinski6832f392015-09-05 18:05:40 -070014066 if (in.readInt() != 0) {
14067 final int numClusters = in.readInt();
14068 if (mPowerProfile != null && mPowerProfile.getNumCpuClusters() != numClusters) {
14069 throw new ParcelFormatException("Incompatible cpu cluster arrangement");
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014070 }
Adam Lesinski6832f392015-09-05 18:05:40 -070014071
Sudheer Shankaaf857412017-07-21 00:14:24 -070014072 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -070014073 for (int cluster = 0; cluster < numClusters; cluster++) {
Adam Lesinski6832f392015-09-05 18:05:40 -070014074 if (in.readInt() != 0) {
Adam Lesinskia57a5402015-09-28 10:21:33 -070014075 final int NSB = in.readInt();
14076 if (mPowerProfile != null &&
14077 mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != NSB) {
14078 throw new ParcelFormatException("File corrupt: too many speed bins " +
14079 NSB);
14080 }
14081
Sudheer Shankaaf857412017-07-21 00:14:24 -070014082 u.mCpuClusterSpeedTimesUs[cluster] = new LongSamplingCounter[NSB];
Adam Lesinski6832f392015-09-05 18:05:40 -070014083 for (int speed = 0; speed < NSB; speed++) {
14084 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070014085 u.mCpuClusterSpeedTimesUs[cluster][speed] = new LongSamplingCounter(
Adam Lesinski6832f392015-09-05 18:05:40 -070014086 mOnBatteryTimeBase);
Sudheer Shankaaf857412017-07-21 00:14:24 -070014087 u.mCpuClusterSpeedTimesUs[cluster][speed].readSummaryFromParcelLocked(in);
Adam Lesinski6832f392015-09-05 18:05:40 -070014088 }
14089 }
Adam Lesinskia57a5402015-09-28 10:21:33 -070014090 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070014091 u.mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -070014092 }
14093 }
14094 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070014095 u.mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014096 }
14097
Sudheer Shanka59f5c002017-05-15 10:57:15 -070014098 u.mCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
14099 in, mOnBatteryTimeBase);
14100 u.mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
14101 in, mOnBatteryScreenOffTimeBase);
Mike Ma3d422c32017-10-25 11:08:57 -070014102
14103 u.mCpuActiveTimeMs.readSummaryFromParcelLocked(in);
14104 u.mCpuClusterTimesMs.readSummaryFromParcelLocked(in);
14105
Sudheer Shankab2f83c12017-11-13 19:25:01 -080014106 int length = in.readInt();
14107 if (length == Uid.NUM_PROCESS_STATE) {
14108 u.mProcStateTimeMs = new LongSamplingCounterArray[length];
14109 for (int procState = 0; procState < length; ++procState) {
14110 u.mProcStateTimeMs[procState]
14111 = LongSamplingCounterArray.readSummaryFromParcelLocked(
14112 in, mOnBatteryTimeBase);
14113 }
14114 } else {
14115 u.mProcStateTimeMs = null;
14116 }
14117 length = in.readInt();
14118 if (length == Uid.NUM_PROCESS_STATE) {
14119 u.mProcStateScreenOffTimeMs = new LongSamplingCounterArray[length];
14120 for (int procState = 0; procState < length; ++procState) {
14121 u.mProcStateScreenOffTimeMs[procState]
14122 = LongSamplingCounterArray.readSummaryFromParcelLocked(
14123 in, mOnBatteryScreenOffTimeBase);
14124 }
14125 } else {
14126 u.mProcStateScreenOffTimeMs = null;
14127 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070014128
14129 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -070014130 u.mMobileRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
14131 u.mMobileRadioApWakeupCount.readSummaryFromParcelLocked(in);
14132 } else {
14133 u.mMobileRadioApWakeupCount = null;
14134 }
14135
14136 if (in.readInt() != 0) {
14137 u.mWifiRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
14138 u.mWifiRadioApWakeupCount.readSummaryFromParcelLocked(in);
14139 } else {
14140 u.mWifiRadioApWakeupCount = null;
14141 }
14142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014143 int NW = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070014144 if (NW > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014145 throw new ParcelFormatException("File corrupt: too many wake locks " + NW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014146 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014147 for (int iw = 0; iw < NW; iw++) {
14148 String wlName = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014149 u.readWakeSummaryFromParcelLocked(wlName, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014150 }
14151
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014152 int NS = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070014153 if (NS > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014154 throw new ParcelFormatException("File corrupt: too many syncs " + NS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014155 }
14156 for (int is = 0; is < NS; is++) {
14157 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014158 u.readSyncSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014159 }
14160
14161 int NJ = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070014162 if (NJ > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014163 throw new ParcelFormatException("File corrupt: too many job timers " + NJ);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014164 }
14165 for (int ij = 0; ij < NJ; ij++) {
14166 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014167 u.readJobSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014168 }
14169
Dianne Hackborn94326cb2017-06-28 16:17:20 -070014170 u.readJobCompletionsFromParcelLocked(in);
14171
Amith Yamasani977e11f2018-02-16 11:29:54 -080014172 u.mJobsDeferredEventCount.readSummaryFromParcelLocked(in);
14173 u.mJobsDeferredCount.readSummaryFromParcelLocked(in);
14174 u.mJobsFreshnessTimeMs.readSummaryFromParcelLocked(in);
14175 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
14176 if (in.readInt() != 0) {
14177 u.mJobsFreshnessBuckets[i] = new Counter(u.mBsi.mOnBatteryTimeBase);
14178 u.mJobsFreshnessBuckets[i].readSummaryFromParcelLocked(in);
14179 }
14180 }
14181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014182 int NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014183 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014184 throw new ParcelFormatException("File corrupt: too many sensors " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014185 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014186 for (int is = 0; is < NP; is++) {
14187 int seNumber = in.readInt();
14188 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -080014189 u.getSensorTimerLocked(seNumber, true).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014190 }
14191 }
14192
14193 NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014194 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014195 throw new ParcelFormatException("File corrupt: too many processes " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014197 for (int ip = 0; ip < NP; ip++) {
14198 String procName = in.readString();
14199 Uid.Proc p = u.getProcessStatsLocked(procName);
14200 p.mUserTime = p.mLoadedUserTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014201 p.mSystemTime = p.mLoadedSystemTime = in.readLong();
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014202 p.mForegroundTime = p.mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014203 p.mStarts = p.mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014204 p.mNumCrashes = p.mLoadedNumCrashes = in.readInt();
14205 p.mNumAnrs = p.mLoadedNumAnrs = in.readInt();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014206 p.readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014207 }
14208
14209 NP = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014210 if (NP > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014211 throw new ParcelFormatException("File corrupt: too many packages " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014212 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014213 for (int ip = 0; ip < NP; ip++) {
14214 String pkgName = in.readString();
14215 Uid.Pkg p = u.getPackageStatsLocked(pkgName);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014216 final int NWA = in.readInt();
14217 if (NWA > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014218 throw new ParcelFormatException("File corrupt: too many wakeup alarms " + NWA);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014219 }
14220 p.mWakeupAlarms.clear();
14221 for (int iwa=0; iwa<NWA; iwa++) {
14222 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -070014223 Counter c = new Counter(mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014224 c.readSummaryFromParcelLocked(in);
14225 p.mWakeupAlarms.put(tag, c);
14226 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014227 NS = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014228 if (NS > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014229 throw new ParcelFormatException("File corrupt: too many services " + NS);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014230 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014231 for (int is = 0; is < NS; is++) {
14232 String servName = in.readString();
14233 Uid.Pkg.Serv s = u.getServiceStatsLocked(pkgName, servName);
14234 s.mStartTime = s.mLoadedStartTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014235 s.mStarts = s.mLoadedStarts = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014236 s.mLaunches = s.mLoadedLaunches = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014237 }
14238 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014239 }
14240 }
14241
14242 /**
14243 * Writes a summary of the statistics to a Parcel, in a format suitable to be written to
14244 * disk. This format does not allow a lossless round-trip.
14245 *
14246 * @param out the Parcel to be written to.
14247 */
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070014248 public void writeSummaryToParcel(Parcel out, boolean inclHistory) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080014249 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014250
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014251 // Pull the clock time. This may update the time and make a new history entry
14252 // if we had originally pulled a time before the RTC was set.
14253 long startClockTime = getStartClockTime();
14254
Joe Onoratoabded112016-02-08 16:49:39 -080014255 final long NOW_SYS = mClocks.uptimeMillis() * 1000;
14256 final long NOWREAL_SYS = mClocks.elapsedRealtime() * 1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014257
14258 out.writeInt(VERSION);
14259
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070014260 writeHistory(out, inclHistory, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014261
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014262 out.writeInt(mStartCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014263 out.writeLong(computeUptime(NOW_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014264 out.writeLong(computeRealtime(NOWREAL_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014265 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014266 out.writeString(mStartPlatformVersion);
14267 out.writeString(mEndPlatformVersion);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014268 mOnBatteryTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
14269 mOnBatteryScreenOffTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014270 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014271 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070014272 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014273 out.writeInt(mCurrentBatteryLevel);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014274 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070014275 out.writeInt(mMinLearnedBatteryCapacity);
14276 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborne4a59512010-12-07 11:08:07 -080014277 out.writeInt(getLowDischargeAmountSinceCharge());
14278 out.writeInt(getHighDischargeAmountSinceCharge());
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014279 out.writeInt(getDischargeAmountScreenOnSinceCharge());
14280 out.writeInt(getDischargeAmountScreenOffSinceCharge());
Mike Mac2f518a2017-09-19 16:06:03 -070014281 out.writeInt(getDischargeAmountScreenDozeSinceCharge());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014282 mDischargeStepTracker.writeToParcel(out);
14283 mChargeStepTracker.writeToParcel(out);
14284 mDailyDischargeStepTracker.writeToParcel(out);
14285 mDailyChargeStepTracker.writeToParcel(out);
Adam Lesinski67c134f2016-06-10 15:15:08 -070014286 mDischargeCounter.writeSummaryFromParcelLocked(out);
14287 mDischargeScreenOffCounter.writeSummaryFromParcelLocked(out);
Mike Mac2f518a2017-09-19 16:06:03 -070014288 mDischargeScreenDozeCounter.writeSummaryFromParcelLocked(out);
Mike Ma15313c92017-11-15 17:58:21 -080014289 mDischargeLightDozeCounter.writeSummaryFromParcelLocked(out);
14290 mDischargeDeepDozeCounter.writeSummaryFromParcelLocked(out);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014291 if (mDailyPackageChanges != null) {
14292 final int NPKG = mDailyPackageChanges.size();
14293 out.writeInt(NPKG);
14294 for (int i=0; i<NPKG; i++) {
14295 PackageChange pc = mDailyPackageChanges.get(i);
14296 out.writeString(pc.mPackageName);
14297 out.writeInt(pc.mUpdate ? 1 : 0);
Dianne Hackborn3accca02013-09-20 09:32:11 -070014298 out.writeLong(pc.mVersionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014299 }
14300 } else {
14301 out.writeInt(0);
14302 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014303 out.writeLong(mDailyStartTime);
14304 out.writeLong(mNextMinDailyDeadline);
14305 out.writeLong(mNextMaxDailyDeadline);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014306
14307 mScreenOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Mike Mac2f518a2017-09-19 16:06:03 -070014308 mScreenDozeTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070014309 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014310 mScreenBrightnessTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070014311 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070014312 mInteractiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070014313 mPowerSaveModeEnabledTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014314 out.writeLong(mLongestLightIdleTime);
14315 out.writeLong(mLongestFullIdleTime);
14316 mDeviceIdleModeLightTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14317 mDeviceIdleModeFullTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14318 mDeviceLightIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014319 mDeviceIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014320 mPhoneOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Wink Saville52840902011-02-18 12:40:47 -080014321 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014322 mPhoneSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070014323 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014324 mPhoneSignalScanningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070014325 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014326 mPhoneDataConnectionsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070014327 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014328 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014329 mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
14330 mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014331 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014332 mMobileRadioActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14333 mMobileRadioActivePerAppTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014334 mMobileRadioActiveAdjustedTime.writeSummaryFromParcelLocked(out);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080014335 mMobileRadioActiveUnknownTime.writeSummaryFromParcelLocked(out);
14336 mMobileRadioActiveUnknownCount.writeSummaryFromParcelLocked(out);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014337 mWifiMulticastWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014338 mWifiOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14339 mGlobalWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080014340 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014341 mWifiStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080014342 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014343 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
14344 mWifiSupplStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14345 }
14346 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
14347 mWifiSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14348 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014349 mWifiActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14350 mWifiActivity.writeSummaryToParcel(out);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014351 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14352 mGpsSignalQualityTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14353 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014354 mBluetoothActivity.writeSummaryToParcel(out);
14355 mModemActivity.writeSummaryToParcel(out);
14356 out.writeInt(mHasWifiReporting ? 1 : 0);
14357 out.writeInt(mHasBluetoothReporting ? 1 : 0);
14358 out.writeInt(mHasModemReporting ? 1 : 0);
14359
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014360 out.writeInt(mNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070014361 mFlashlightOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014362 mCameraOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014363 mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014364
Bookatz50df7112017-08-04 14:53:26 -070014365 out.writeInt(mRpmStats.size());
14366 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
14367 Timer rpmt = ent.getValue();
14368 if (rpmt != null) {
14369 out.writeInt(1);
14370 out.writeString(ent.getKey());
14371 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14372 } else {
14373 out.writeInt(0);
14374 }
14375 }
14376 out.writeInt(mScreenOffRpmStats.size());
14377 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
14378 Timer rpmt = ent.getValue();
14379 if (rpmt != null) {
14380 out.writeInt(1);
14381 out.writeString(ent.getKey());
14382 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14383 } else {
14384 out.writeInt(0);
14385 }
14386 }
14387
Evan Millarc64edde2009-04-18 12:26:32 -070014388 out.writeInt(mKernelWakelockStats.size());
14389 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
14390 Timer kwlt = ent.getValue();
14391 if (kwlt != null) {
14392 out.writeInt(1);
14393 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014394 kwlt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14395 } else {
14396 out.writeInt(0);
14397 }
14398 }
14399
14400 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014401 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
14402 SamplingTimer timer = ent.getValue();
14403 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014404 out.writeInt(1);
14405 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014406 timer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Evan Millarc64edde2009-04-18 12:26:32 -070014407 } else {
14408 out.writeInt(0);
14409 }
14410 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014411
James Carr3a226052016-07-01 14:49:52 -070014412 out.writeInt(mKernelMemoryStats.size());
14413 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
14414 Timer kmt = mKernelMemoryStats.valueAt(i);
14415 if (kmt != null) {
14416 out.writeInt(1);
14417 out.writeLong(mKernelMemoryStats.keyAt(i));
14418 kmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14419 } else {
14420 out.writeInt(0);
14421 }
14422 }
14423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014424 final int NU = mUidStats.size();
14425 out.writeInt(NU);
14426 for (int iu = 0; iu < NU; iu++) {
14427 out.writeInt(mUidStats.keyAt(iu));
14428 Uid u = mUidStats.valueAt(iu);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014429
Bookatz867c0d72017-03-07 18:23:42 -080014430 u.mOnBatteryBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatzc8c44962017-05-11 12:12:54 -070014431 u.mOnBatteryScreenOffBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatz867c0d72017-03-07 18:23:42 -080014432
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014433 if (u.mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014434 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014435 u.mWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014436 } else {
14437 out.writeInt(0);
14438 }
14439 if (u.mFullWifiLockTimer != null) {
14440 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014441 u.mFullWifiLockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014442 } else {
14443 out.writeInt(0);
14444 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070014445 if (u.mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014446 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014447 u.mWifiScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014448 } else {
14449 out.writeInt(0);
14450 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070014451 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
14452 if (u.mWifiBatchedScanTimer[i] != null) {
14453 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014454 u.mWifiBatchedScanTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Robert Greenwalta029ea12013-09-25 16:38:12 -070014455 } else {
14456 out.writeInt(0);
14457 }
14458 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014459 if (u.mWifiMulticastTimer != null) {
14460 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014461 u.mWifiMulticastTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014462 } else {
14463 out.writeInt(0);
14464 }
14465 if (u.mAudioTurnedOnTimer != null) {
14466 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014467 u.mAudioTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014468 } else {
14469 out.writeInt(0);
14470 }
14471 if (u.mVideoTurnedOnTimer != null) {
14472 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014473 u.mVideoTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014474 } else {
14475 out.writeInt(0);
14476 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014477 if (u.mFlashlightTurnedOnTimer != null) {
14478 out.writeInt(1);
14479 u.mFlashlightTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14480 } else {
14481 out.writeInt(0);
14482 }
14483 if (u.mCameraTurnedOnTimer != null) {
14484 out.writeInt(1);
14485 u.mCameraTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14486 } else {
14487 out.writeInt(0);
14488 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014489 if (u.mForegroundActivityTimer != null) {
14490 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014491 u.mForegroundActivityTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014492 } else {
14493 out.writeInt(0);
14494 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070014495 if (u.mForegroundServiceTimer != null) {
14496 out.writeInt(1);
14497 u.mForegroundServiceTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14498 } else {
14499 out.writeInt(0);
14500 }
Bookatzc8c44962017-05-11 12:12:54 -070014501 if (u.mAggregatedPartialWakelockTimer != null) {
14502 out.writeInt(1);
14503 u.mAggregatedPartialWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14504 } else {
14505 out.writeInt(0);
14506 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014507 if (u.mBluetoothScanTimer != null) {
14508 out.writeInt(1);
14509 u.mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14510 } else {
14511 out.writeInt(0);
14512 }
Bookatzb1f04f32017-05-19 13:57:32 -070014513 if (u.mBluetoothUnoptimizedScanTimer != null) {
14514 out.writeInt(1);
14515 u.mBluetoothUnoptimizedScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14516 } else {
14517 out.writeInt(0);
14518 }
Bookatz956f36bf2017-04-28 09:48:17 -070014519 if (u.mBluetoothScanResultCounter != null) {
14520 out.writeInt(1);
14521 u.mBluetoothScanResultCounter.writeSummaryFromParcelLocked(out);
14522 } else {
14523 out.writeInt(0);
14524 }
Bookatzb1f04f32017-05-19 13:57:32 -070014525 if (u.mBluetoothScanResultBgCounter != null) {
14526 out.writeInt(1);
14527 u.mBluetoothScanResultBgCounter.writeSummaryFromParcelLocked(out);
14528 } else {
14529 out.writeInt(0);
14530 }
Dianne Hackborn61659e52014-07-09 16:13:01 -070014531 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
14532 if (u.mProcessStateTimer[i] != null) {
14533 out.writeInt(1);
14534 u.mProcessStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14535 } else {
14536 out.writeInt(0);
14537 }
14538 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014539 if (u.mVibratorOnTimer != null) {
14540 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014541 u.mVibratorOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014542 } else {
14543 out.writeInt(0);
14544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014545
Dianne Hackborn617f8772009-03-31 15:04:46 -070014546 if (u.mUserActivityCounters == null) {
14547 out.writeInt(0);
14548 } else {
14549 out.writeInt(1);
14550 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
14551 u.mUserActivityCounters[i].writeSummaryFromParcelLocked(out);
14552 }
14553 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014554
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014555 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014556 out.writeInt(0);
14557 } else {
14558 out.writeInt(1);
14559 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014560 u.mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
14561 u.mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014562 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080014563 u.mMobileRadioActiveTime.writeSummaryFromParcelLocked(out);
14564 u.mMobileRadioActiveCount.writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014565 }
14566
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014567 u.mUserCpuTime.writeSummaryFromParcelLocked(out);
14568 u.mSystemCpuTime.writeSummaryFromParcelLocked(out);
14569
Sudheer Shankaaf857412017-07-21 00:14:24 -070014570 if (u.mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -070014571 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -070014572 out.writeInt(u.mCpuClusterSpeedTimesUs.length);
14573 for (LongSamplingCounter[] cpuSpeeds : u.mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -070014574 if (cpuSpeeds != null) {
14575 out.writeInt(1);
14576 out.writeInt(cpuSpeeds.length);
14577 for (LongSamplingCounter c : cpuSpeeds) {
14578 if (c != null) {
14579 out.writeInt(1);
14580 c.writeSummaryFromParcelLocked(out);
14581 } else {
14582 out.writeInt(0);
14583 }
14584 }
14585 } else {
14586 out.writeInt(0);
14587 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014588 }
Adam Lesinski6832f392015-09-05 18:05:40 -070014589 } else {
14590 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014591 }
14592
Sudheer Shanka59f5c002017-05-15 10:57:15 -070014593 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mCpuFreqTimeMs);
14594 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mScreenOffCpuFreqTimeMs);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070014595
Mike Ma3d422c32017-10-25 11:08:57 -070014596 u.mCpuActiveTimeMs.writeSummaryFromParcelLocked(out);
14597 u.mCpuClusterTimesMs.writeSummaryToParcelLocked(out);
14598
Sudheer Shankab2f83c12017-11-13 19:25:01 -080014599 if (u.mProcStateTimeMs != null) {
14600 out.writeInt(u.mProcStateTimeMs.length);
14601 for (LongSamplingCounterArray counters : u.mProcStateTimeMs) {
14602 LongSamplingCounterArray.writeSummaryToParcelLocked(out, counters);
14603 }
14604 } else {
14605 out.writeInt(0);
14606 }
14607 if (u.mProcStateScreenOffTimeMs != null) {
14608 out.writeInt(u.mProcStateScreenOffTimeMs.length);
14609 for (LongSamplingCounterArray counters : u.mProcStateScreenOffTimeMs) {
14610 LongSamplingCounterArray.writeSummaryToParcelLocked(out, counters);
14611 }
14612 } else {
14613 out.writeInt(0);
14614 }
14615
Adam Lesinski5f056f62016-07-14 16:56:08 -070014616 if (u.mMobileRadioApWakeupCount != null) {
14617 out.writeInt(1);
14618 u.mMobileRadioApWakeupCount.writeSummaryFromParcelLocked(out);
14619 } else {
14620 out.writeInt(0);
14621 }
14622
14623 if (u.mWifiRadioApWakeupCount != null) {
14624 out.writeInt(1);
14625 u.mWifiRadioApWakeupCount.writeSummaryFromParcelLocked(out);
14626 } else {
14627 out.writeInt(0);
14628 }
14629
Dianne Hackbornd953c532014-08-16 18:17:38 -070014630 final ArrayMap<String, Uid.Wakelock> wakeStats = u.mWakelockStats.getMap();
14631 int NW = wakeStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014632 out.writeInt(NW);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014633 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014634 out.writeString(wakeStats.keyAt(iw));
14635 Uid.Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014636 if (wl.mTimerFull != null) {
14637 out.writeInt(1);
14638 wl.mTimerFull.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14639 } else {
14640 out.writeInt(0);
14641 }
14642 if (wl.mTimerPartial != null) {
14643 out.writeInt(1);
14644 wl.mTimerPartial.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14645 } else {
14646 out.writeInt(0);
14647 }
14648 if (wl.mTimerWindow != null) {
14649 out.writeInt(1);
14650 wl.mTimerWindow.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14651 } else {
14652 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014653 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070014654 if (wl.mTimerDraw != null) {
Adam Lesinski9425fe22015-06-19 12:02:13 -070014655 out.writeInt(1);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070014656 wl.mTimerDraw.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9425fe22015-06-19 12:02:13 -070014657 } else {
14658 out.writeInt(0);
14659 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014660 }
14661
Bookatz2bffb5b2017-04-13 11:59:33 -070014662 final ArrayMap<String, DualTimer> syncStats = u.mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014663 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014664 out.writeInt(NS);
14665 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014666 out.writeString(syncStats.keyAt(is));
14667 syncStats.valueAt(is).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014668 }
14669
Bookatzaa4594a2017-03-24 12:39:56 -070014670 final ArrayMap<String, DualTimer> jobStats = u.mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014671 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014672 out.writeInt(NJ);
14673 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014674 out.writeString(jobStats.keyAt(ij));
14675 jobStats.valueAt(ij).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014676 }
14677
Dianne Hackborn94326cb2017-06-28 16:17:20 -070014678 u.writeJobCompletionsToParcelLocked(out);
14679
Amith Yamasani977e11f2018-02-16 11:29:54 -080014680 u.mJobsDeferredEventCount.writeSummaryFromParcelLocked(out);
14681 u.mJobsDeferredCount.writeSummaryFromParcelLocked(out);
14682 u.mJobsFreshnessTimeMs.writeSummaryFromParcelLocked(out);
14683 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
14684 if (u.mJobsFreshnessBuckets[i] != null) {
Adam Lesinski14082082018-02-23 12:35:55 -080014685 out.writeInt(1);
Amith Yamasani977e11f2018-02-16 11:29:54 -080014686 u.mJobsFreshnessBuckets[i].writeSummaryFromParcelLocked(out);
14687 } else {
14688 out.writeInt(0);
14689 }
14690 }
14691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014692 int NSE = u.mSensorStats.size();
14693 out.writeInt(NSE);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014694 for (int ise=0; ise<NSE; ise++) {
14695 out.writeInt(u.mSensorStats.keyAt(ise));
14696 Uid.Sensor se = u.mSensorStats.valueAt(ise);
14697 if (se.mTimer != null) {
14698 out.writeInt(1);
14699 se.mTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14700 } else {
14701 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014702 }
14703 }
14704
14705 int NP = u.mProcessStats.size();
14706 out.writeInt(NP);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014707 for (int ip=0; ip<NP; ip++) {
14708 out.writeString(u.mProcessStats.keyAt(ip));
14709 Uid.Proc ps = u.mProcessStats.valueAt(ip);
14710 out.writeLong(ps.mUserTime);
14711 out.writeLong(ps.mSystemTime);
14712 out.writeLong(ps.mForegroundTime);
14713 out.writeInt(ps.mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014714 out.writeInt(ps.mNumCrashes);
14715 out.writeInt(ps.mNumAnrs);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014716 ps.writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014717 }
14718
14719 NP = u.mPackageStats.size();
14720 out.writeInt(NP);
14721 if (NP > 0) {
14722 for (Map.Entry<String, BatteryStatsImpl.Uid.Pkg> ent
14723 : u.mPackageStats.entrySet()) {
14724 out.writeString(ent.getKey());
14725 Uid.Pkg ps = ent.getValue();
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014726 final int NWA = ps.mWakeupAlarms.size();
14727 out.writeInt(NWA);
14728 for (int iwa=0; iwa<NWA; iwa++) {
14729 out.writeString(ps.mWakeupAlarms.keyAt(iwa));
14730 ps.mWakeupAlarms.valueAt(iwa).writeSummaryFromParcelLocked(out);
14731 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014732 NS = ps.mServiceStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014733 out.writeInt(NS);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014734 for (int is=0; is<NS; is++) {
14735 out.writeString(ps.mServiceStats.keyAt(is));
14736 BatteryStatsImpl.Uid.Pkg.Serv ss = ps.mServiceStats.valueAt(is);
14737 long time = ss.getStartTimeToNowLocked(
14738 mOnBatteryTimeBase.getUptime(NOW_SYS));
14739 out.writeLong(time);
14740 out.writeInt(ss.mStarts);
14741 out.writeInt(ss.mLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014742 }
14743 }
14744 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014745 }
14746 }
14747
14748 public void readFromParcel(Parcel in) {
14749 readFromParcelLocked(in);
14750 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014752 void readFromParcelLocked(Parcel in) {
14753 int magic = in.readInt();
14754 if (magic != MAGIC) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014755 throw new ParcelFormatException("Bad magic number: #" + Integer.toHexString(magic));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014756 }
14757
Dianne Hackbornae384452011-06-28 12:33:48 -070014758 readHistory(in, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014760 mStartCount = in.readInt();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080014761 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014762 mStartPlatformVersion = in.readString();
14763 mEndPlatformVersion = in.readString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014764 mUptime = in.readLong();
14765 mUptimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014766 mRealtime = in.readLong();
14767 mRealtimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014768 mOnBattery = in.readInt() != 0;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014769 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070014770 mMinLearnedBatteryCapacity = in.readInt();
14771 mMaxLearnedBatteryCapacity = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014772 mOnBatteryInternal = false; // we are no longer really running.
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014773 mOnBatteryTimeBase.readFromParcel(in);
14774 mOnBatteryScreenOffTimeBase.readFromParcel(in);
14775
Jeff Browne95c3cd2014-05-02 16:59:26 -070014776 mScreenState = Display.STATE_UNKNOWN;
Joe Onoratoabded112016-02-08 16:49:39 -080014777 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070014778 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014779 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014780 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
14781 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014782 }
Dianne Hackborn29325132014-05-21 15:01:03 -070014783 mInteractive = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014784 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014785 mPhoneOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014786 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
14787 mOnBatteryTimeBase, in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014788 mLongestLightIdleTime = in.readLong();
14789 mLongestFullIdleTime = in.readLong();
Joe Onoratoabded112016-02-08 16:49:39 -080014790 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -14, null,
14791 mOnBatteryTimeBase, in);
14792 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -11, null,
14793 mOnBatteryTimeBase, in);
14794 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null,
14795 mOnBatteryTimeBase, in);
14796 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase, in);
14797 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014798 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014799 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014800 null, mOnBatteryTimeBase, in);
14801 }
Joe Onoratoabded112016-02-08 16:49:39 -080014802 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
14803 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014804 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014805 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014806 null, mOnBatteryTimeBase, in);
14807 }
14808 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
14809 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
14810 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
14811 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014812 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Joe Onoratoabded112016-02-08 16:49:39 -080014813 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null,
14814 mOnBatteryTimeBase, in);
Kweku Adams87b19ec2017-10-09 12:40:03 -070014815 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
Joe Onoratoabded112016-02-08 16:49:39 -080014816 mOnBatteryTimeBase, in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014817 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014818 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
14819 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase, in);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014820 mWifiMulticastWakelockTimer = new StopwatchTimer(mClocks, null, -4, null,
14821 mOnBatteryTimeBase, in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070014822 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014823 mWifiOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014824 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014825 mGlobalWifiRunning = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014826 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null,
14827 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014828 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014829 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014830 null, mOnBatteryTimeBase, in);
14831 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014832 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014833 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070014834 null, mOnBatteryTimeBase, in);
14835 }
14836 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014837 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070014838 null, mOnBatteryTimeBase, in);
14839 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014840 mWifiActiveTimer = new StopwatchTimer(mClocks, null, -900, null,
14841 mOnBatteryTimeBase, in);
14842 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14843 NUM_WIFI_TX_LEVELS, in);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014844 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14845 mGpsSignalQualityTimer[i] = new StopwatchTimer(mClocks, null, -1000-i,
14846 null, mOnBatteryTimeBase, in);
14847 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014848 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14849 NUM_BT_TX_LEVELS, in);
14850 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14851 ModemActivityInfo.TX_POWER_LEVELS, in);
14852 mHasWifiReporting = in.readInt() != 0;
14853 mHasBluetoothReporting = in.readInt() != 0;
14854 mHasModemReporting = in.readInt() != 0;
14855
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014856 mNumConnectivityChange = in.readInt();
14857 mLoadedNumConnectivityChange = in.readInt();
14858 mUnpluggedNumConnectivityChange = in.readInt();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014859 mAudioOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014860 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014861 mVideoOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014862 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014863 mFlashlightOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014864 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014865 mCameraOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014866 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014867 mBluetoothScanNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014868 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase, in);
Siddharth Rayf5e796a2018-01-22 18:18:17 -080014869 mIsCellularTxPowerHigh = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014870 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014871 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070014872 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014873 mCurrentBatteryLevel = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014874 mLowDischargeAmountSinceCharge = in.readInt();
14875 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014876 mDischargeAmountScreenOn = in.readInt();
14877 mDischargeAmountScreenOnSinceCharge = in.readInt();
14878 mDischargeAmountScreenOff = in.readInt();
14879 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070014880 mDischargeAmountScreenDoze = in.readInt();
14881 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014882 mDischargeStepTracker.readFromParcel(in);
14883 mChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070014884 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070014885 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase, in);
14886 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Ma15313c92017-11-15 17:58:21 -080014887 mDischargeLightDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
14888 mDischargeDeepDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014889 mLastWriteTime = in.readLong();
14890
Bookatz50df7112017-08-04 14:53:26 -070014891 mRpmStats.clear();
14892 int NRPMS = in.readInt();
14893 for (int irpm = 0; irpm < NRPMS; irpm++) {
14894 if (in.readInt() != 0) {
14895 String rpmName = in.readString();
14896 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
14897 mRpmStats.put(rpmName, rpmt);
14898 }
14899 }
14900 mScreenOffRpmStats.clear();
14901 int NSORPMS = in.readInt();
14902 for (int irpm = 0; irpm < NSORPMS; irpm++) {
14903 if (in.readInt() != 0) {
14904 String rpmName = in.readString();
14905 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
14906 mScreenOffRpmStats.put(rpmName, rpmt);
14907 }
14908 }
14909
Evan Millarc64edde2009-04-18 12:26:32 -070014910 mKernelWakelockStats.clear();
14911 int NKW = in.readInt();
14912 for (int ikw = 0; ikw < NKW; ikw++) {
14913 if (in.readInt() != 0) {
14914 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080014915 SamplingTimer kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -070014916 mKernelWakelockStats.put(wakelockName, kwlt);
14917 }
14918 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014919
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014920 mWakeupReasonStats.clear();
14921 int NWR = in.readInt();
14922 for (int iwr = 0; iwr < NWR; iwr++) {
14923 if (in.readInt() != 0) {
14924 String reasonName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080014925 SamplingTimer timer = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014926 mWakeupReasonStats.put(reasonName, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014927 }
14928 }
14929
James Carr3a226052016-07-01 14:49:52 -070014930 mKernelMemoryStats.clear();
14931 int nmt = in.readInt();
14932 for (int imt = 0; imt < nmt; imt++) {
14933 if (in.readInt() != 0) {
14934 Long bucket = in.readLong();
14935 SamplingTimer kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
14936 mKernelMemoryStats.put(bucket, kmt);
14937 }
14938 }
14939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014940 mPartialTimers.clear();
14941 mFullTimers.clear();
14942 mWindowTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014943 mWifiRunningTimers.clear();
14944 mFullWifiLockTimers.clear();
Nick Pelly6ccaa542012-06-15 15:22:47 -070014945 mWifiScanTimers.clear();
Robert Greenwalta029ea12013-09-25 16:38:12 -070014946 mWifiBatchedScanTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014947 mWifiMulticastTimers.clear();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014948 mAudioTurnedOnTimers.clear();
14949 mVideoTurnedOnTimers.clear();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014950 mFlashlightTurnedOnTimers.clear();
14951 mCameraTurnedOnTimers.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014952
14953 int numUids = in.readInt();
14954 mUidStats.clear();
14955 for (int i = 0; i < numUids; i++) {
14956 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080014957 Uid u = new Uid(this, uid);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014958 u.readFromParcelLocked(mOnBatteryTimeBase, mOnBatteryScreenOffTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014959 mUidStats.append(uid, u);
14960 }
14961 }
14962
14963 public void writeToParcel(Parcel out, int flags) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014964 writeToParcelLocked(out, true, flags);
14965 }
14966
14967 public void writeToParcelWithoutUids(Parcel out, int flags) {
14968 writeToParcelLocked(out, false, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014969 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014970
14971 @SuppressWarnings("unused")
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014972 void writeToParcelLocked(Parcel out, boolean inclUids, int flags) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014973 // Need to update with current kernel wake lock counts.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080014974 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014975
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014976 // Pull the clock time. This may update the time and make a new history entry
14977 // if we had originally pulled a time before the RTC was set.
14978 long startClockTime = getStartClockTime();
14979
Joe Onoratoabded112016-02-08 16:49:39 -080014980 final long uSecUptime = mClocks.uptimeMillis() * 1000;
14981 final long uSecRealtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014982 final long batteryRealtime = mOnBatteryTimeBase.getRealtime(uSecRealtime);
14983 final long batteryScreenOffRealtime = mOnBatteryScreenOffTimeBase.getRealtime(uSecRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014984
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014985 out.writeInt(MAGIC);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014986
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070014987 writeHistory(out, true, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014988
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014989 out.writeInt(mStartCount);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014990 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014991 out.writeString(mStartPlatformVersion);
14992 out.writeString(mEndPlatformVersion);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014993 out.writeLong(mUptime);
14994 out.writeLong(mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014995 out.writeLong(mRealtime);
14996 out.writeLong(mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014997 out.writeInt(mOnBattery ? 1 : 0);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014998 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070014999 out.writeInt(mMinLearnedBatteryCapacity);
15000 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080015001 mOnBatteryTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
15002 mOnBatteryScreenOffTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
15003
15004 mScreenOnTimer.writeToParcel(out, uSecRealtime);
Mike Mac2f518a2017-09-19 16:06:03 -070015005 mScreenDozeTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080015006 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
15007 mScreenBrightnessTimer[i].writeToParcel(out, uSecRealtime);
15008 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070015009 mInteractiveTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070015010 mPowerSaveModeEnabledTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070015011 out.writeLong(mLongestLightIdleTime);
15012 out.writeLong(mLongestFullIdleTime);
15013 mDeviceIdleModeLightTimer.writeToParcel(out, uSecRealtime);
15014 mDeviceIdleModeFullTimer.writeToParcel(out, uSecRealtime);
15015 mDeviceLightIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070015016 mDeviceIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080015017 mPhoneOnTimer.writeToParcel(out, uSecRealtime);
15018 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
15019 mPhoneSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
15020 }
15021 mPhoneSignalScanningTimer.writeToParcel(out, uSecRealtime);
15022 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
15023 mPhoneDataConnectionsTimer[i].writeToParcel(out, uSecRealtime);
15024 }
15025 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
15026 mNetworkByteActivityCounters[i].writeToParcel(out);
15027 mNetworkPacketActivityCounters[i].writeToParcel(out);
15028 }
15029 mMobileRadioActiveTimer.writeToParcel(out, uSecRealtime);
15030 mMobileRadioActivePerAppTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070015031 mMobileRadioActiveAdjustedTime.writeToParcel(out);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080015032 mMobileRadioActiveUnknownTime.writeToParcel(out);
15033 mMobileRadioActiveUnknownCount.writeToParcel(out);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080015034 mWifiMulticastWakelockTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080015035 mWifiOnTimer.writeToParcel(out, uSecRealtime);
15036 mGlobalWifiRunningTimer.writeToParcel(out, uSecRealtime);
15037 for (int i=0; i<NUM_WIFI_STATES; i++) {
15038 mWifiStateTimer[i].writeToParcel(out, uSecRealtime);
15039 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070015040 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
15041 mWifiSupplStateTimer[i].writeToParcel(out, uSecRealtime);
15042 }
15043 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
15044 mWifiSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
15045 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080015046 mWifiActiveTimer.writeToParcel(out, uSecRealtime);
15047 mWifiActivity.writeToParcel(out, 0);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080015048 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
15049 mGpsSignalQualityTimer[i].writeToParcel(out, uSecRealtime);
15050 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080015051 mBluetoothActivity.writeToParcel(out, 0);
15052 mModemActivity.writeToParcel(out, 0);
15053 out.writeInt(mHasWifiReporting ? 1 : 0);
15054 out.writeInt(mHasBluetoothReporting ? 1 : 0);
15055 out.writeInt(mHasModemReporting ? 1 : 0);
15056
Dianne Hackborn1e01d162014-12-04 17:46:42 -080015057 out.writeInt(mNumConnectivityChange);
15058 out.writeInt(mLoadedNumConnectivityChange);
15059 out.writeInt(mUnpluggedNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070015060 mFlashlightOnTimer.writeToParcel(out, uSecRealtime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070015061 mCameraOnTimer.writeToParcel(out, uSecRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080015062 mBluetoothScanTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070015063 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070015064 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070015065 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070015066 out.writeInt(mCurrentBatteryLevel);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015067 out.writeInt(mLowDischargeAmountSinceCharge);
15068 out.writeInt(mHighDischargeAmountSinceCharge);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080015069 out.writeInt(mDischargeAmountScreenOn);
15070 out.writeInt(mDischargeAmountScreenOnSinceCharge);
15071 out.writeInt(mDischargeAmountScreenOff);
15072 out.writeInt(mDischargeAmountScreenOffSinceCharge);
Mike Mac2f518a2017-09-19 16:06:03 -070015073 out.writeInt(mDischargeAmountScreenDoze);
15074 out.writeInt(mDischargeAmountScreenDozeSinceCharge);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080015075 mDischargeStepTracker.writeToParcel(out);
15076 mChargeStepTracker.writeToParcel(out);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070015077 mDischargeCounter.writeToParcel(out);
15078 mDischargeScreenOffCounter.writeToParcel(out);
Mike Mac2f518a2017-09-19 16:06:03 -070015079 mDischargeScreenDozeCounter.writeToParcel(out);
Mike Ma15313c92017-11-15 17:58:21 -080015080 mDischargeLightDozeCounter.writeToParcel(out);
15081 mDischargeDeepDozeCounter.writeToParcel(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015082 out.writeLong(mLastWriteTime);
15083
Bookatz50df7112017-08-04 14:53:26 -070015084 out.writeInt(mRpmStats.size());
15085 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
15086 SamplingTimer rpmt = ent.getValue();
15087 if (rpmt != null) {
15088 out.writeInt(1);
15089 out.writeString(ent.getKey());
15090 rpmt.writeToParcel(out, uSecRealtime);
15091 } else {
15092 out.writeInt(0);
15093 }
15094 }
15095 out.writeInt(mScreenOffRpmStats.size());
15096 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
15097 SamplingTimer rpmt = ent.getValue();
15098 if (rpmt != null) {
15099 out.writeInt(1);
15100 out.writeString(ent.getKey());
15101 rpmt.writeToParcel(out, uSecRealtime);
15102 } else {
15103 out.writeInt(0);
15104 }
15105 }
15106
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015107 if (inclUids) {
15108 out.writeInt(mKernelWakelockStats.size());
15109 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
15110 SamplingTimer kwlt = ent.getValue();
15111 if (kwlt != null) {
15112 out.writeInt(1);
15113 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070015114 kwlt.writeToParcel(out, uSecRealtime);
15115 } else {
15116 out.writeInt(0);
15117 }
15118 }
15119 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070015120 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
15121 SamplingTimer timer = ent.getValue();
15122 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070015123 out.writeInt(1);
15124 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070015125 timer.writeToParcel(out, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015126 } else {
15127 out.writeInt(0);
15128 }
Evan Millarc64edde2009-04-18 12:26:32 -070015129 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015130 } else {
Bookatzba78b2b2017-10-10 11:06:33 -070015131 out.writeInt(0);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015132 out.writeInt(0);
Evan Millarc64edde2009-04-18 12:26:32 -070015133 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070015134
James Carr3a226052016-07-01 14:49:52 -070015135 out.writeInt(mKernelMemoryStats.size());
15136 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
15137 SamplingTimer kmt = mKernelMemoryStats.valueAt(i);
15138 if (kmt != null) {
15139 out.writeInt(1);
15140 out.writeLong(mKernelMemoryStats.keyAt(i));
15141 kmt.writeToParcel(out, uSecRealtime);
15142 } else {
15143 out.writeInt(0);
15144 }
15145 }
15146
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015147 if (inclUids) {
15148 int size = mUidStats.size();
15149 out.writeInt(size);
15150 for (int i = 0; i < size; i++) {
15151 out.writeInt(mUidStats.keyAt(i));
15152 Uid uid = mUidStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015153
Bookatz867c0d72017-03-07 18:23:42 -080015154 uid.writeToParcelLocked(out, uSecUptime, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015155 }
15156 } else {
15157 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015158 }
15159 }
15160
Mathew Inwoodc185f082018-08-20 14:28:54 +010015161 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015162 public static final Parcelable.Creator<BatteryStatsImpl> CREATOR =
15163 new Parcelable.Creator<BatteryStatsImpl>() {
15164 public BatteryStatsImpl createFromParcel(Parcel in) {
15165 return new BatteryStatsImpl(in);
15166 }
15167
15168 public BatteryStatsImpl[] newArray(int size) {
15169 return new BatteryStatsImpl[size];
15170 }
15171 };
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070015172
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070015173 public void prepareForDumpLocked() {
15174 // Need to retrieve current kernel wake lock stats before printing.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080015175 pullPendingStateUpdatesLocked();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070015176
15177 // Pull the clock time. This may update the time and make a new history entry
15178 // if we had originally pulled a time before the RTC was set.
15179 getStartClockTime();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070015180 }
15181
Dianne Hackbornc51cf032014-03-02 19:08:15 -080015182 public void dumpLocked(Context context, PrintWriter pw, int flags, int reqUid, long histStart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015183 if (DEBUG) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080015184 pw.println("mOnBatteryTimeBase:");
15185 mOnBatteryTimeBase.dump(pw, " ");
15186 pw.println("mOnBatteryScreenOffTimeBase:");
15187 mOnBatteryScreenOffTimeBase.dump(pw, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015188 Printer pr = new PrintWriterPrinter(pw);
Mike Mac2f518a2017-09-19 16:06:03 -070015189 pr.println("*** Screen on timer:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015190 mScreenOnTimer.logState(pr, " ");
Mike Mac2f518a2017-09-19 16:06:03 -070015191 pr.println("*** Screen doze timer:");
15192 mScreenDozeTimer.logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070015193 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015194 pr.println("*** Screen brightness #" + i + ":");
15195 mScreenBrightnessTimer[i].logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070015196 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070015197 pr.println("*** Interactive timer:");
15198 mInteractiveTimer.logState(pr, " ");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070015199 pr.println("*** Power save mode timer:");
15200 mPowerSaveModeEnabledTimer.logState(pr, " ");
Dianne Hackborn08c47a52015-10-15 12:38:14 -070015201 pr.println("*** Device idle mode light timer:");
15202 mDeviceIdleModeLightTimer.logState(pr, " ");
15203 pr.println("*** Device idle mode full timer:");
15204 mDeviceIdleModeFullTimer.logState(pr, " ");
15205 pr.println("*** Device light idling timer:");
15206 mDeviceLightIdlingTimer.logState(pr, " ");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070015207 pr.println("*** Device idling timer:");
15208 mDeviceIdlingTimer.logState(pr, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015209 pr.println("*** Phone timer:");
15210 mPhoneOnTimer.logState(pr, " ");
Wink Saville52840902011-02-18 12:40:47 -080015211 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3251b902014-06-20 14:40:53 -070015212 pr.println("*** Phone signal strength #" + i + ":");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015213 mPhoneSignalStrengthsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070015214 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070015215 pr.println("*** Signal scanning :");
15216 mPhoneSignalScanningTimer.logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070015217 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015218 pr.println("*** Data connection type #" + i + ":");
15219 mPhoneDataConnectionsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070015220 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070015221 pr.println("*** mMobileRadioPowerState=" + mMobileRadioPowerState);
Dianne Hackborne13c4c02014-02-11 17:18:35 -080015222 pr.println("*** Mobile network active timer:");
15223 mMobileRadioActiveTimer.logState(pr, " ");
Dianne Hackborna1bd7922014-03-21 11:07:11 -070015224 pr.println("*** Mobile network active adjusted timer:");
15225 mMobileRadioActiveAdjustedTime.logState(pr, " ");
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080015226 pr.println("*** Wifi Multicast WakeLock Timer:");
15227 mWifiMulticastWakelockTimer.logState(pr, " ");
Dianne Hackborn0c820db2015-04-14 17:47:34 -070015228 pr.println("*** mWifiRadioPowerState=" + mWifiRadioPowerState);
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015229 pr.println("*** Wifi timer:");
15230 mWifiOnTimer.logState(pr, " ");
15231 pr.println("*** WifiRunning timer:");
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070015232 mGlobalWifiRunningTimer.logState(pr, " ");
Dianne Hackbornca1bf212014-02-14 14:18:36 -080015233 for (int i=0; i<NUM_WIFI_STATES; i++) {
15234 pr.println("*** Wifi state #" + i + ":");
15235 mWifiStateTimer[i].logState(pr, " ");
15236 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070015237 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
15238 pr.println("*** Wifi suppl state #" + i + ":");
15239 mWifiSupplStateTimer[i].logState(pr, " ");
15240 }
15241 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
15242 pr.println("*** Wifi signal strength #" + i + ":");
15243 mWifiSignalStrengthsTimer[i].logState(pr, " ");
15244 }
Siddharth Ray78ccaf52017-12-23 16:16:21 -080015245 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
15246 pr.println("*** GPS signal quality #" + i + ":");
15247 mGpsSignalQualityTimer[i].logState(pr, " ");
15248 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -070015249 pr.println("*** Flashlight timer:");
15250 mFlashlightOnTimer.logState(pr, " ");
Ruben Brunk6d2c3632015-05-26 17:32:16 -070015251 pr.println("*** Camera timer:");
15252 mCameraOnTimer.logState(pr, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015253 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -080015254 super.dumpLocked(context, pw, flags, reqUid, histStart);
Sudheer Shankac20379e2018-02-15 00:06:21 -080015255 pw.print("Total cpu time reads: ");
Mike Ma234d1822018-03-13 18:53:21 -070015256 pw.println(mNumSingleUidCpuTimeReads);
Sudheer Shankac20379e2018-02-15 00:06:21 -080015257 pw.print("Batched cpu time reads: ");
Mike Ma234d1822018-03-13 18:53:21 -070015258 pw.println(mNumBatchedSingleUidCpuTimeReads);
Sudheer Shankac20379e2018-02-15 00:06:21 -080015259 pw.print("Batching Duration (min): ");
15260 pw.println((mClocks.uptimeMillis() - mCpuTimeReadsTrackingStartTime) / (60 * 1000));
Mike Ma234d1822018-03-13 18:53:21 -070015261 pw.print("All UID cpu time reads since the later of device start or stats reset: ");
15262 pw.println(mNumAllUidCpuTimeReads);
15263 pw.print("UIDs removed since the later of device start or stats reset: ");
15264 pw.println(mNumUidsRemoved);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015265 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015266}