blob: 8b06c47c60d195914b84bbb82dfb962bb1cc9c54 [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"));
Mike Mab3a81a12018-06-29 12:18:27 -07004034 if (registrar != null) {
4035 registrar.scheduleUpdate();
4036 }
Adam Lesinskie1f480d2017-02-15 18:51:23 -08004037 } catch (RemoteException e) {
4038 // Ignore.
4039 }
4040 }
4041
Dianne Hackborn099bc622014-01-22 13:39:16 -08004042 public void addIsolatedUidLocked(int isolatedUid, int appUid) {
4043 mIsolatedUids.put(isolatedUid, appUid);
Bookatz90867622018-01-31 15:05:57 -08004044 StatsLog.write(StatsLog.ISOLATED_UID_CHANGED, appUid, isolatedUid,
4045 StatsLog.ISOLATED_UID_CHANGED__EVENT__CREATED);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08004046 final Uid u = getUidStatsLocked(appUid);
4047 u.addIsolatedUid(isolatedUid);
Dianne Hackborn099bc622014-01-22 13:39:16 -08004048 }
4049
Adam Lesinski61db88f2015-07-01 15:05:07 -07004050 /**
4051 * Schedules a read of the latest cpu times before removing the isolated UID.
4052 * @see #removeIsolatedUidLocked(int)
4053 */
4054 public void scheduleRemoveIsolatedUidLocked(int isolatedUid, int appUid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004055 int curUid = mIsolatedUids.get(isolatedUid, -1);
4056 if (curUid == appUid) {
Adam Lesinski61db88f2015-07-01 15:05:07 -07004057 if (mExternalSync != null) {
4058 mExternalSync.scheduleCpuSyncDueToRemovedUid(isolatedUid);
4059 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08004060 }
4061 }
4062
Adam Lesinski61db88f2015-07-01 15:05:07 -07004063 /**
4064 * This should only be called after the cpu times have been read.
4065 * @see #scheduleRemoveIsolatedUidLocked(int, int)
4066 */
Andreas Gampe3f24e692018-02-05 13:24:28 -08004067 @GuardedBy("this")
Adam Lesinski61db88f2015-07-01 15:05:07 -07004068 public void removeIsolatedUidLocked(int isolatedUid) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08004069 StatsLog.write(
Bookatz90867622018-01-31 15:05:57 -08004070 StatsLog.ISOLATED_UID_CHANGED, mIsolatedUids.get(isolatedUid, -1),
4071 isolatedUid, StatsLog.ISOLATED_UID_CHANGED__EVENT__REMOVED);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08004072 final int idx = mIsolatedUids.indexOfKey(isolatedUid);
4073 if (idx >= 0) {
4074 final int ownerUid = mIsolatedUids.valueAt(idx);
4075 final Uid u = getUidStatsLocked(ownerUid);
4076 u.removeIsolatedUid(isolatedUid);
4077 mIsolatedUids.removeAt(idx);
4078 }
Mike Ma234d1822018-03-13 18:53:21 -07004079 mPendingRemovedUids.add(new UidToRemove(isolatedUid, mClocks.elapsedRealtime()));
Adam Lesinski61db88f2015-07-01 15:05:07 -07004080 }
4081
Dianne Hackborn099bc622014-01-22 13:39:16 -08004082 public int mapUid(int uid) {
4083 int isolated = mIsolatedUids.get(uid, -1);
4084 return isolated > 0 ? isolated : uid;
4085 }
4086
4087 public void noteEventLocked(int code, String name, int uid) {
4088 uid = mapUid(uid);
Dianne Hackborn37de0982014-05-09 09:32:18 -07004089 if (!mActiveEvents.updateState(code, name, uid, 0)) {
4090 return;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08004091 }
Joe Onoratoabded112016-02-08 16:49:39 -08004092 final long elapsedRealtime = mClocks.elapsedRealtime();
4093 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -07004094 addHistoryEventLocked(elapsedRealtime, uptime, code, name, uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -08004095 }
4096
Dianne Hackbornd48954f2015-07-22 17:20:33 -07004097 boolean ensureStartClockTime(final long currentTime) {
4098 final long ABOUT_ONE_YEAR = 365*24*60*60*1000L;
Makoto Onuki62b3c922018-04-25 14:51:56 -07004099 if ((currentTime > ABOUT_ONE_YEAR && mStartClockTime < (currentTime-ABOUT_ONE_YEAR))
4100 || (mStartClockTime > currentTime)) {
Dianne Hackbornd48954f2015-07-22 17:20:33 -07004101 // If the start clock time has changed by more than a year, then presumably
4102 // the previous time was completely bogus. So we are going to figure out a
4103 // new time based on how much time has elapsed since we started counting.
Joe Onoratoabded112016-02-08 16:49:39 -08004104 mStartClockTime = currentTime - (mClocks.elapsedRealtime()-(mRealtimeStart/1000));
Dianne Hackbornd48954f2015-07-22 17:20:33 -07004105 return true;
4106 }
4107 return false;
4108 }
4109
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07004110 public void noteCurrentTimeChangedLocked() {
4111 final long currentTime = System.currentTimeMillis();
Joe Onoratoabded112016-02-08 16:49:39 -08004112 final long elapsedRealtime = mClocks.elapsedRealtime();
4113 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07004114 recordCurrentTimeChangeLocked(currentTime, elapsedRealtime, uptime);
Dianne Hackbornd48954f2015-07-22 17:20:33 -07004115 ensureStartClockTime(currentTime);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07004116 }
4117
Dianne Hackborn61659e52014-07-09 16:13:01 -07004118 public void noteProcessStartLocked(String name, int uid) {
4119 uid = mapUid(uid);
4120 if (isOnBattery()) {
4121 Uid u = getUidStatsLocked(uid);
4122 u.getProcessStatsLocked(name).incStartsLocked();
4123 }
4124 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_START, name, uid, 0)) {
4125 return;
4126 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004127 if (!mRecordAllHistory) {
4128 return;
4129 }
Joe Onoratoabded112016-02-08 16:49:39 -08004130 final long elapsedRealtime = mClocks.elapsedRealtime();
4131 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn61659e52014-07-09 16:13:01 -07004132 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_START, name, uid);
4133 }
4134
Dianne Hackborn1e01d162014-12-04 17:46:42 -08004135 public void noteProcessCrashLocked(String name, int uid) {
4136 uid = mapUid(uid);
4137 if (isOnBattery()) {
4138 Uid u = getUidStatsLocked(uid);
4139 u.getProcessStatsLocked(name).incNumCrashesLocked();
4140 }
4141 }
4142
4143 public void noteProcessAnrLocked(String name, int uid) {
4144 uid = mapUid(uid);
4145 if (isOnBattery()) {
4146 Uid u = getUidStatsLocked(uid);
4147 u.getProcessStatsLocked(name).incNumAnrsLocked();
4148 }
4149 }
4150
Dianne Hackborna8d10942015-11-19 17:55:19 -08004151 public void noteUidProcessStateLocked(int uid, int state) {
Amith Yamasanifd3caf62017-07-26 11:48:35 -07004152 int parentUid = mapUid(uid);
4153 if (uid != parentUid) {
4154 // Isolated UIDs process state is already rolled up into parent, so no need to track
4155 // Otherwise the parent's process state will get downgraded incorrectly
4156 return;
4157 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08004158 getUidStatsLocked(uid).updateUidProcessStateLocked(state);
Dianne Hackborn61659e52014-07-09 16:13:01 -07004159 }
4160
4161 public void noteProcessFinishLocked(String name, int uid) {
4162 uid = mapUid(uid);
4163 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_FINISH, name, uid, 0)) {
4164 return;
4165 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004166 if (!mRecordAllHistory) {
4167 return;
4168 }
Joe Onoratoabded112016-02-08 16:49:39 -08004169 final long elapsedRealtime = mClocks.elapsedRealtime();
4170 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004171 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_FINISH, name, uid);
Dianne Hackborn61659e52014-07-09 16:13:01 -07004172 }
4173
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004174 public void noteSyncStartLocked(String name, int uid) {
4175 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004176 final long elapsedRealtime = mClocks.elapsedRealtime();
4177 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004178 getUidStatsLocked(uid).noteStartSyncLocked(name, elapsedRealtime);
4179 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_START, name, uid, 0)) {
4180 return;
4181 }
4182 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_START, name, uid);
4183 }
4184
4185 public void noteSyncFinishLocked(String name, int uid) {
4186 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004187 final long elapsedRealtime = mClocks.elapsedRealtime();
4188 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004189 getUidStatsLocked(uid).noteStopSyncLocked(name, elapsedRealtime);
4190 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_FINISH, name, uid, 0)) {
4191 return;
4192 }
4193 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_FINISH, name, uid);
4194 }
4195
4196 public void noteJobStartLocked(String name, int uid) {
4197 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004198 final long elapsedRealtime = mClocks.elapsedRealtime();
4199 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004200 getUidStatsLocked(uid).noteStartJobLocked(name, elapsedRealtime);
4201 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_START, name, uid, 0)) {
4202 return;
4203 }
4204 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_START, name, uid);
4205 }
4206
Dianne Hackborn94326cb2017-06-28 16:17:20 -07004207 public void noteJobFinishLocked(String name, int uid, int stopReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004208 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004209 final long elapsedRealtime = mClocks.elapsedRealtime();
4210 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07004211 getUidStatsLocked(uid).noteStopJobLocked(name, elapsedRealtime, stopReason);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004212 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_FINISH, name, uid, 0)) {
4213 return;
4214 }
4215 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_FINISH, name, uid);
4216 }
4217
Amith Yamasani977e11f2018-02-16 11:29:54 -08004218 public void noteJobsDeferredLocked(int uid, int numDeferred, long sinceLast) {
4219 uid = mapUid(uid);
4220 getUidStatsLocked(uid).noteJobsDeferredLocked(numDeferred, sinceLast);
4221 }
4222
Narayan Kamath695cf722017-12-21 18:32:47 +00004223 public void noteAlarmStartLocked(String name, WorkSource workSource, int uid) {
4224 noteAlarmStartOrFinishLocked(HistoryItem.EVENT_ALARM_START, name, workSource, uid);
Dianne Hackborn1e383822015-04-10 14:02:33 -07004225 }
4226
Narayan Kamath695cf722017-12-21 18:32:47 +00004227 public void noteAlarmFinishLocked(String name, WorkSource workSource, int uid) {
4228 noteAlarmStartOrFinishLocked(HistoryItem.EVENT_ALARM_FINISH, name, workSource, uid);
4229 }
4230
4231 private void noteAlarmStartOrFinishLocked(int historyItem, String name, WorkSource workSource,
4232 int uid) {
Dianne Hackborn1e383822015-04-10 14:02:33 -07004233 if (!mRecordAllHistory) {
4234 return;
4235 }
Narayan Kamath695cf722017-12-21 18:32:47 +00004236
Joe Onoratoabded112016-02-08 16:49:39 -08004237 final long elapsedRealtime = mClocks.elapsedRealtime();
4238 final long uptime = mClocks.uptimeMillis();
Narayan Kamath695cf722017-12-21 18:32:47 +00004239
4240 if (workSource != null) {
4241 for (int i = 0; i < workSource.size(); ++i) {
4242 uid = mapUid(workSource.get(i));
4243 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4244 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4245 }
4246 }
4247
4248 List<WorkChain> workChains = workSource.getWorkChains();
4249 if (workChains != null) {
4250 for (int i = 0; i < workChains.size(); ++i) {
4251 uid = mapUid(workChains.get(i).getAttributionUid());
4252 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4253 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4254 }
4255 }
4256 }
4257 } else {
4258 uid = mapUid(uid);
4259
4260 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4261 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4262 }
4263 }
4264 }
4265
4266 public void noteWakupAlarmLocked(String packageName, int uid, WorkSource workSource,
4267 String tag) {
Narayan Kamath695cf722017-12-21 18:32:47 +00004268 if (workSource != null) {
4269 for (int i = 0; i < workSource.size(); ++i) {
4270 uid = workSource.get(i);
4271 final String workSourceName = workSource.getName(i);
4272
Tej Singh6f724c42018-01-03 20:02:03 -08004273 if (isOnBattery()) {
4274 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid,
4275 workSourceName != null ? workSourceName : packageName);
4276 pkg.noteWakeupAlarmLocked(tag);
4277 }
Yangster-mac2f5daec2018-01-16 10:23:15 -08004278 StatsLog.write_non_chained(StatsLog.WAKEUP_ALARM_OCCURRED, workSource.get(i),
4279 workSource.getName(i), tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004280 }
4281
4282 ArrayList<WorkChain> workChains = workSource.getWorkChains();
4283 if (workChains != null) {
4284 for (int i = 0; i < workChains.size(); ++i) {
4285 final WorkChain wc = workChains.get(i);
4286 uid = wc.getAttributionUid();
4287
Tej Singh6f724c42018-01-03 20:02:03 -08004288 if (isOnBattery()) {
4289 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid, packageName);
4290 pkg.noteWakeupAlarmLocked(tag);
4291 }
Yangster-macafad8c62018-01-05 22:30:49 -08004292 StatsLog.write(StatsLog.WAKEUP_ALARM_OCCURRED, wc.getUids(), wc.getTags(), tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004293 }
4294 }
4295 } else {
Tej Singh6f724c42018-01-03 20:02:03 -08004296 if (isOnBattery()) {
4297 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid, packageName);
4298 pkg.noteWakeupAlarmLocked(tag);
4299 }
Yangster-mac2f5daec2018-01-16 10:23:15 -08004300 StatsLog.write_non_chained(StatsLog.WAKEUP_ALARM_OCCURRED, uid, null, tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004301 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07004302 }
4303
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004304 private void requestWakelockCpuUpdate() {
Sudheer Shankac57729a2018-02-09 15:44:42 -08004305 mExternalSync.scheduleCpuSyncDueToWakelockChange(DELAY_UPDATE_WAKELOCKS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004306 }
4307
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004308 private void requestImmediateCpuUpdate() {
Sudheer Shankac57729a2018-02-09 15:44:42 -08004309 mExternalSync.scheduleCpuSyncDueToWakelockChange(0 /* delayMillis */);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004310 }
4311
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004312 public void setRecordAllHistoryLocked(boolean enabled) {
4313 mRecordAllHistory = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004314 if (!enabled) {
4315 // Clear out any existing state.
4316 mActiveEvents.removeEvents(HistoryItem.EVENT_WAKE_LOCK);
Dianne Hackborn1e383822015-04-10 14:02:33 -07004317 mActiveEvents.removeEvents(HistoryItem.EVENT_ALARM);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004318 // Record the currently running processes as stopping, now that we are no
4319 // longer tracking them.
4320 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
4321 HistoryItem.EVENT_PROC);
4322 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08004323 long mSecRealtime = mClocks.elapsedRealtime();
4324 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004325 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
4326 SparseIntArray uids = ent.getValue();
4327 for (int j=0; j<uids.size(); j++) {
4328 addHistoryEventLocked(mSecRealtime, mSecUptime,
4329 HistoryItem.EVENT_PROC_FINISH, ent.getKey(), uids.keyAt(j));
4330 }
4331 }
4332 }
4333 } else {
4334 // Record the currently running processes as starting, now that we are tracking them.
4335 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
4336 HistoryItem.EVENT_PROC);
4337 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08004338 long mSecRealtime = mClocks.elapsedRealtime();
4339 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004340 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
4341 SparseIntArray uids = ent.getValue();
4342 for (int j=0; j<uids.size(); j++) {
4343 addHistoryEventLocked(mSecRealtime, mSecUptime,
4344 HistoryItem.EVENT_PROC_START, ent.getKey(), uids.keyAt(j));
4345 }
4346 }
4347 }
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004348 }
4349 }
4350
Dianne Hackborn9a755432014-05-15 17:05:22 -07004351 public void setNoAutoReset(boolean enabled) {
4352 mNoAutoReset = enabled;
4353 }
4354
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004355 public void setPretendScreenOff(boolean pretendScreenOff) {
Mike Mac2f518a2017-09-19 16:06:03 -07004356 if (mPretendScreenOff != pretendScreenOff) {
4357 mPretendScreenOff = pretendScreenOff;
4358 noteScreenStateLocked(pretendScreenOff ? Display.STATE_OFF : Display.STATE_ON);
4359 }
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004360 }
4361
Dianne Hackborn9a755432014-05-15 17:05:22 -07004362 private String mInitialAcquireWakeName;
4363 private int mInitialAcquireWakeUid = -1;
4364
Narayan Kamath81822022017-12-08 11:56:01 +00004365 public void noteStartWakeLocked(int uid, int pid, WorkChain wc, String name, String historyName,
4366 int type, boolean unimportantForLogging, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004367 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004368 if (type == WAKE_TYPE_PARTIAL) {
4369 // Only care about partial wake locks, since full wake locks
4370 // will be canceled when the user puts the screen to sleep.
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004371 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07004372 if (historyName == null) {
4373 historyName = name;
4374 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004375 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07004376 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_START, historyName,
4377 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07004378 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07004379 HistoryItem.EVENT_WAKE_LOCK_START, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07004380 }
4381 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004382 if (mWakeLockNesting == 0) {
4383 mHistoryCur.states |= HistoryItem.STATE_WAKE_LOCK_FLAG;
4384 if (DEBUG_HISTORY) Slog.v(TAG, "Start wake lock to: "
4385 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08004386 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004387 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07004388 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004389 mWakeLockImportant = !unimportantForLogging;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004390 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07004391 } else if (!mWakeLockImportant && !unimportantForLogging
4392 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004393 if (mHistoryLastWritten.wakelockTag != null) {
4394 // We'll try to update the last tag.
4395 mHistoryLastWritten.wakelockTag = null;
4396 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004397 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07004398 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004399 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004400 }
4401 mWakeLockImportant = true;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004402 }
4403 mWakeLockNesting++;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004404 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004405 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07004406 if (mOnBatteryScreenOffTimeBase.isRunning()) {
4407 // We only update the cpu time when a wake lock is acquired if the screen is off.
4408 // If the screen is on, we don't distribute the power amongst partial wakelocks.
4409 if (DEBUG_ENERGY_CPU) {
4410 Slog.d(TAG, "Updating cpu time because of +wake_lock");
4411 }
4412 requestWakelockCpuUpdate();
4413 }
Narayan Kamath81822022017-12-08 11:56:01 +00004414
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004415 getUidStatsLocked(uid).noteStartWakeLocked(pid, name, type, elapsedRealtime);
Narayan Kamath81822022017-12-08 11:56:01 +00004416
Yangster-mac20877162017-12-22 17:19:39 -08004417 if (wc != null) {
Bookatz1a1b0462018-01-12 11:47:03 -08004418 StatsLog.write(StatsLog.WAKELOCK_STATE_CHANGED, wc.getUids(), wc.getTags(),
Bookatz90867622018-01-31 15:05:57 -08004419 getPowerManagerWakeLockLevel(type), name,
4420 StatsLog.WAKELOCK_STATE_CHANGED__STATE__ACQUIRE);
Yangster-macafad8c62018-01-05 22:30:49 -08004421 } else {
Bookatz1a1b0462018-01-12 11:47:03 -08004422 StatsLog.write_non_chained(StatsLog.WAKELOCK_STATE_CHANGED, uid, null,
Bookatz90867622018-01-31 15:05:57 -08004423 getPowerManagerWakeLockLevel(type), name,
4424 StatsLog.WAKELOCK_STATE_CHANGED__STATE__ACQUIRE);
Narayan Kamath81822022017-12-08 11:56:01 +00004425 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004426 }
4427 }
4428
Narayan Kamath81822022017-12-08 11:56:01 +00004429 public void noteStopWakeLocked(int uid, int pid, WorkChain wc, String name, String historyName,
4430 int type, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004431 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004432 if (type == WAKE_TYPE_PARTIAL) {
4433 mWakeLockNesting--;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004434 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07004435 if (historyName == null) {
4436 historyName = name;
4437 }
4438 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName,
4439 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07004440 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07004441 HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07004442 }
4443 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004444 if (mWakeLockNesting == 0) {
4445 mHistoryCur.states &= ~HistoryItem.STATE_WAKE_LOCK_FLAG;
4446 if (DEBUG_HISTORY) Slog.v(TAG, "Stop wake lock to: "
4447 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn37de0982014-05-09 09:32:18 -07004448 mInitialAcquireWakeName = null;
4449 mInitialAcquireWakeUid = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004450 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004451 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004452 }
4453 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07004454 if (mOnBatteryScreenOffTimeBase.isRunning()) {
4455 if (DEBUG_ENERGY_CPU) {
4456 Slog.d(TAG, "Updating cpu time because of -wake_lock");
4457 }
4458 requestWakelockCpuUpdate();
4459 }
Narayan Kamath81822022017-12-08 11:56:01 +00004460
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004461 getUidStatsLocked(uid).noteStopWakeLocked(pid, name, type, elapsedRealtime);
Yangster-mac20877162017-12-22 17:19:39 -08004462 if (wc != null) {
Bookatz1a1b0462018-01-12 11:47:03 -08004463 StatsLog.write(StatsLog.WAKELOCK_STATE_CHANGED, wc.getUids(), wc.getTags(),
Bookatz90867622018-01-31 15:05:57 -08004464 getPowerManagerWakeLockLevel(type), name,
4465 StatsLog.WAKELOCK_STATE_CHANGED__STATE__RELEASE);
Yangster-macafad8c62018-01-05 22:30:49 -08004466 } else {
Bookatz1a1b0462018-01-12 11:47:03 -08004467 StatsLog.write_non_chained(StatsLog.WAKELOCK_STATE_CHANGED, uid, null,
Bookatz90867622018-01-31 15:05:57 -08004468 getPowerManagerWakeLockLevel(type), name,
4469 StatsLog.WAKELOCK_STATE_CHANGED__STATE__RELEASE);
Narayan Kamath81822022017-12-08 11:56:01 +00004470 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004471 }
4472 }
4473
Bookatz1a1b0462018-01-12 11:47:03 -08004474 /**
4475 * Converts BatteryStats wakelock types back into PowerManager wakelock levels.
4476 * This is the inverse map of Notifier.getBatteryStatsWakeLockMonitorType().
4477 * These are estimations, since batterystats loses some of the original data.
4478 * TODO: Delete this. Instead, StatsLog.write should be called from PowerManager's Notifier.
4479 */
4480 private int getPowerManagerWakeLockLevel(int battertStatsWakelockType) {
4481 switch (battertStatsWakelockType) {
4482 // PowerManager.PARTIAL_WAKE_LOCK or PROXIMITY_SCREEN_OFF_WAKE_LOCK
4483 case BatteryStats.WAKE_TYPE_PARTIAL:
4484 return PowerManager.PARTIAL_WAKE_LOCK;
4485
4486 // PowerManager.SCREEN_DIM_WAKE_LOCK or SCREEN_BRIGHT_WAKE_LOCK
4487 case BatteryStats.WAKE_TYPE_FULL:
4488 return PowerManager.FULL_WAKE_LOCK;
4489
4490 case BatteryStats.WAKE_TYPE_DRAW:
4491 return PowerManager.DRAW_WAKE_LOCK;
4492
4493 // It appears that nothing can ever make a Window and PowerManager lacks an equivalent.
4494 case BatteryStats.WAKE_TYPE_WINDOW:
4495 Slog.e(TAG, "Illegal window wakelock type observed in batterystats.");
4496 return -1;
4497
4498 default:
4499 Slog.e(TAG, "Illegal wakelock type in batterystats: " + battertStatsWakelockType);
4500 return -1;
4501 }
4502 }
4503
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004504 public void noteStartWakeFromSourceLocked(WorkSource ws, int pid, String name,
4505 String historyName, int type, boolean unimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08004506 final long elapsedRealtime = mClocks.elapsedRealtime();
4507 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004508 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004509 for (int i=0; i<N; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004510 noteStartWakeLocked(ws.get(i), pid, null, name, historyName, type,
4511 unimportantForLogging, elapsedRealtime, uptime);
4512 }
4513
4514 List<WorkChain> wcs = ws.getWorkChains();
4515 if (wcs != null) {
4516 for (int i = 0; i < wcs.size(); ++i) {
4517 final WorkChain wc = wcs.get(i);
4518 noteStartWakeLocked(wc.getAttributionUid(), pid, wc, name, historyName, type,
4519 unimportantForLogging, elapsedRealtime, uptime);
4520 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004521 }
4522 }
4523
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004524 public void noteChangeWakelockFromSourceLocked(WorkSource ws, int pid, String name,
4525 String historyName, int type, WorkSource newWs, int newPid, String newName,
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004526 String newHistoryName, int newType, boolean newUnimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08004527 final long elapsedRealtime = mClocks.elapsedRealtime();
4528 final long uptime = mClocks.uptimeMillis();
Narayan Kamath81822022017-12-08 11:56:01 +00004529
4530 List<WorkChain>[] wcs = WorkSource.diffChains(ws, newWs);
4531
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004532 // For correct semantics, we start the need worksources first, so that we won't
4533 // make inappropriate history items as if all wake locks went away and new ones
4534 // appeared. This is okay because tracking of wake locks allows nesting.
Narayan Kamath81822022017-12-08 11:56:01 +00004535 //
4536 // First the starts :
Dianne Hackborn40c87252014-03-19 16:55:40 -07004537 final int NN = newWs.size();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004538 for (int i=0; i<NN; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004539 noteStartWakeLocked(newWs.get(i), newPid, null, newName, newHistoryName, newType,
Dianne Hackborn40c87252014-03-19 16:55:40 -07004540 newUnimportantForLogging, elapsedRealtime, uptime);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004541 }
Narayan Kamath81822022017-12-08 11:56:01 +00004542 if (wcs != null) {
4543 List<WorkChain> newChains = wcs[0];
4544 if (newChains != null) {
4545 for (int i = 0; i < newChains.size(); ++i) {
4546 final WorkChain newChain = newChains.get(i);
4547 noteStartWakeLocked(newChain.getAttributionUid(), newPid, newChain, newName,
4548 newHistoryName, newType, newUnimportantForLogging, elapsedRealtime,
4549 uptime);
4550 }
4551 }
4552 }
4553
4554 // Then the stops :
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004555 final int NO = ws.size();
4556 for (int i=0; i<NO; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004557 noteStopWakeLocked(ws.get(i), pid, null, name, historyName, type, elapsedRealtime,
4558 uptime);
4559 }
4560 if (wcs != null) {
4561 List<WorkChain> goneChains = wcs[1];
4562 if (goneChains != null) {
4563 for (int i = 0; i < goneChains.size(); ++i) {
4564 final WorkChain goneChain = goneChains.get(i);
4565 noteStopWakeLocked(goneChain.getAttributionUid(), pid, goneChain, name,
4566 historyName, type, elapsedRealtime, uptime);
4567 }
4568 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004569 }
4570 }
4571
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004572 public void noteStopWakeFromSourceLocked(WorkSource ws, int pid, String name,
4573 String historyName, int type) {
Joe Onoratoabded112016-02-08 16:49:39 -08004574 final long elapsedRealtime = mClocks.elapsedRealtime();
4575 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004576 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004577 for (int i=0; i<N; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004578 noteStopWakeLocked(ws.get(i), pid, null, name, historyName, type, elapsedRealtime,
4579 uptime);
4580 }
4581
4582 List<WorkChain> wcs = ws.getWorkChains();
4583 if (wcs != null) {
4584 for (int i = 0; i < wcs.size(); ++i) {
4585 final WorkChain wc = wcs.get(i);
4586 noteStopWakeLocked(wc.getAttributionUid(), pid, wc, name, historyName, type,
4587 elapsedRealtime, uptime);
4588 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004589 }
4590 }
4591
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004592 public void noteLongPartialWakelockStart(String name, String historyName, int uid) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08004593 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004594 uid, null, name, historyName,
4595 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
Yangster-macafad8c62018-01-05 22:30:49 -08004596
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004597 uid = mapUid(uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004598 noteLongPartialWakeLockStartInternal(name, historyName, uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004599 }
4600
4601 public void noteLongPartialWakelockStartFromSource(String name, String historyName,
4602 WorkSource workSource) {
4603 final int N = workSource.size();
4604 for (int i = 0; i < N; ++i) {
4605 final int uid = mapUid(workSource.get(i));
4606 noteLongPartialWakeLockStartInternal(name, historyName, uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08004607 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004608 workSource.get(i), workSource.getName(i), name, historyName,
4609 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath96a92562018-01-02 18:57:17 +00004610 }
4611
4612 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
4613 if (workChains != null) {
4614 for (int i = 0; i < workChains.size(); ++i) {
4615 final WorkChain workChain = workChains.get(i);
4616 final int uid = workChain.getAttributionUid();
4617 noteLongPartialWakeLockStartInternal(name, historyName, uid);
4618
Yangster-macafad8c62018-01-05 22:30:49 -08004619 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004620 workChain.getUids(), workChain.getTags(), name, historyName,
4621 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath96a92562018-01-02 18:57:17 +00004622 }
4623 }
4624 }
4625
4626 private void noteLongPartialWakeLockStartInternal(String name, String historyName, int uid) {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004627 final long elapsedRealtime = mClocks.elapsedRealtime();
4628 final long uptime = mClocks.uptimeMillis();
4629 if (historyName == null) {
4630 historyName = name;
4631 }
4632 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_START, historyName, uid,
4633 0)) {
4634 return;
4635 }
4636 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_START,
4637 historyName, uid);
4638 }
4639
4640 public void noteLongPartialWakelockFinish(String name, String historyName, int uid) {
Bookatz90867622018-01-31 15:05:57 -08004641 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED, uid, null,
4642 name, historyName, StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
Yangster-macafad8c62018-01-05 22:30:49 -08004643
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004644 uid = mapUid(uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004645 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004646 }
4647
4648 public void noteLongPartialWakelockFinishFromSource(String name, String historyName,
4649 WorkSource workSource) {
4650 final int N = workSource.size();
4651 for (int i = 0; i < N; ++i) {
4652 final int uid = mapUid(workSource.get(i));
4653 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08004654 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004655 workSource.get(i), workSource.getName(i), name, historyName,
4656 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath96a92562018-01-02 18:57:17 +00004657 }
4658
4659 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
4660 if (workChains != null) {
4661 for (int i = 0; i < workChains.size(); ++i) {
4662 final WorkChain workChain = workChains.get(i);
4663 final int uid = workChain.getAttributionUid();
Narayan Kamath96a92562018-01-02 18:57:17 +00004664 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Yangster-macafad8c62018-01-05 22:30:49 -08004665 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004666 workChain.getUids(), workChain.getTags(), name, historyName,
4667 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath96a92562018-01-02 18:57:17 +00004668 }
4669 }
4670 }
4671
4672 private void noteLongPartialWakeLockFinishInternal(String name, String historyName, int uid) {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004673 final long elapsedRealtime = mClocks.elapsedRealtime();
4674 final long uptime = mClocks.uptimeMillis();
4675 if (historyName == null) {
4676 historyName = name;
4677 }
4678 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH, historyName, uid,
4679 0)) {
4680 return;
4681 }
4682 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH,
4683 historyName, uid);
4684 }
4685
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004686 void aggregateLastWakeupUptimeLocked(long uptimeMs) {
4687 if (mLastWakeupReason != null) {
4688 long deltaUptime = uptimeMs - mLastWakeupUptimeMs;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004689 SamplingTimer timer = getWakeupReasonTimerLocked(mLastWakeupReason);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07004690 timer.add(deltaUptime * 1000, 1); // time in in microseconds
Bookatz90867622018-01-31 15:05:57 -08004691 StatsLog.write(StatsLog.KERNEL_WAKEUP_REPORTED, mLastWakeupReason,
4692 /* duration_usec */ deltaUptime * 1000);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004693 mLastWakeupReason = null;
4694 }
4695 }
4696
4697 public void noteWakeupReasonLocked(String reason) {
Joe Onoratoabded112016-02-08 16:49:39 -08004698 final long elapsedRealtime = mClocks.elapsedRealtime();
4699 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004700 if (DEBUG_HISTORY) Slog.v(TAG, "Wakeup reason \"" + reason +"\": "
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004701 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004702 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004703 mHistoryCur.wakeReasonTag = mHistoryCur.localWakeReasonTag;
4704 mHistoryCur.wakeReasonTag.string = reason;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004705 mHistoryCur.wakeReasonTag.uid = 0;
4706 mLastWakeupReason = reason;
4707 mLastWakeupUptimeMs = uptime;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004708 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004709 }
4710
Adam Lesinski72478f02015-06-17 15:39:43 -07004711 public boolean startAddingCpuLocked() {
Sudheer Shankac57729a2018-02-09 15:44:42 -08004712 mExternalSync.cancelCpuSyncDueToWakelockChange();
Adam Lesinski72478f02015-06-17 15:39:43 -07004713 return mOnBatteryInternal;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004714 }
4715
Adam Lesinski72478f02015-06-17 15:39:43 -07004716 public void finishAddingCpuLocked(int totalUTime, int totalSTime, int statUserTime,
4717 int statSystemTime, int statIOWaitTime, int statIrqTime,
4718 int statSoftIrqTime, int statIdleTime) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004719 if (DEBUG) Slog.d(TAG, "Adding cpu: tuser=" + totalUTime + " tsys=" + totalSTime
4720 + " user=" + statUserTime + " sys=" + statSystemTime
4721 + " io=" + statIOWaitTime + " irq=" + statIrqTime
4722 + " sirq=" + statSoftIrqTime + " idle=" + statIdleTime);
4723 mCurStepCpuUserTime += totalUTime;
4724 mCurStepCpuSystemTime += totalSTime;
4725 mCurStepStatUserTime += statUserTime;
4726 mCurStepStatSystemTime += statSystemTime;
4727 mCurStepStatIOWaitTime += statIOWaitTime;
4728 mCurStepStatIrqTime += statIrqTime;
4729 mCurStepStatSoftIrqTime += statSoftIrqTime;
4730 mCurStepStatIdleTime += statIdleTime;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004731 }
4732
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004733 public void noteProcessDiedLocked(int uid, int pid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004734 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004735 Uid u = mUidStats.get(uid);
4736 if (u != null) {
4737 u.mPids.remove(pid);
4738 }
4739 }
4740
4741 public long getProcessWakeTime(int uid, int pid, long realtime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004742 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004743 Uid u = mUidStats.get(uid);
4744 if (u != null) {
4745 Uid.Pid p = u.mPids.get(pid);
4746 if (p != null) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004747 return p.mWakeSumMs + (p.mWakeNesting > 0 ? (realtime - p.mWakeStartMs) : 0);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004748 }
4749 }
4750 return 0;
4751 }
4752
Dianne Hackborn287952c2010-09-22 22:34:31 -07004753 public void reportExcessiveCpuLocked(int uid, String proc, long overTime, long usedTime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004754 uid = mapUid(uid);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004755 Uid u = mUidStats.get(uid);
4756 if (u != null) {
4757 u.reportExcessiveCpuLocked(proc, overTime, usedTime);
4758 }
4759 }
4760
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004761 int mSensorNesting;
4762
4763 public void noteStartSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004764 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004765 final long elapsedRealtime = mClocks.elapsedRealtime();
4766 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004767 if (mSensorNesting == 0) {
4768 mHistoryCur.states |= HistoryItem.STATE_SENSOR_ON_FLAG;
4769 if (DEBUG_HISTORY) Slog.v(TAG, "Start sensor to: "
4770 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004771 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004772 }
4773 mSensorNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004774 getUidStatsLocked(uid).noteStartSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004775 }
4776
4777 public void noteStopSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004778 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004779 final long elapsedRealtime = mClocks.elapsedRealtime();
4780 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004781 mSensorNesting--;
4782 if (mSensorNesting == 0) {
4783 mHistoryCur.states &= ~HistoryItem.STATE_SENSOR_ON_FLAG;
4784 if (DEBUG_HISTORY) Slog.v(TAG, "Stop sensor to: "
4785 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004786 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004787 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004788 getUidStatsLocked(uid).noteStopSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004789 }
4790
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004791 int mGpsNesting;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004792
Narayan Kamath32684dd2018-01-08 17:32:51 +00004793 public void noteGpsChangedLocked(WorkSource oldWs, WorkSource newWs) {
4794 for (int i = 0; i < newWs.size(); ++i) {
4795 noteStartGpsLocked(newWs.get(i), null);
4796 }
4797
4798 for (int i = 0; i < oldWs.size(); ++i) {
4799 noteStopGpsLocked((oldWs.get(i)), null);
4800 }
4801
4802 List<WorkChain>[] wcs = WorkSource.diffChains(oldWs, newWs);
4803 if (wcs != null) {
4804 if (wcs[0] != null) {
4805 final List<WorkChain> newChains = wcs[0];
4806 for (int i = 0; i < newChains.size(); ++i) {
4807 noteStartGpsLocked(-1, newChains.get(i));
4808 }
4809 }
4810
4811 if (wcs[1] != null) {
4812 final List<WorkChain> goneChains = wcs[1];
4813 for (int i = 0; i < goneChains.size(); ++i) {
4814 noteStopGpsLocked(-1, goneChains.get(i));
4815 }
4816 }
4817 }
4818 }
4819
4820 private void noteStartGpsLocked(int uid, WorkChain workChain) {
4821 uid = getAttributionUid(uid, workChain);
Joe Onoratoabded112016-02-08 16:49:39 -08004822 final long elapsedRealtime = mClocks.elapsedRealtime();
4823 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004824 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004825 mHistoryCur.states |= HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004826 if (DEBUG_HISTORY) Slog.v(TAG, "Start GPS to: "
4827 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004828 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004829 }
4830 mGpsNesting++;
Narayan Kamath32684dd2018-01-08 17:32:51 +00004831
4832 if (workChain == null) {
Bookatz90867622018-01-31 15:05:57 -08004833 StatsLog.write_non_chained(StatsLog.GPS_SCAN_STATE_CHANGED, uid, null,
4834 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004835 } else {
4836 StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004837 workChain.getUids(), workChain.getTags(),
4838 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004839 }
4840
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004841 getUidStatsLocked(uid).noteStartGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004842 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004843
Narayan Kamath32684dd2018-01-08 17:32:51 +00004844 private void noteStopGpsLocked(int uid, WorkChain workChain) {
4845 uid = getAttributionUid(uid, workChain);
Joe Onoratoabded112016-02-08 16:49:39 -08004846 final long elapsedRealtime = mClocks.elapsedRealtime();
4847 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004848 mGpsNesting--;
4849 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004850 mHistoryCur.states &= ~HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004851 if (DEBUG_HISTORY) Slog.v(TAG, "Stop GPS to: "
4852 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004853 addHistoryRecordLocked(elapsedRealtime, uptime);
Siddharth Ray78ccaf52017-12-23 16:16:21 -08004854 stopAllGpsSignalQualityTimersLocked(-1);
4855 mGpsSignalQualityBin = -1;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004856 }
Narayan Kamath32684dd2018-01-08 17:32:51 +00004857
4858 if (workChain == null) {
Bookatz90867622018-01-31 15:05:57 -08004859 StatsLog.write_non_chained(StatsLog.GPS_SCAN_STATE_CHANGED, uid, null,
4860 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004861 } else {
4862 StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED, workChain.getUids(),
Bookatz90867622018-01-31 15:05:57 -08004863 workChain.getTags(), StatsLog.GPS_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004864 }
4865
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004866 getUidStatsLocked(uid).noteStopGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004867 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07004868
Siddharth Ray78ccaf52017-12-23 16:16:21 -08004869 public void noteGpsSignalQualityLocked(int signalLevel) {
4870 if (mGpsNesting == 0) {
4871 return;
4872 }
4873 if (signalLevel < 0 || signalLevel >= GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS) {
4874 stopAllGpsSignalQualityTimersLocked(-1);
4875 return;
4876 }
4877 final long elapsedRealtime = mClocks.elapsedRealtime();
4878 final long uptime = mClocks.uptimeMillis();
4879 if (mGpsSignalQualityBin != signalLevel) {
4880 if (mGpsSignalQualityBin >= 0) {
4881 mGpsSignalQualityTimer[mGpsSignalQualityBin].stopRunningLocked(elapsedRealtime);
4882 }
4883 if(!mGpsSignalQualityTimer[signalLevel].isRunningLocked()) {
4884 mGpsSignalQualityTimer[signalLevel].startRunningLocked(elapsedRealtime);
4885 }
4886 mHistoryCur.states2 = (mHistoryCur.states2&~HistoryItem.STATE2_GPS_SIGNAL_QUALITY_MASK)
4887 | (signalLevel << HistoryItem.STATE2_GPS_SIGNAL_QUALITY_SHIFT);
4888 addHistoryRecordLocked(elapsedRealtime, uptime);
4889 mGpsSignalQualityBin = signalLevel;
4890 }
4891 return;
4892 }
4893
Andreas Gampe3f24e692018-02-05 13:24:28 -08004894 @GuardedBy("this")
Jeff Browne95c3cd2014-05-02 16:59:26 -07004895 public void noteScreenStateLocked(int state) {
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004896 state = mPretendScreenOff ? Display.STATE_OFF : state;
Santos Cordone94f0502017-02-24 12:31:20 -08004897
4898 // Battery stats relies on there being 4 states. To accommodate this, new states beyond the
4899 // original 4 are mapped to one of the originals.
4900 if (state > MAX_TRACKED_SCREEN_STATE) {
4901 switch (state) {
4902 case Display.STATE_VR:
4903 state = Display.STATE_ON;
4904 break;
4905 default:
4906 Slog.wtf(TAG, "Unknown screen state (not mapped): " + state);
4907 break;
4908 }
4909 }
4910
Jeff Browne95c3cd2014-05-02 16:59:26 -07004911 if (mScreenState != state) {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08004912 recordDailyStatsIfNeededLocked(true);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004913 final int oldState = mScreenState;
4914 mScreenState = state;
4915 if (DEBUG) Slog.v(TAG, "Screen state: oldState=" + Display.stateToString(oldState)
4916 + ", newState=" + Display.stateToString(state));
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004917
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004918 if (state != Display.STATE_UNKNOWN) {
4919 int stepState = state-1;
Santos Cordone94f0502017-02-24 12:31:20 -08004920 if ((stepState & STEP_LEVEL_MODE_SCREEN_STATE) == stepState) {
4921 mModStepMode |= (mCurStepMode & STEP_LEVEL_MODE_SCREEN_STATE) ^ stepState;
4922 mCurStepMode = (mCurStepMode & ~STEP_LEVEL_MODE_SCREEN_STATE) | stepState;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004923 } else {
4924 Slog.wtf(TAG, "Unexpected screen state: " + state);
4925 }
4926 }
4927
Mike Mac2f518a2017-09-19 16:06:03 -07004928 final long elapsedRealtime = mClocks.elapsedRealtime();
4929 final long uptime = mClocks.uptimeMillis();
4930
4931 boolean updateHistory = false;
4932 if (isScreenDoze(state)) {
4933 mHistoryCur.states |= HistoryItem.STATE_SCREEN_DOZE_FLAG;
4934 mScreenDozeTimer.startRunningLocked(elapsedRealtime);
4935 updateHistory = true;
4936 } else if (isScreenDoze(oldState)) {
4937 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_DOZE_FLAG;
4938 mScreenDozeTimer.stopRunningLocked(elapsedRealtime);
4939 updateHistory = true;
4940 }
4941 if (isScreenOn(state)) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07004942 mHistoryCur.states |= HistoryItem.STATE_SCREEN_ON_FLAG;
4943 if (DEBUG_HISTORY) Slog.v(TAG, "Screen on to: "
4944 + Integer.toHexString(mHistoryCur.states));
Jeff Browne95c3cd2014-05-02 16:59:26 -07004945 mScreenOnTimer.startRunningLocked(elapsedRealtime);
4946 if (mScreenBrightnessBin >= 0) {
4947 mScreenBrightnessTimer[mScreenBrightnessBin].startRunningLocked(elapsedRealtime);
4948 }
Mike Mac2f518a2017-09-19 16:06:03 -07004949 updateHistory = true;
4950 } else if (isScreenOn(oldState)) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07004951 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_ON_FLAG;
4952 if (DEBUG_HISTORY) Slog.v(TAG, "Screen off to: "
4953 + Integer.toHexString(mHistoryCur.states));
Jeff Browne95c3cd2014-05-02 16:59:26 -07004954 mScreenOnTimer.stopRunningLocked(elapsedRealtime);
4955 if (mScreenBrightnessBin >= 0) {
4956 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
4957 }
Mike Mac2f518a2017-09-19 16:06:03 -07004958 updateHistory = true;
4959 }
4960 if (updateHistory) {
4961 if (DEBUG_HISTORY) Slog.v(TAG, "Screen state to: "
4962 + Display.stateToString(state));
4963 addHistoryRecordLocked(elapsedRealtime, uptime);
4964 }
Sudheer Shankac57729a2018-02-09 15:44:42 -08004965 mExternalSync.scheduleCpuSyncDueToScreenStateChange(
4966 mOnBatteryTimeBase.isRunning(), mOnBatteryScreenOffTimeBase.isRunning());
Mike Mac2f518a2017-09-19 16:06:03 -07004967 if (isScreenOn(state)) {
4968 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), state,
4969 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
4970 // Fake a wake lock, so we consider the device waked as long as the screen is on.
Narayan Kamath81822022017-12-08 11:56:01 +00004971 noteStartWakeLocked(-1, -1, null, "screen", null, WAKE_TYPE_PARTIAL, false,
Mike Mac2f518a2017-09-19 16:06:03 -07004972 elapsedRealtime, uptime);
4973 } else if (isScreenOn(oldState)) {
Narayan Kamath81822022017-12-08 11:56:01 +00004974 noteStopWakeLocked(-1, -1, null, "screen", "screen", WAKE_TYPE_PARTIAL,
Jeff Browne95c3cd2014-05-02 16:59:26 -07004975 elapsedRealtime, uptime);
Mike Mac2f518a2017-09-19 16:06:03 -07004976 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), state,
Joe Onoratoabded112016-02-08 16:49:39 -08004977 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
Mike Mac2f518a2017-09-19 16:06:03 -07004978 }
4979 // Update discharge amounts.
4980 if (mOnBatteryInternal) {
4981 updateDischargeScreenLevelsLocked(oldState, state);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08004982 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07004983 }
4984 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004985
Mathew Inwoodc185f082018-08-20 14:28:54 +01004986 @UnsupportedAppUsage
Dianne Hackborn617f8772009-03-31 15:04:46 -07004987 public void noteScreenBrightnessLocked(int brightness) {
4988 // Bin the brightness.
4989 int bin = brightness / (256/NUM_SCREEN_BRIGHTNESS_BINS);
4990 if (bin < 0) bin = 0;
4991 else if (bin >= NUM_SCREEN_BRIGHTNESS_BINS) bin = NUM_SCREEN_BRIGHTNESS_BINS-1;
4992 if (mScreenBrightnessBin != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08004993 final long elapsedRealtime = mClocks.elapsedRealtime();
4994 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004995 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_BRIGHTNESS_MASK)
4996 | (bin << HistoryItem.STATE_BRIGHTNESS_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004997 if (DEBUG_HISTORY) Slog.v(TAG, "Screen brightness " + bin + " to: "
4998 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004999 addHistoryRecordLocked(elapsedRealtime, uptime);
Jeff Browne95c3cd2014-05-02 16:59:26 -07005000 if (mScreenState == Display.STATE_ON) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07005001 if (mScreenBrightnessBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005002 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07005003 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005004 mScreenBrightnessTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07005005 }
5006 mScreenBrightnessBin = bin;
5007 }
5008 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005009
Mathew Inwoodc185f082018-08-20 14:28:54 +01005010 @UnsupportedAppUsage
Dianne Hackborn617f8772009-03-31 15:04:46 -07005011 public void noteUserActivityLocked(int uid, int event) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08005012 if (mOnBatteryInternal) {
5013 uid = mapUid(uid);
5014 getUidStatsLocked(uid).noteUserActivityLocked(event);
5015 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005016 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005017
Dianne Hackborn280a64e2015-07-13 14:48:08 -07005018 public void noteWakeUpLocked(String reason, int reasonUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005019 final long elapsedRealtime = mClocks.elapsedRealtime();
5020 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn280a64e2015-07-13 14:48:08 -07005021 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SCREEN_WAKE_UP,
5022 reason, reasonUid);
5023 }
5024
Jeff Browne95c3cd2014-05-02 16:59:26 -07005025 public void noteInteractiveLocked(boolean interactive) {
5026 if (mInteractive != interactive) {
Joe Onoratoabded112016-02-08 16:49:39 -08005027 final long elapsedRealtime = mClocks.elapsedRealtime();
Jeff Browne95c3cd2014-05-02 16:59:26 -07005028 mInteractive = interactive;
5029 if (DEBUG) Slog.v(TAG, "Interactive: " + interactive);
5030 if (interactive) {
5031 mInteractiveTimer.startRunningLocked(elapsedRealtime);
5032 } else {
5033 mInteractiveTimer.stopRunningLocked(elapsedRealtime);
5034 }
5035 }
5036 }
5037
Dianne Hackborn1e01d162014-12-04 17:46:42 -08005038 public void noteConnectivityChangedLocked(int type, String extra) {
Joe Onoratoabded112016-02-08 16:49:39 -08005039 final long elapsedRealtime = mClocks.elapsedRealtime();
5040 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08005041 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_CONNECTIVITY_CHANGED,
5042 extra, type);
5043 mNumConnectivityChange++;
5044 }
5045
Adam Lesinski5f056f62016-07-14 16:56:08 -07005046 private void noteMobileRadioApWakeupLocked(final long elapsedRealtimeMillis,
5047 final long uptimeMillis, int uid) {
5048 uid = mapUid(uid);
5049 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
5050 uid);
5051 getUidStatsLocked(uid).noteMobileRadioApWakeupLocked();
5052 }
5053
Adam Lesinski14ae39a2017-05-26 11:50:40 -07005054 /**
5055 * Updates the radio power state and returns true if an external stats collection should occur.
5056 */
5057 public boolean noteMobileRadioPowerStateLocked(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005058 final long elapsedRealtime = mClocks.elapsedRealtime();
5059 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005060 if (mMobileRadioPowerState != powerState) {
5061 long realElapsedRealtimeMs;
5062 final boolean active =
5063 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
5064 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
5065 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07005066 if (uid > 0) {
5067 noteMobileRadioApWakeupLocked(elapsedRealtime, uptime, uid);
5068 }
5069
Adam Lesinski9acfd812016-04-19 18:29:50 -07005070 mMobileRadioActiveStartTime = realElapsedRealtimeMs = timestampNs / (1000 * 1000);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005071 mHistoryCur.states |= HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
5072 } else {
5073 realElapsedRealtimeMs = timestampNs / (1000*1000);
Dianne Hackbornf7097a52014-05-13 09:56:14 -07005074 long lastUpdateTimeMs = mMobileRadioActiveStartTime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005075 if (realElapsedRealtimeMs < lastUpdateTimeMs) {
5076 Slog.wtf(TAG, "Data connection inactive timestamp " + realElapsedRealtimeMs
5077 + " is before start time " + lastUpdateTimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005078 realElapsedRealtimeMs = elapsedRealtime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005079 } else if (realElapsedRealtimeMs < elapsedRealtime) {
5080 mMobileRadioActiveAdjustedTime.addCountLocked(elapsedRealtime
5081 - realElapsedRealtimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005082 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005083 mHistoryCur.states &= ~HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
5084 }
5085 if (DEBUG_HISTORY) Slog.v(TAG, "Mobile network active " + active + " to: "
5086 + Integer.toHexString(mHistoryCur.states));
5087 addHistoryRecordLocked(elapsedRealtime, uptime);
5088 mMobileRadioPowerState = powerState;
Yangster-mac4c7255f2018-05-07 13:41:47 -07005089 StatsLog.write_non_chained(StatsLog.MOBILE_RADIO_POWER_STATE_CHANGED, uid, null,
5090 powerState);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005091 if (active) {
5092 mMobileRadioActiveTimer.startRunningLocked(elapsedRealtime);
5093 mMobileRadioActivePerAppTimer.startRunningLocked(elapsedRealtime);
5094 } else {
5095 mMobileRadioActiveTimer.stopRunningLocked(realElapsedRealtimeMs);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005096 mMobileRadioActivePerAppTimer.stopRunningLocked(realElapsedRealtimeMs);
Adam Lesinski14ae39a2017-05-26 11:50:40 -07005097 // Tell the caller to collect radio network/power stats.
5098 return true;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08005099 }
Dianne Hackborne13c4c02014-02-11 17:18:35 -08005100 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -07005101 return false;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08005102 }
5103
Adam Lesinski14ae39a2017-05-26 11:50:40 -07005104 public void notePowerSaveModeLocked(boolean enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005105 if (mPowerSaveModeEnabled != enabled) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07005106 int stepState = enabled ? STEP_LEVEL_MODE_POWER_SAVE : 0;
5107 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_POWER_SAVE) ^ stepState;
5108 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_POWER_SAVE) | stepState;
Joe Onoratoabded112016-02-08 16:49:39 -08005109 final long elapsedRealtime = mClocks.elapsedRealtime();
5110 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005111 mPowerSaveModeEnabled = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005112 if (enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005113 mHistoryCur.states2 |= HistoryItem.STATE2_POWER_SAVE_FLAG;
5114 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode enabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005115 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005116 mPowerSaveModeEnabledTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005117 } else {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005118 mHistoryCur.states2 &= ~HistoryItem.STATE2_POWER_SAVE_FLAG;
5119 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode disabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005120 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005121 mPowerSaveModeEnabledTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005122 }
5123 addHistoryRecordLocked(elapsedRealtime, uptime);
Bookatz90867622018-01-31 15:05:57 -08005124 StatsLog.write(StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED, enabled ?
5125 StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED__STATE__ON :
5126 StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED__STATE__OFF);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005127 }
5128 }
5129
Bookatzddccf0a2017-11-28 16:48:14 -08005130 public void noteDeviceIdleModeLocked(final int mode, String activeReason, int activeUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005131 final long elapsedRealtime = mClocks.elapsedRealtime();
5132 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005133 boolean nowIdling = mode == DEVICE_IDLE_MODE_DEEP;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005134 if (mDeviceIdling && !nowIdling && activeReason == null) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005135 // We don't go out of general idling mode until explicitly taken out of
5136 // device idle through going active or significant motion.
5137 nowIdling = true;
5138 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005139 boolean nowLightIdling = mode == DEVICE_IDLE_MODE_LIGHT;
5140 if (mDeviceLightIdling && !nowLightIdling && !nowIdling && activeReason == null) {
5141 // We don't go out of general light idling mode until explicitly taken out of
5142 // device idle through going active or significant motion.
5143 nowLightIdling = true;
5144 }
5145 if (activeReason != null && (mDeviceIdling || mDeviceLightIdling)) {
5146 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_ACTIVE,
5147 activeReason, activeUid);
5148 }
Bookatzddccf0a2017-11-28 16:48:14 -08005149 if (mDeviceIdling != nowIdling || mDeviceLightIdling != nowLightIdling) {
5150 int statsmode;
5151 if (nowIdling) statsmode = DEVICE_IDLE_MODE_DEEP;
5152 else if (nowLightIdling) statsmode = DEVICE_IDLE_MODE_LIGHT;
5153 else statsmode = DEVICE_IDLE_MODE_OFF;
5154 StatsLog.write(StatsLog.DEVICE_IDLING_MODE_STATE_CHANGED, statsmode);
5155 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005156 if (mDeviceIdling != nowIdling) {
5157 mDeviceIdling = nowIdling;
5158 int stepState = nowIdling ? STEP_LEVEL_MODE_DEVICE_IDLE : 0;
5159 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_DEVICE_IDLE) ^ stepState;
5160 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_DEVICE_IDLE) | stepState;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005161 if (nowIdling) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005162 mDeviceIdlingTimer.startRunningLocked(elapsedRealtime);
5163 } else {
5164 mDeviceIdlingTimer.stopRunningLocked(elapsedRealtime);
5165 }
5166 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005167 if (mDeviceLightIdling != nowLightIdling) {
5168 mDeviceLightIdling = nowLightIdling;
5169 if (nowLightIdling) {
5170 mDeviceLightIdlingTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005171 } else {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005172 mDeviceLightIdlingTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005173 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005174 }
5175 if (mDeviceIdleMode != mode) {
5176 mHistoryCur.states2 = (mHistoryCur.states2 & ~HistoryItem.STATE2_DEVICE_IDLE_MASK)
5177 | (mode << HistoryItem.STATE2_DEVICE_IDLE_SHIFT);
5178 if (DEBUG_HISTORY) Slog.v(TAG, "Device idle mode changed to: "
5179 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005180 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005181 long lastDuration = elapsedRealtime - mLastIdleTimeStart;
5182 mLastIdleTimeStart = elapsedRealtime;
5183 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
5184 if (lastDuration > mLongestLightIdleTime) {
5185 mLongestLightIdleTime = lastDuration;
5186 }
5187 mDeviceIdleModeLightTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005188 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005189 if (lastDuration > mLongestFullIdleTime) {
5190 mLongestFullIdleTime = lastDuration;
5191 }
5192 mDeviceIdleModeFullTimer.stopRunningLocked(elapsedRealtime);
5193 }
5194 if (mode == DEVICE_IDLE_MODE_LIGHT) {
5195 mDeviceIdleModeLightTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005196 } else if (mode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005197 mDeviceIdleModeFullTimer.startRunningLocked(elapsedRealtime);
5198 }
5199 mDeviceIdleMode = mode;
Bookatzddccf0a2017-11-28 16:48:14 -08005200 StatsLog.write(StatsLog.DEVICE_IDLE_MODE_STATE_CHANGED, mode);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005201 }
5202 }
5203
Dianne Hackborn3accca02013-09-20 09:32:11 -07005204 public void notePackageInstalledLocked(String pkgName, long versionCode) {
Joe Onoratoabded112016-02-08 16:49:39 -08005205 final long elapsedRealtime = mClocks.elapsedRealtime();
5206 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3accca02013-09-20 09:32:11 -07005207 // XXX need to figure out what to do with long version codes.
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005208 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_INSTALLED,
Dianne Hackborn3accca02013-09-20 09:32:11 -07005209 pkgName, (int)versionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005210 PackageChange pc = new PackageChange();
5211 pc.mPackageName = pkgName;
5212 pc.mUpdate = true;
5213 pc.mVersionCode = versionCode;
5214 addPackageChange(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005215 }
5216
5217 public void notePackageUninstalledLocked(String pkgName) {
Joe Onoratoabded112016-02-08 16:49:39 -08005218 final long elapsedRealtime = mClocks.elapsedRealtime();
5219 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005220 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_UNINSTALLED,
5221 pkgName, 0);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005222 PackageChange pc = new PackageChange();
5223 pc.mPackageName = pkgName;
5224 pc.mUpdate = true;
5225 addPackageChange(pc);
5226 }
5227
5228 private void addPackageChange(PackageChange pc) {
5229 if (mDailyPackageChanges == null) {
5230 mDailyPackageChanges = new ArrayList<>();
5231 }
5232 mDailyPackageChanges.add(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005233 }
5234
Siddharth Ray78ccaf52017-12-23 16:16:21 -08005235 void stopAllGpsSignalQualityTimersLocked(int except) {
5236 final long elapsedRealtime = mClocks.elapsedRealtime();
5237 for (int i = 0; i < GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
5238 if (i == except) {
5239 continue;
5240 }
5241 while (mGpsSignalQualityTimer[i].isRunningLocked()) {
5242 mGpsSignalQualityTimer[i].stopRunningLocked(elapsedRealtime);
5243 }
5244 }
5245 }
5246
Mathew Inwoodc185f082018-08-20 14:28:54 +01005247 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005248 public void notePhoneOnLocked() {
5249 if (!mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005250 final long elapsedRealtime = mClocks.elapsedRealtime();
5251 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005252 mHistoryCur.states2 |= HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005253 if (DEBUG_HISTORY) Slog.v(TAG, "Phone on to: "
5254 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005255 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005256 mPhoneOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005257 mPhoneOnTimer.startRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005258 }
5259 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005260
Mathew Inwoodc185f082018-08-20 14:28:54 +01005261 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005262 public void notePhoneOffLocked() {
5263 if (mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005264 final long elapsedRealtime = mClocks.elapsedRealtime();
5265 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005266 mHistoryCur.states2 &= ~HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005267 if (DEBUG_HISTORY) Slog.v(TAG, "Phone off to: "
5268 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005269 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005270 mPhoneOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005271 mPhoneOnTimer.stopRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005272 }
5273 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07005274
Mike Mafbc01fc2018-04-02 10:28:28 -07005275 private void registerUsbStateReceiver(Context context) {
5276 final IntentFilter usbStateFilter = new IntentFilter();
5277 usbStateFilter.addAction(UsbManager.ACTION_USB_STATE);
5278 context.registerReceiver(new BroadcastReceiver() {
5279 @Override
5280 public void onReceive(Context context, Intent intent) {
5281 final boolean state = intent.getBooleanExtra(UsbManager.USB_CONNECTED, false);
5282 synchronized (BatteryStatsImpl.this) {
5283 noteUsbConnectionStateLocked(state);
5284 }
5285 }
5286 }, usbStateFilter);
5287 synchronized (this) {
5288 if (mUsbDataState == USB_DATA_UNKNOWN) {
5289 final Intent usbState = context.registerReceiver(null, usbStateFilter);
5290 final boolean initState = usbState != null && usbState.getBooleanExtra(
5291 UsbManager.USB_CONNECTED, false);
5292 noteUsbConnectionStateLocked(initState);
5293 }
5294 }
5295 }
5296
5297 private void noteUsbConnectionStateLocked(boolean connected) {
5298 int newState = connected ? USB_DATA_CONNECTED : USB_DATA_DISCONNECTED;
Mike Ma926a97c2018-03-25 02:32:35 -07005299 if (mUsbDataState != newState) {
5300 mUsbDataState = newState;
5301 if (connected) {
5302 mHistoryCur.states2 |= HistoryItem.STATE2_USB_DATA_LINK_FLAG;
5303 } else {
5304 mHistoryCur.states2 &= ~HistoryItem.STATE2_USB_DATA_LINK_FLAG;
5305 }
5306 addHistoryRecordLocked(mClocks.elapsedRealtime(), mClocks.uptimeMillis());
5307 }
5308 }
5309
Dianne Hackborn3251b902014-06-20 14:40:53 -07005310 void stopAllPhoneSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005311 final long elapsedRealtime = mClocks.elapsedRealtime();
Wink Saville52840902011-02-18 12:40:47 -08005312 for (int i = 0; i < SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005313 if (i == except) {
5314 continue;
5315 }
5316 while (mPhoneSignalStrengthsTimer[i].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005317 mPhoneSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005318 }
5319 }
5320 }
5321
Dianne Hackborne4a59512010-12-07 11:08:07 -08005322 private int fixPhoneServiceState(int state, int signalBin) {
5323 if (mPhoneSimStateRaw == TelephonyManager.SIM_STATE_ABSENT) {
5324 // In this case we will always be STATE_OUT_OF_SERVICE, so need
5325 // to infer that we are scanning from other data.
5326 if (state == ServiceState.STATE_OUT_OF_SERVICE
Wink Saville52840902011-02-18 12:40:47 -08005327 && signalBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005328 state = ServiceState.STATE_IN_SERVICE;
5329 }
5330 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005331
Dianne Hackborne4a59512010-12-07 11:08:07 -08005332 return state;
5333 }
5334
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005335 private void updateAllPhoneStateLocked(int state, int simState, int strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005336 boolean scanning = false;
5337 boolean newHistory = false;
5338
5339 mPhoneServiceStateRaw = state;
5340 mPhoneSimStateRaw = simState;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005341 mPhoneSignalStrengthBinRaw = strengthBin;
5342
Joe Onoratoabded112016-02-08 16:49:39 -08005343 final long elapsedRealtime = mClocks.elapsedRealtime();
5344 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne4a59512010-12-07 11:08:07 -08005345
5346 if (simState == TelephonyManager.SIM_STATE_ABSENT) {
5347 // In this case we will always be STATE_OUT_OF_SERVICE, so need
5348 // to infer that we are scanning from other data.
5349 if (state == ServiceState.STATE_OUT_OF_SERVICE
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005350 && strengthBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005351 state = ServiceState.STATE_IN_SERVICE;
5352 }
5353 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005354
5355 // If the phone is powered off, stop all timers.
5356 if (state == ServiceState.STATE_POWER_OFF) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005357 strengthBin = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -07005358
Dianne Hackborne4a59512010-12-07 11:08:07 -08005359 // If we are in service, make sure the correct signal string timer is running.
5360 } else if (state == ServiceState.STATE_IN_SERVICE) {
5361 // Bin will be changed below.
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005362
5363 // If we're out of service, we are in the lowest signal strength
5364 // bin and have the scanning bit set.
Amith Yamasanif37447b2009-10-08 18:28:01 -07005365 } else if (state == ServiceState.STATE_OUT_OF_SERVICE) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005366 scanning = true;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005367 strengthBin = SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN;
Amith Yamasanif37447b2009-10-08 18:28:01 -07005368 if (!mPhoneSignalScanningTimer.isRunningLocked()) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005369 mHistoryCur.states |= HistoryItem.STATE_PHONE_SCANNING_FLAG;
Dianne Hackborne4a59512010-12-07 11:08:07 -08005370 newHistory = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005371 if (DEBUG_HISTORY) Slog.v(TAG, "Phone started scanning to: "
5372 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005373 mPhoneSignalScanningTimer.startRunningLocked(elapsedRealtime);
Yangster4ccebea2018-10-09 17:09:02 -07005374 StatsLog.write(StatsLog.PHONE_SERVICE_STATE_CHANGED, state, simState, strengthBin);
Amith Yamasanif37447b2009-10-08 18:28:01 -07005375 }
5376 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005377
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005378 if (!scanning) {
5379 // If we are no longer scanning, then stop the scanning timer.
5380 if (mPhoneSignalScanningTimer.isRunningLocked()) {
5381 mHistoryCur.states &= ~HistoryItem.STATE_PHONE_SCANNING_FLAG;
5382 if (DEBUG_HISTORY) Slog.v(TAG, "Phone stopped scanning to: "
5383 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08005384 newHistory = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005385 mPhoneSignalScanningTimer.stopRunningLocked(elapsedRealtime);
Yangster4ccebea2018-10-09 17:09:02 -07005386 StatsLog.write(StatsLog.PHONE_SERVICE_STATE_CHANGED, state, simState, strengthBin);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005387 }
5388 }
5389
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005390 if (mPhoneServiceState != state) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005391 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_STATE_MASK)
5392 | (state << HistoryItem.STATE_PHONE_STATE_SHIFT);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005393 if (DEBUG_HISTORY) Slog.v(TAG, "Phone state " + state + " to: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005394 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08005395 newHistory = true;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005396 mPhoneServiceState = state;
5397 }
Dianne Hackborne4a59512010-12-07 11:08:07 -08005398
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005399 if (mPhoneSignalStrengthBin != strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005400 if (mPhoneSignalStrengthBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005401 mPhoneSignalStrengthsTimer[mPhoneSignalStrengthBin].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005402 elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005403 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005404 if (strengthBin >= 0) {
5405 if (!mPhoneSignalStrengthsTimer[strengthBin].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005406 mPhoneSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005407 }
Dianne Hackborn3251b902014-06-20 14:40:53 -07005408 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_MASK)
5409 | (strengthBin << HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_SHIFT);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005410 if (DEBUG_HISTORY) Slog.v(TAG, "Signal strength " + strengthBin + " to: "
Dianne Hackborne4a59512010-12-07 11:08:07 -08005411 + Integer.toHexString(mHistoryCur.states));
5412 newHistory = true;
Bookatze5885242017-10-24 20:10:31 -07005413 StatsLog.write(StatsLog.PHONE_SIGNAL_STRENGTH_CHANGED, strengthBin);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005414 } else {
Dianne Hackborn3251b902014-06-20 14:40:53 -07005415 stopAllPhoneSignalStrengthTimersLocked(-1);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005416 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005417 mPhoneSignalStrengthBin = strengthBin;
Dianne Hackborne4a59512010-12-07 11:08:07 -08005418 }
5419
5420 if (newHistory) {
Dianne Hackborn40c87252014-03-19 16:55:40 -07005421 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005422 }
5423 }
5424
5425 /**
5426 * Telephony stack updates the phone state.
5427 * @param state phone state from ServiceState.getState()
5428 */
5429 public void notePhoneStateLocked(int state, int simState) {
5430 updateAllPhoneStateLocked(state, simState, mPhoneSignalStrengthBinRaw);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07005431 }
5432
Mathew Inwoodc185f082018-08-20 14:28:54 +01005433 @UnsupportedAppUsage
Wink Savillee9b06d72009-05-18 21:47:50 -07005434 public void notePhoneSignalStrengthLocked(SignalStrength signalStrength) {
Dianne Hackborn627bba72009-03-24 22:32:56 -07005435 // Bin the strength.
Wink Saville52840902011-02-18 12:40:47 -08005436 int bin = signalStrength.getLevel();
Dianne Hackborne4a59512010-12-07 11:08:07 -08005437 updateAllPhoneStateLocked(mPhoneServiceStateRaw, mPhoneSimStateRaw, bin);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005438 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005439
Mathew Inwoodc185f082018-08-20 14:28:54 +01005440 @UnsupportedAppUsage
Dianne Hackborn627bba72009-03-24 22:32:56 -07005441 public void notePhoneDataConnectionStateLocked(int dataType, boolean hasData) {
Tej Singheee317b2018-03-07 19:28:05 -08005442 // BatteryStats uses 0 to represent no network type.
5443 // Telephony does not have a concept of no network type, and uses 0 to represent unknown.
5444 // Unknown is included in DATA_CONNECTION_OTHER.
Dianne Hackborn627bba72009-03-24 22:32:56 -07005445 int bin = DATA_CONNECTION_NONE;
5446 if (hasData) {
Tej Singheee317b2018-03-07 19:28:05 -08005447 if (dataType > 0 && dataType <= TelephonyManager.MAX_NETWORK_TYPE) {
5448 bin = dataType;
5449 } else {
5450 bin = DATA_CONNECTION_OTHER;
Dianne Hackborn627bba72009-03-24 22:32:56 -07005451 }
5452 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07005453 if (DEBUG) Log.i(TAG, "Phone Data Connection -> " + dataType + " = " + hasData);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005454 if (mPhoneDataConnectionType != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005455 final long elapsedRealtime = mClocks.elapsedRealtime();
5456 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005457 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_DATA_CONNECTION_MASK)
5458 | (bin << HistoryItem.STATE_DATA_CONNECTION_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005459 if (DEBUG_HISTORY) Slog.v(TAG, "Data connection " + bin + " to: "
5460 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005461 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005462 if (mPhoneDataConnectionType >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005463 mPhoneDataConnectionsTimer[mPhoneDataConnectionType].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005464 elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005465 }
5466 mPhoneDataConnectionType = bin;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005467 mPhoneDataConnectionsTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005468 }
5469 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005470
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005471 public void noteWifiOnLocked() {
The Android Open Source Project10592532009-03-18 17:39:46 -07005472 if (!mWifiOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005473 final long elapsedRealtime = mClocks.elapsedRealtime();
5474 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005475 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005476 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI on to: "
5477 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005478 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005479 mWifiOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005480 mWifiOnTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005481 scheduleSyncExternalStatsLocked("wifi-off", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07005482 }
5483 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005484
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005485 public void noteWifiOffLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08005486 final long elapsedRealtime = mClocks.elapsedRealtime();
5487 final long uptime = mClocks.uptimeMillis();
The Android Open Source Project10592532009-03-18 17:39:46 -07005488 if (mWifiOn) {
Dianne Hackborn3251b902014-06-20 14:40:53 -07005489 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005490 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI off to: "
5491 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005492 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005493 mWifiOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005494 mWifiOnTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005495 scheduleSyncExternalStatsLocked("wifi-on", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07005496 }
5497 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005498
Mathew Inwoodc185f082018-08-20 14:28:54 +01005499 @UnsupportedAppUsage
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005500 public void noteAudioOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005501 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005502 final long elapsedRealtime = mClocks.elapsedRealtime();
5503 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005504 if (mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005505 mHistoryCur.states |= HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005506 if (DEBUG_HISTORY) Slog.v(TAG, "Audio on to: "
5507 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005508 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005509 mAudioOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005510 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005511 mAudioOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005512 getUidStatsLocked(uid).noteAudioTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005513 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005514
Mathew Inwoodc185f082018-08-20 14:28:54 +01005515 @UnsupportedAppUsage
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005516 public void noteAudioOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005517 if (mAudioOnNesting == 0) {
5518 return;
5519 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08005520 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005521 final long elapsedRealtime = mClocks.elapsedRealtime();
5522 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005523 if (--mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005524 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005525 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
5526 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005527 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005528 mAudioOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005529 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005530 getUidStatsLocked(uid).noteAudioTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005531 }
5532
Mathew Inwoodc185f082018-08-20 14:28:54 +01005533 @UnsupportedAppUsage
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005534 public void noteVideoOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005535 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005536 final long elapsedRealtime = mClocks.elapsedRealtime();
5537 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005538 if (mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005539 mHistoryCur.states2 |= HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005540 if (DEBUG_HISTORY) Slog.v(TAG, "Video on to: "
5541 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005542 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005543 mVideoOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005544 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005545 mVideoOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005546 getUidStatsLocked(uid).noteVideoTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005547 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005548
Mathew Inwoodc185f082018-08-20 14:28:54 +01005549 @UnsupportedAppUsage
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005550 public void noteVideoOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005551 if (mVideoOnNesting == 0) {
5552 return;
5553 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08005554 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005555 final long elapsedRealtime = mClocks.elapsedRealtime();
5556 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005557 if (--mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005558 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005559 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
5560 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005561 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005562 mVideoOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005563 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005564 getUidStatsLocked(uid).noteVideoTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005565 }
5566
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005567 public void noteResetAudioLocked() {
5568 if (mAudioOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005569 final long elapsedRealtime = mClocks.elapsedRealtime();
5570 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005571 mAudioOnNesting = 0;
5572 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
5573 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
5574 + Integer.toHexString(mHistoryCur.states));
5575 addHistoryRecordLocked(elapsedRealtime, uptime);
5576 mAudioOnTimer.stopAllRunningLocked(elapsedRealtime);
5577 for (int i=0; i<mUidStats.size(); i++) {
5578 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5579 uid.noteResetAudioLocked(elapsedRealtime);
5580 }
5581 }
5582 }
5583
5584 public void noteResetVideoLocked() {
5585 if (mVideoOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005586 final long elapsedRealtime = mClocks.elapsedRealtime();
5587 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005588 mAudioOnNesting = 0;
5589 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
5590 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
5591 + Integer.toHexString(mHistoryCur.states));
5592 addHistoryRecordLocked(elapsedRealtime, uptime);
5593 mVideoOnTimer.stopAllRunningLocked(elapsedRealtime);
5594 for (int i=0; i<mUidStats.size(); i++) {
5595 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5596 uid.noteResetVideoLocked(elapsedRealtime);
5597 }
5598 }
5599 }
5600
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005601 public void noteActivityResumedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005602 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005603 getUidStatsLocked(uid).noteActivityResumedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005604 }
5605
5606 public void noteActivityPausedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005607 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005608 getUidStatsLocked(uid).noteActivityPausedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005609 }
5610
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005611 public void noteVibratorOnLocked(int uid, long durationMillis) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005612 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005613 getUidStatsLocked(uid).noteVibratorOnLocked(durationMillis);
5614 }
5615
5616 public void noteVibratorOffLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005617 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005618 getUidStatsLocked(uid).noteVibratorOffLocked();
5619 }
5620
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005621 public void noteFlashlightOnLocked(int uid) {
5622 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005623 final long elapsedRealtime = mClocks.elapsedRealtime();
5624 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005625 if (mFlashlightOnNesting++ == 0) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005626 mHistoryCur.states2 |= HistoryItem.STATE2_FLASHLIGHT_FLAG;
5627 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight on to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005628 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005629 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005630 mFlashlightOnTimer.startRunningLocked(elapsedRealtime);
5631 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005632 getUidStatsLocked(uid).noteFlashlightTurnedOnLocked(elapsedRealtime);
5633 }
5634
5635 public void noteFlashlightOffLocked(int uid) {
5636 if (mFlashlightOnNesting == 0) {
5637 return;
5638 }
5639 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005640 final long elapsedRealtime = mClocks.elapsedRealtime();
5641 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005642 if (--mFlashlightOnNesting == 0) {
5643 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
5644 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
5645 + Integer.toHexString(mHistoryCur.states2));
5646 addHistoryRecordLocked(elapsedRealtime, uptime);
5647 mFlashlightOnTimer.stopRunningLocked(elapsedRealtime);
5648 }
5649 getUidStatsLocked(uid).noteFlashlightTurnedOffLocked(elapsedRealtime);
5650 }
5651
5652 public void noteCameraOnLocked(int uid) {
5653 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005654 final long elapsedRealtime = mClocks.elapsedRealtime();
5655 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005656 if (mCameraOnNesting++ == 0) {
5657 mHistoryCur.states2 |= HistoryItem.STATE2_CAMERA_FLAG;
5658 if (DEBUG_HISTORY) Slog.v(TAG, "Camera on to: "
5659 + Integer.toHexString(mHistoryCur.states2));
5660 addHistoryRecordLocked(elapsedRealtime, uptime);
5661 mCameraOnTimer.startRunningLocked(elapsedRealtime);
5662 }
5663 getUidStatsLocked(uid).noteCameraTurnedOnLocked(elapsedRealtime);
5664 }
5665
5666 public void noteCameraOffLocked(int uid) {
5667 if (mCameraOnNesting == 0) {
5668 return;
5669 }
5670 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005671 final long elapsedRealtime = mClocks.elapsedRealtime();
5672 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005673 if (--mCameraOnNesting == 0) {
5674 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
5675 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
5676 + Integer.toHexString(mHistoryCur.states2));
5677 addHistoryRecordLocked(elapsedRealtime, uptime);
5678 mCameraOnTimer.stopRunningLocked(elapsedRealtime);
5679 }
5680 getUidStatsLocked(uid).noteCameraTurnedOffLocked(elapsedRealtime);
5681 }
5682
5683 public void noteResetCameraLocked() {
5684 if (mCameraOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005685 final long elapsedRealtime = mClocks.elapsedRealtime();
5686 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005687 mCameraOnNesting = 0;
5688 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
5689 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
5690 + Integer.toHexString(mHistoryCur.states2));
5691 addHistoryRecordLocked(elapsedRealtime, uptime);
5692 mCameraOnTimer.stopAllRunningLocked(elapsedRealtime);
5693 for (int i=0; i<mUidStats.size(); i++) {
5694 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5695 uid.noteResetCameraLocked(elapsedRealtime);
5696 }
5697 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005698 }
5699
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005700 public void noteResetFlashlightLocked() {
5701 if (mFlashlightOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005702 final long elapsedRealtime = mClocks.elapsedRealtime();
5703 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005704 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005705 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
5706 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005707 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005708 addHistoryRecordLocked(elapsedRealtime, uptime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005709 mFlashlightOnTimer.stopAllRunningLocked(elapsedRealtime);
5710 for (int i=0; i<mUidStats.size(); i++) {
5711 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5712 uid.noteResetFlashlightLocked(elapsedRealtime);
5713 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005714 }
5715 }
5716
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005717 private void noteBluetoothScanStartedLocked(WorkChain workChain, int uid,
5718 boolean isUnoptimized) {
5719 uid = getAttributionUid(uid, workChain);
Bookatz867c0d72017-03-07 18:23:42 -08005720 final long elapsedRealtime = mClocks.elapsedRealtime();
5721 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005722 if (mBluetoothScanNesting == 0) {
5723 mHistoryCur.states2 |= HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5724 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan started for: "
5725 + Integer.toHexString(mHistoryCur.states2));
5726 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005727 mBluetoothScanTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005728 }
5729 mBluetoothScanNesting++;
Bookatzb1f04f32017-05-19 13:57:32 -07005730 getUidStatsLocked(uid).noteBluetoothScanStartedLocked(elapsedRealtime, isUnoptimized);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005731 }
5732
Bookatzb1f04f32017-05-19 13:57:32 -07005733 public void noteBluetoothScanStartedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005734 final int N = ws.size();
5735 for (int i = 0; i < N; i++) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005736 noteBluetoothScanStartedLocked(null, ws.get(i), isUnoptimized);
5737 }
5738
5739 final List<WorkChain> workChains = ws.getWorkChains();
5740 if (workChains != null) {
5741 for (int i = 0; i < workChains.size(); ++i) {
5742 noteBluetoothScanStartedLocked(workChains.get(i), -1, isUnoptimized);
5743 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005744 }
5745 }
5746
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005747 private void noteBluetoothScanStoppedLocked(WorkChain workChain, int uid,
5748 boolean isUnoptimized) {
5749 uid = getAttributionUid(uid, workChain);
Bookatz867c0d72017-03-07 18:23:42 -08005750 final long elapsedRealtime = mClocks.elapsedRealtime();
5751 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005752 mBluetoothScanNesting--;
5753 if (mBluetoothScanNesting == 0) {
5754 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5755 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan stopped for: "
5756 + Integer.toHexString(mHistoryCur.states2));
5757 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005758 mBluetoothScanTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005759 }
Bookatz94c5a312017-07-11 16:49:17 -07005760 getUidStatsLocked(uid).noteBluetoothScanStoppedLocked(elapsedRealtime, isUnoptimized);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005761 }
5762
5763 private int getAttributionUid(int uid, WorkChain workChain) {
5764 if (workChain != null) {
5765 return mapUid(workChain.getAttributionUid());
5766 }
5767
5768 return mapUid(uid);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005769 }
5770
Bookatz94c5a312017-07-11 16:49:17 -07005771 public void noteBluetoothScanStoppedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005772 final int N = ws.size();
5773 for (int i = 0; i < N; i++) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005774 noteBluetoothScanStoppedLocked(null, ws.get(i), isUnoptimized);
5775 }
5776
5777 final List<WorkChain> workChains = ws.getWorkChains();
5778 if (workChains != null) {
5779 for (int i = 0; i < workChains.size(); ++i) {
5780 noteBluetoothScanStoppedLocked(workChains.get(i), -1, isUnoptimized);
5781 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005782 }
5783 }
5784
5785 public void noteResetBluetoothScanLocked() {
5786 if (mBluetoothScanNesting > 0) {
Bookatz867c0d72017-03-07 18:23:42 -08005787 final long elapsedRealtime = mClocks.elapsedRealtime();
5788 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005789 mBluetoothScanNesting = 0;
5790 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5791 if (DEBUG_HISTORY) Slog.v(TAG, "BLE can stopped for: "
5792 + Integer.toHexString(mHistoryCur.states2));
5793 addHistoryRecordLocked(elapsedRealtime, uptime);
5794 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtime);
5795 for (int i=0; i<mUidStats.size(); i++) {
5796 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5797 uid.noteResetBluetoothScanLocked(elapsedRealtime);
5798 }
5799 }
5800 }
5801
Bookatz4ebc0642017-05-11 12:21:19 -07005802 public void noteBluetoothScanResultsFromSourceLocked(WorkSource ws, int numNewResults) {
Bookatz956f36bf2017-04-28 09:48:17 -07005803 final int N = ws.size();
5804 for (int i = 0; i < N; i++) {
5805 int uid = mapUid(ws.get(i));
Bookatz4ebc0642017-05-11 12:21:19 -07005806 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005807 }
5808
5809 final List<WorkChain> workChains = ws.getWorkChains();
5810 if (workChains != null) {
5811 for (int i = 0; i < workChains.size(); ++i) {
5812 final WorkChain wc = workChains.get(i);
5813 int uid = mapUid(wc.getAttributionUid());
5814 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005815 }
Bookatz956f36bf2017-04-28 09:48:17 -07005816 }
5817 }
5818
Adam Lesinski5f056f62016-07-14 16:56:08 -07005819 private void noteWifiRadioApWakeupLocked(final long elapsedRealtimeMillis,
5820 final long uptimeMillis, int uid) {
5821 uid = mapUid(uid);
5822 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
5823 uid);
5824 getUidStatsLocked(uid).noteWifiRadioApWakeupLocked();
5825 }
5826
5827 public void noteWifiRadioPowerState(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005828 final long elapsedRealtime = mClocks.elapsedRealtime();
5829 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005830 if (mWifiRadioPowerState != powerState) {
5831 final boolean active =
5832 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
5833 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
5834 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07005835 if (uid > 0) {
5836 noteWifiRadioApWakeupLocked(elapsedRealtime, uptime, uid);
5837 }
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005838 mHistoryCur.states |= HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
Siddharth Rayb50a6842017-12-14 15:15:28 -08005839 mWifiActiveTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005840 } else {
5841 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
Siddharth Rayb50a6842017-12-14 15:15:28 -08005842 mWifiActiveTimer.stopRunningLocked(
5843 timestampNs / (1000 * 1000));
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005844 }
5845 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi network active " + active + " to: "
5846 + Integer.toHexString(mHistoryCur.states));
5847 addHistoryRecordLocked(elapsedRealtime, uptime);
5848 mWifiRadioPowerState = powerState;
Yangster-mac4c7255f2018-05-07 13:41:47 -07005849 StatsLog.write_non_chained(StatsLog.WIFI_RADIO_POWER_STATE_CHANGED, uid, null,
5850 powerState);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005851 }
5852 }
5853
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005854 public void noteWifiRunningLocked(WorkSource ws) {
5855 if (!mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005856 final long elapsedRealtime = mClocks.elapsedRealtime();
5857 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005858 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005859 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI running to: "
5860 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005861 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005862 mGlobalWifiRunning = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005863 mGlobalWifiRunningTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005864 int N = ws.size();
5865 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005866 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005867 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005868 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005869
5870 List<WorkChain> workChains = ws.getWorkChains();
5871 if (workChains != null) {
5872 for (int i = 0; i < workChains.size(); ++i) {
5873 int uid = mapUid(workChains.get(i).getAttributionUid());
5874 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
5875 }
5876 }
5877
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005878 scheduleSyncExternalStatsLocked("wifi-running", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005879 } else {
5880 Log.w(TAG, "noteWifiRunningLocked -- called while WIFI running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005881 }
5882 }
5883
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005884 public void noteWifiRunningChangedLocked(WorkSource oldWs, WorkSource newWs) {
5885 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005886 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005887 int N = oldWs.size();
5888 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005889 int uid = mapUid(oldWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005890 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005891 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005892
5893 List<WorkChain> workChains = oldWs.getWorkChains();
5894 if (workChains != null) {
5895 for (int i = 0; i < workChains.size(); ++i) {
5896 int uid = mapUid(workChains.get(i).getAttributionUid());
5897 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
5898 }
5899 }
5900
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005901 N = newWs.size();
5902 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005903 int uid = mapUid(newWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005904 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005905 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005906
5907 workChains = newWs.getWorkChains();
5908 if (workChains != null) {
5909 for (int i = 0; i < workChains.size(); ++i) {
5910 int uid = mapUid(workChains.get(i).getAttributionUid());
5911 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
5912 }
5913 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005914 } else {
5915 Log.w(TAG, "noteWifiRunningChangedLocked -- called while WIFI not running");
5916 }
5917 }
5918
5919 public void noteWifiStoppedLocked(WorkSource ws) {
5920 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005921 final long elapsedRealtime = mClocks.elapsedRealtime();
5922 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005923 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005924 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI stopped to: "
5925 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005926 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005927 mGlobalWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005928 mGlobalWifiRunningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005929 int N = ws.size();
5930 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005931 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005932 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005933 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005934
5935 List<WorkChain> workChains = ws.getWorkChains();
5936 if (workChains != null) {
5937 for (int i = 0; i < workChains.size(); ++i) {
5938 int uid = mapUid(workChains.get(i).getAttributionUid());
5939 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
5940 }
5941 }
5942
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005943 scheduleSyncExternalStatsLocked("wifi-stopped", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005944 } else {
5945 Log.w(TAG, "noteWifiStoppedLocked -- called while WIFI not running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005946 }
5947 }
5948
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005949 public void noteWifiStateLocked(int wifiState, String accessPoint) {
5950 if (DEBUG) Log.i(TAG, "WiFi state -> " + wifiState);
5951 if (mWifiState != wifiState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005952 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005953 if (mWifiState >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005954 mWifiStateTimer[mWifiState].stopRunningLocked(elapsedRealtime);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005955 }
5956 mWifiState = wifiState;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005957 mWifiStateTimer[wifiState].startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005958 scheduleSyncExternalStatsLocked("wifi-state", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005959 }
5960 }
5961
Dianne Hackborn3251b902014-06-20 14:40:53 -07005962 public void noteWifiSupplicantStateChangedLocked(int supplState, boolean failedAuth) {
5963 if (DEBUG) Log.i(TAG, "WiFi suppl state -> " + supplState);
5964 if (mWifiSupplState != supplState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005965 final long elapsedRealtime = mClocks.elapsedRealtime();
5966 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005967 if (mWifiSupplState >= 0) {
5968 mWifiSupplStateTimer[mWifiSupplState].stopRunningLocked(elapsedRealtime);
5969 }
5970 mWifiSupplState = supplState;
5971 mWifiSupplStateTimer[supplState].startRunningLocked(elapsedRealtime);
5972 mHistoryCur.states2 =
5973 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SUPPL_STATE_MASK)
5974 | (supplState << HistoryItem.STATE2_WIFI_SUPPL_STATE_SHIFT);
5975 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi suppl state " + supplState + " to: "
5976 + Integer.toHexString(mHistoryCur.states2));
5977 addHistoryRecordLocked(elapsedRealtime, uptime);
5978 }
5979 }
5980
5981 void stopAllWifiSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005982 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005983 for (int i = 0; i < NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
5984 if (i == except) {
5985 continue;
5986 }
5987 while (mWifiSignalStrengthsTimer[i].isRunningLocked()) {
5988 mWifiSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
5989 }
5990 }
5991 }
5992
5993 public void noteWifiRssiChangedLocked(int newRssi) {
5994 int strengthBin = WifiManager.calculateSignalLevel(newRssi, NUM_WIFI_SIGNAL_STRENGTH_BINS);
5995 if (DEBUG) Log.i(TAG, "WiFi rssi -> " + newRssi + " bin=" + strengthBin);
5996 if (mWifiSignalStrengthBin != strengthBin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005997 final long elapsedRealtime = mClocks.elapsedRealtime();
5998 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005999 if (mWifiSignalStrengthBin >= 0) {
6000 mWifiSignalStrengthsTimer[mWifiSignalStrengthBin].stopRunningLocked(
6001 elapsedRealtime);
6002 }
6003 if (strengthBin >= 0) {
6004 if (!mWifiSignalStrengthsTimer[strengthBin].isRunningLocked()) {
6005 mWifiSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
6006 }
6007 mHistoryCur.states2 =
6008 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_MASK)
6009 | (strengthBin << HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_SHIFT);
6010 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi signal strength " + strengthBin + " to: "
6011 + Integer.toHexString(mHistoryCur.states2));
6012 addHistoryRecordLocked(elapsedRealtime, uptime);
6013 } else {
6014 stopAllWifiSignalStrengthTimersLocked(-1);
6015 }
Bookatz235343d2018-03-26 13:03:50 -07006016 StatsLog.write(StatsLog.WIFI_SIGNAL_STRENGTH_CHANGED, strengthBin);
Dianne Hackborn3251b902014-06-20 14:40:53 -07006017 mWifiSignalStrengthBin = strengthBin;
6018 }
6019 }
6020
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006021 int mWifiFullLockNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006022
Mathew Inwoodc185f082018-08-20 14:28:54 +01006023 @UnsupportedAppUsage
The Android Open Source Project10592532009-03-18 17:39:46 -07006024 public void noteFullWifiLockAcquiredLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006025 final long elapsedRealtime = mClocks.elapsedRealtime();
6026 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006027 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006028 mHistoryCur.states |= HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006029 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock on to: "
6030 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006031 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006032 }
6033 mWifiFullLockNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006034 getUidStatsLocked(uid).noteFullWifiLockAcquiredLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006035 }
6036
Mathew Inwoodc185f082018-08-20 14:28:54 +01006037 @UnsupportedAppUsage
The Android Open Source Project10592532009-03-18 17:39:46 -07006038 public void noteFullWifiLockReleasedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006039 final long elapsedRealtime = mClocks.elapsedRealtime();
6040 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006041 mWifiFullLockNesting--;
6042 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006043 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006044 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock off to: "
6045 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006046 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006047 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006048 getUidStatsLocked(uid).noteFullWifiLockReleasedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006049 }
6050
Nick Pelly6ccaa542012-06-15 15:22:47 -07006051 int mWifiScanNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006052
Nick Pelly6ccaa542012-06-15 15:22:47 -07006053 public void noteWifiScanStartedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006054 final long elapsedRealtime = mClocks.elapsedRealtime();
6055 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07006056 if (mWifiScanNesting == 0) {
6057 mHistoryCur.states |= HistoryItem.STATE_WIFI_SCAN_FLAG;
6058 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan started for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006059 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006060 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006061 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07006062 mWifiScanNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006063 getUidStatsLocked(uid).noteWifiScanStartedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006064 }
6065
Nick Pelly6ccaa542012-06-15 15:22:47 -07006066 public void noteWifiScanStoppedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006067 final long elapsedRealtime = mClocks.elapsedRealtime();
6068 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07006069 mWifiScanNesting--;
6070 if (mWifiScanNesting == 0) {
6071 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_SCAN_FLAG;
6072 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan stopped for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006073 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006074 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006075 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006076 getUidStatsLocked(uid).noteWifiScanStoppedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006077 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006078
Robert Greenwalta029ea12013-09-25 16:38:12 -07006079 public void noteWifiBatchedScanStartedLocked(int uid, int csph) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006080 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006081 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006082 getUidStatsLocked(uid).noteWifiBatchedScanStartedLocked(csph, elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006083 }
6084
6085 public void noteWifiBatchedScanStoppedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006086 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006087 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006088 getUidStatsLocked(uid).noteWifiBatchedScanStoppedLocked(elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006089 }
6090
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006091 int mWifiMulticastNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006092
Mathew Inwoodc185f082018-08-20 14:28:54 +01006093 @UnsupportedAppUsage
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006094 public void noteWifiMulticastEnabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006095 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006096 final long elapsedRealtime = mClocks.elapsedRealtime();
6097 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006098 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006099 mHistoryCur.states |= HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006100 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast on to: "
6101 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006102 addHistoryRecordLocked(elapsedRealtime, uptime);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006103
6104 // Start Wifi Multicast overall timer
6105 if (!mWifiMulticastWakelockTimer.isRunningLocked()) {
6106 if (DEBUG_HISTORY) Slog.v(TAG, "WiFi Multicast Overall Timer Started");
6107 mWifiMulticastWakelockTimer.startRunningLocked(elapsedRealtime);
6108 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006109 }
6110 mWifiMulticastNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006111 getUidStatsLocked(uid).noteWifiMulticastEnabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006112 }
6113
Mathew Inwoodc185f082018-08-20 14:28:54 +01006114 @UnsupportedAppUsage
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006115 public void noteWifiMulticastDisabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006116 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006117 final long elapsedRealtime = mClocks.elapsedRealtime();
6118 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006119 mWifiMulticastNesting--;
6120 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006121 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006122 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast off to: "
6123 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006124 addHistoryRecordLocked(elapsedRealtime, uptime);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006125
6126 // Stop Wifi Multicast overall timer
6127 if (mWifiMulticastWakelockTimer.isRunningLocked()) {
6128 if (DEBUG_HISTORY) Slog.v(TAG, "Multicast Overall Timer Stopped");
6129 mWifiMulticastWakelockTimer.stopRunningLocked(elapsedRealtime);
6130 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006131 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006132 getUidStatsLocked(uid).noteWifiMulticastDisabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006133 }
6134
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006135 public void noteFullWifiLockAcquiredFromSourceLocked(WorkSource ws) {
6136 int N = ws.size();
6137 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006138 final int uid = mapUid(ws.get(i));
6139 noteFullWifiLockAcquiredLocked(uid);
Bookatz90867622018-01-31 15:05:57 -08006140 StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, ws.get(i), ws.getName(i),
6141 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006142 }
6143
6144 final List<WorkChain> workChains = ws.getWorkChains();
6145 if (workChains != null) {
6146 for (int i = 0; i < workChains.size(); ++i) {
6147 final WorkChain workChain = workChains.get(i);
6148 final int uid = mapUid(workChain.getAttributionUid());
6149 noteFullWifiLockAcquiredLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006150 StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006151 workChain.getUids(), workChain.getTags(),
6152 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006153 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006154 }
6155 }
6156
6157 public void noteFullWifiLockReleasedFromSourceLocked(WorkSource ws) {
6158 int N = ws.size();
6159 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006160 final int uid = mapUid(ws.get(i));
6161 noteFullWifiLockReleasedLocked(uid);
Bookatz90867622018-01-31 15:05:57 -08006162 StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, ws.get(i), ws.getName(i),
6163 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006164 }
6165
6166 final List<WorkChain> workChains = ws.getWorkChains();
6167 if (workChains != null) {
6168 for (int i = 0; i < workChains.size(); ++i) {
6169 final WorkChain workChain = workChains.get(i);
6170 final int uid = mapUid(workChain.getAttributionUid());
6171 noteFullWifiLockReleasedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006172 StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006173 workChain.getUids(), workChain.getTags(),
6174 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006175 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006176 }
6177 }
6178
Nick Pelly6ccaa542012-06-15 15:22:47 -07006179 public void noteWifiScanStartedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006180 int N = ws.size();
6181 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006182 final int uid = mapUid(ws.get(i));
6183 noteWifiScanStartedLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08006184 StatsLog.write_non_chained(StatsLog.WIFI_SCAN_STATE_CHANGED, ws.get(i), ws.getName(i),
Bookatz90867622018-01-31 15:05:57 -08006185 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006186 }
6187
6188 final List<WorkChain> workChains = ws.getWorkChains();
6189 if (workChains != null) {
6190 for (int i = 0; i < workChains.size(); ++i) {
6191 final WorkChain workChain = workChains.get(i);
6192 final int uid = mapUid(workChain.getAttributionUid());
6193 noteWifiScanStartedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006194 StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED, workChain.getUids(),
Bookatz90867622018-01-31 15:05:57 -08006195 workChain.getTags(), StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006196 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006197 }
6198 }
6199
Nick Pelly6ccaa542012-06-15 15:22:47 -07006200 public void noteWifiScanStoppedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006201 int N = ws.size();
6202 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006203 final int uid = mapUid(ws.get(i));
6204 noteWifiScanStoppedLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08006205 StatsLog.write_non_chained(StatsLog.WIFI_SCAN_STATE_CHANGED, ws.get(i), ws.getName(i),
Bookatz90867622018-01-31 15:05:57 -08006206 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006207 }
6208
6209 final List<WorkChain> workChains = ws.getWorkChains();
6210 if (workChains != null) {
6211 for (int i = 0; i < workChains.size(); ++i) {
6212 final WorkChain workChain = workChains.get(i);
6213 final int uid = mapUid(workChain.getAttributionUid());
6214 noteWifiScanStoppedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006215 StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006216 workChain.getUids(), workChain.getTags(),
6217 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006218 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006219 }
6220 }
6221
Robert Greenwalta029ea12013-09-25 16:38:12 -07006222 public void noteWifiBatchedScanStartedFromSourceLocked(WorkSource ws, int csph) {
6223 int N = ws.size();
6224 for (int i=0; i<N; i++) {
6225 noteWifiBatchedScanStartedLocked(ws.get(i), csph);
6226 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00006227
6228 final List<WorkChain> workChains = ws.getWorkChains();
6229 if (workChains != null) {
6230 for (int i = 0; i < workChains.size(); ++i) {
6231 noteWifiBatchedScanStartedLocked(workChains.get(i).getAttributionUid(), csph);
6232 }
6233 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006234 }
6235
6236 public void noteWifiBatchedScanStoppedFromSourceLocked(WorkSource ws) {
6237 int N = ws.size();
6238 for (int i=0; i<N; i++) {
6239 noteWifiBatchedScanStoppedLocked(ws.get(i));
6240 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00006241
6242 final List<WorkChain> workChains = ws.getWorkChains();
6243 if (workChains != null) {
6244 for (int i = 0; i < workChains.size(); ++i) {
6245 noteWifiBatchedScanStoppedLocked(workChains.get(i).getAttributionUid());
6246 }
6247 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006248 }
6249
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08006250 private static String[] includeInStringArray(String[] array, String str) {
6251 if (ArrayUtils.indexOf(array, str) >= 0) {
6252 return array;
6253 }
6254 String[] newArray = new String[array.length+1];
6255 System.arraycopy(array, 0, newArray, 0, array.length);
6256 newArray[array.length] = str;
6257 return newArray;
6258 }
6259
6260 private static String[] excludeFromStringArray(String[] array, String str) {
6261 int index = ArrayUtils.indexOf(array, str);
6262 if (index >= 0) {
6263 String[] newArray = new String[array.length-1];
6264 if (index > 0) {
6265 System.arraycopy(array, 0, newArray, 0, index);
6266 }
6267 if (index < array.length-1) {
6268 System.arraycopy(array, index+1, newArray, index, array.length-index-1);
6269 }
6270 return newArray;
6271 }
6272 return array;
6273 }
6274
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07006275 public void noteNetworkInterfaceTypeLocked(String iface, int networkType) {
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07006276 if (TextUtils.isEmpty(iface)) return;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006277
Adam Lesinski14ae39a2017-05-26 11:50:40 -07006278 synchronized (mModemNetworkLock) {
6279 if (ConnectivityManager.isNetworkTypeMobile(networkType)) {
6280 mModemIfaces = includeInStringArray(mModemIfaces, iface);
6281 if (DEBUG) Slog.d(TAG, "Note mobile iface " + iface + ": " + mModemIfaces);
6282 } else {
6283 mModemIfaces = excludeFromStringArray(mModemIfaces, iface);
6284 if (DEBUG) Slog.d(TAG, "Note non-mobile iface " + iface + ": " + mModemIfaces);
6285 }
6286 }
6287
6288 synchronized (mWifiNetworkLock) {
6289 if (ConnectivityManager.isNetworkTypeWifi(networkType)) {
6290 mWifiIfaces = includeInStringArray(mWifiIfaces, iface);
6291 if (DEBUG) Slog.d(TAG, "Note wifi iface " + iface + ": " + mWifiIfaces);
6292 } else {
6293 mWifiIfaces = excludeFromStringArray(mWifiIfaces, iface);
6294 if (DEBUG) Slog.d(TAG, "Note non-wifi iface " + iface + ": " + mWifiIfaces);
6295 }
6296 }
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07006297 }
6298
David Chenc8a43242017-10-17 16:23:28 -07006299 public String[] getWifiIfaces() {
6300 synchronized (mWifiNetworkLock) {
6301 return mWifiIfaces;
6302 }
6303 }
6304
6305 public String[] getMobileIfaces() {
6306 synchronized (mModemNetworkLock) {
6307 return mModemIfaces;
6308 }
6309 }
6310
Mathew Inwoodc185f082018-08-20 14:28:54 +01006311 @UnsupportedAppUsage
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006312 @Override public long getScreenOnTime(long elapsedRealtimeUs, int which) {
6313 return mScreenOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006314 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006315
Dianne Hackborn77b987f2014-02-26 16:20:52 -08006316 @Override public int getScreenOnCount(int which) {
6317 return mScreenOnTimer.getCountLocked(which);
6318 }
6319
Mike Mac2f518a2017-09-19 16:06:03 -07006320 @Override public long getScreenDozeTime(long elapsedRealtimeUs, int which) {
6321 return mScreenDozeTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6322 }
6323
6324 @Override public int getScreenDozeCount(int which) {
6325 return mScreenDozeTimer.getCountLocked(which);
6326 }
6327
Mathew Inwoodc185f082018-08-20 14:28:54 +01006328 @UnsupportedAppUsage
Dianne Hackborn617f8772009-03-31 15:04:46 -07006329 @Override public long getScreenBrightnessTime(int brightnessBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006330 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006331 return mScreenBrightnessTimer[brightnessBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006332 elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006333 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006334
Kweku Adams87b19ec2017-10-09 12:40:03 -07006335 @Override public Timer getScreenBrightnessTimer(int brightnessBin) {
6336 return mScreenBrightnessTimer[brightnessBin];
6337 }
6338
Jeff Browne95c3cd2014-05-02 16:59:26 -07006339 @Override public long getInteractiveTime(long elapsedRealtimeUs, int which) {
6340 return mInteractiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006341 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006342
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006343 @Override public long getPowerSaveModeEnabledTime(long elapsedRealtimeUs, int which) {
6344 return mPowerSaveModeEnabledTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07006345 }
6346
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006347 @Override public int getPowerSaveModeEnabledCount(int which) {
6348 return mPowerSaveModeEnabledTimer.getCountLocked(which);
6349 }
6350
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006351 @Override public long getDeviceIdleModeTime(int mode, long elapsedRealtimeUs,
6352 int which) {
6353 switch (mode) {
6354 case DEVICE_IDLE_MODE_LIGHT:
6355 return mDeviceIdleModeLightTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006356 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006357 return mDeviceIdleModeFullTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6358 }
6359 return 0;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006360 }
6361
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006362 @Override public int getDeviceIdleModeCount(int mode, int which) {
6363 switch (mode) {
6364 case DEVICE_IDLE_MODE_LIGHT:
6365 return mDeviceIdleModeLightTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006366 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006367 return mDeviceIdleModeFullTimer.getCountLocked(which);
6368 }
6369 return 0;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07006370 }
6371
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006372 @Override public long getLongestDeviceIdleModeTime(int mode) {
6373 switch (mode) {
6374 case DEVICE_IDLE_MODE_LIGHT:
6375 return mLongestLightIdleTime;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006376 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006377 return mLongestFullIdleTime;
6378 }
6379 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07006380 }
6381
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006382 @Override public long getDeviceIdlingTime(int mode, long elapsedRealtimeUs, int which) {
6383 switch (mode) {
6384 case DEVICE_IDLE_MODE_LIGHT:
6385 return mDeviceLightIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006386 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006387 return mDeviceIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6388 }
6389 return 0;
6390 }
6391
6392 @Override public int getDeviceIdlingCount(int mode, int which) {
6393 switch (mode) {
6394 case DEVICE_IDLE_MODE_LIGHT:
6395 return mDeviceLightIdlingTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006396 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006397 return mDeviceIdlingTimer.getCountLocked(which);
6398 }
6399 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07006400 }
6401
Dianne Hackborn1e01d162014-12-04 17:46:42 -08006402 @Override public int getNumConnectivityChange(int which) {
6403 int val = mNumConnectivityChange;
6404 if (which == STATS_CURRENT) {
6405 val -= mLoadedNumConnectivityChange;
6406 } else if (which == STATS_SINCE_UNPLUGGED) {
6407 val -= mUnpluggedNumConnectivityChange;
6408 }
6409 return val;
6410 }
6411
Siddharth Ray78ccaf52017-12-23 16:16:21 -08006412 @Override public long getGpsSignalQualityTime(int strengthBin,
6413 long elapsedRealtimeUs, int which) {
6414 if (strengthBin < 0 || strengthBin >= GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS) {
6415 return 0;
6416 }
6417 return mGpsSignalQualityTimer[strengthBin].getTotalTimeLocked(
6418 elapsedRealtimeUs, which);
6419 }
6420
6421 @Override public long getGpsBatteryDrainMaMs() {
Siddharth Ray0ed2e952018-01-22 11:32:14 -08006422 final double opVolt = mPowerProfile.getAveragePower(
6423 PowerProfile.POWER_GPS_OPERATING_VOLTAGE) / 1000.0;
6424 if (opVolt == 0) {
6425 return 0;
6426 }
6427 double energyUsedMaMs = 0.0;
6428 final int which = STATS_SINCE_CHARGED;
6429 final long rawRealtime = SystemClock.elapsedRealtime() * 1000;
6430 for(int i=0; i < GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
6431 energyUsedMaMs
6432 += mPowerProfile.getAveragePower(PowerProfile.POWER_GPS_SIGNAL_QUALITY_BASED, i)
6433 * (getGpsSignalQualityTime(i, rawRealtime, which) / 1000);
6434 }
6435 return (long) energyUsedMaMs;
Siddharth Ray78ccaf52017-12-23 16:16:21 -08006436 }
6437
Mathew Inwoodc185f082018-08-20 14:28:54 +01006438 @UnsupportedAppUsage
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006439 @Override public long getPhoneOnTime(long elapsedRealtimeUs, int which) {
6440 return mPhoneOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006441 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006442
Dianne Hackborn77b987f2014-02-26 16:20:52 -08006443 @Override public int getPhoneOnCount(int which) {
6444 return mPhoneOnTimer.getCountLocked(which);
6445 }
6446
Mathew Inwoodc185f082018-08-20 14:28:54 +01006447 @UnsupportedAppUsage
Dianne Hackborn627bba72009-03-24 22:32:56 -07006448 @Override public long getPhoneSignalStrengthTime(int strengthBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006449 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006450 return mPhoneSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006451 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07006452 }
Amith Yamasanif37447b2009-10-08 18:28:01 -07006453
Mathew Inwoodc185f082018-08-20 14:28:54 +01006454 @UnsupportedAppUsage
Amith Yamasanif37447b2009-10-08 18:28:01 -07006455 @Override public long getPhoneSignalScanningTime(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006456 long elapsedRealtimeUs, int which) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07006457 return mPhoneSignalScanningTimer.getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006458 elapsedRealtimeUs, which);
Amith Yamasanif37447b2009-10-08 18:28:01 -07006459 }
6460
Kweku Adams87b19ec2017-10-09 12:40:03 -07006461 @Override public Timer getPhoneSignalScanningTimer() {
6462 return mPhoneSignalScanningTimer;
6463 }
6464
Mathew Inwoodc185f082018-08-20 14:28:54 +01006465 @UnsupportedAppUsage
Catherine Liufb900812012-07-17 14:12:56 -05006466 @Override public int getPhoneSignalStrengthCount(int strengthBin, int which) {
6467 return mPhoneSignalStrengthsTimer[strengthBin].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006468 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006469
Kweku Adams87b19ec2017-10-09 12:40:03 -07006470 @Override public Timer getPhoneSignalStrengthTimer(int strengthBin) {
6471 return mPhoneSignalStrengthsTimer[strengthBin];
6472 }
6473
Mathew Inwoodc185f082018-08-20 14:28:54 +01006474 @UnsupportedAppUsage
Dianne Hackborn627bba72009-03-24 22:32:56 -07006475 @Override public long getPhoneDataConnectionTime(int dataType,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006476 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006477 return mPhoneDataConnectionsTimer[dataType].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006478 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07006479 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006480
Mathew Inwoodc185f082018-08-20 14:28:54 +01006481 @UnsupportedAppUsage
Dianne Hackborn617f8772009-03-31 15:04:46 -07006482 @Override public int getPhoneDataConnectionCount(int dataType, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006483 return mPhoneDataConnectionsTimer[dataType].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006484 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006485
Kweku Adams87b19ec2017-10-09 12:40:03 -07006486 @Override public Timer getPhoneDataConnectionTimer(int dataType) {
6487 return mPhoneDataConnectionsTimer[dataType];
6488 }
6489
Mathew Inwoodc185f082018-08-20 14:28:54 +01006490 @UnsupportedAppUsage
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006491 @Override public long getMobileRadioActiveTime(long elapsedRealtimeUs, int which) {
6492 return mMobileRadioActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborne13c4c02014-02-11 17:18:35 -08006493 }
6494
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006495 @Override public int getMobileRadioActiveCount(int which) {
6496 return mMobileRadioActiveTimer.getCountLocked(which);
6497 }
6498
Dianne Hackborna1bd7922014-03-21 11:07:11 -07006499 @Override public long getMobileRadioActiveAdjustedTime(int which) {
6500 return mMobileRadioActiveAdjustedTime.getCountLocked(which);
6501 }
6502
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006503 @Override public long getMobileRadioActiveUnknownTime(int which) {
6504 return mMobileRadioActiveUnknownTime.getCountLocked(which);
6505 }
6506
6507 @Override public int getMobileRadioActiveUnknownCount(int which) {
6508 return (int)mMobileRadioActiveUnknownCount.getCountLocked(which);
6509 }
6510
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006511 @Override public long getWifiMulticastWakelockTime(
6512 long elapsedRealtimeUs, int which) {
6513 return mWifiMulticastWakelockTimer.getTotalTimeLocked(
6514 elapsedRealtimeUs, which);
6515 }
6516
6517 @Override public int getWifiMulticastWakelockCount(int which) {
6518 return mWifiMulticastWakelockTimer.getCountLocked(which);
6519 }
6520
Mathew Inwoodc185f082018-08-20 14:28:54 +01006521 @UnsupportedAppUsage
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006522 @Override public long getWifiOnTime(long elapsedRealtimeUs, int which) {
6523 return mWifiOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07006524 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006525
Siddharth Rayb50a6842017-12-14 15:15:28 -08006526 @Override public long getWifiActiveTime(long elapsedRealtimeUs, int which) {
6527 return mWifiActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6528 }
6529
Mathew Inwoodc185f082018-08-20 14:28:54 +01006530 @UnsupportedAppUsage
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006531 @Override public long getGlobalWifiRunningTime(long elapsedRealtimeUs, int which) {
6532 return mGlobalWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07006533 }
6534
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006535 @Override public long getWifiStateTime(int wifiState,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006536 long elapsedRealtimeUs, int which) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006537 return mWifiStateTimer[wifiState].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006538 elapsedRealtimeUs, which);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006539 }
6540
6541 @Override public int getWifiStateCount(int wifiState, int which) {
6542 return mWifiStateTimer[wifiState].getCountLocked(which);
6543 }
6544
Kweku Adams87b19ec2017-10-09 12:40:03 -07006545 @Override public Timer getWifiStateTimer(int wifiState) {
6546 return mWifiStateTimer[wifiState];
6547 }
6548
Dianne Hackborn3251b902014-06-20 14:40:53 -07006549 @Override public long getWifiSupplStateTime(int state,
6550 long elapsedRealtimeUs, int which) {
6551 return mWifiSupplStateTimer[state].getTotalTimeLocked(
6552 elapsedRealtimeUs, which);
6553 }
6554
6555 @Override public int getWifiSupplStateCount(int state, int which) {
6556 return mWifiSupplStateTimer[state].getCountLocked(which);
6557 }
6558
Kweku Adams87b19ec2017-10-09 12:40:03 -07006559 @Override public Timer getWifiSupplStateTimer(int state) {
6560 return mWifiSupplStateTimer[state];
6561 }
6562
Dianne Hackborn3251b902014-06-20 14:40:53 -07006563 @Override public long getWifiSignalStrengthTime(int strengthBin,
6564 long elapsedRealtimeUs, int which) {
6565 return mWifiSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
6566 elapsedRealtimeUs, which);
6567 }
6568
6569 @Override public int getWifiSignalStrengthCount(int strengthBin, int which) {
6570 return mWifiSignalStrengthsTimer[strengthBin].getCountLocked(which);
6571 }
6572
Kweku Adams87b19ec2017-10-09 12:40:03 -07006573 @Override public Timer getWifiSignalStrengthTimer(int strengthBin) {
6574 return mWifiSignalStrengthsTimer[strengthBin];
6575 }
6576
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006577 @Override
6578 public ControllerActivityCounter getBluetoothControllerActivity() {
6579 return mBluetoothActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07006580 }
6581
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006582 @Override
6583 public ControllerActivityCounter getWifiControllerActivity() {
6584 return mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -07006585 }
6586
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006587 @Override
6588 public ControllerActivityCounter getModemControllerActivity() {
6589 return mModemActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07006590 }
6591
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006592 @Override
6593 public boolean hasBluetoothActivityReporting() {
6594 return mHasBluetoothReporting;
6595 }
6596
6597 @Override
6598 public boolean hasWifiActivityReporting() {
6599 return mHasWifiReporting;
6600 }
6601
6602 @Override
6603 public boolean hasModemActivityReporting() {
6604 return mHasModemReporting;
Adam Lesinski33dac552015-03-09 15:24:48 -07006605 }
6606
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006607 @Override
6608 public long getFlashlightOnTime(long elapsedRealtimeUs, int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07006609 return mFlashlightOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6610 }
6611
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006612 @Override
6613 public long getFlashlightOnCount(int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07006614 return mFlashlightOnTimer.getCountLocked(which);
6615 }
6616
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006617 @Override
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006618 public long getCameraOnTime(long elapsedRealtimeUs, int which) {
6619 return mCameraOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6620 }
6621
6622 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006623 public long getBluetoothScanTime(long elapsedRealtimeUs, int which) {
6624 return mBluetoothScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6625 }
6626
6627 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01006628 @UnsupportedAppUsage
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006629 public long getNetworkActivityBytes(int type, int which) {
6630 if (type >= 0 && type < mNetworkByteActivityCounters.length) {
6631 return mNetworkByteActivityCounters[type].getCountLocked(which);
6632 } else {
6633 return 0;
6634 }
6635 }
6636
6637 @Override
6638 public long getNetworkActivityPackets(int type, int which) {
6639 if (type >= 0 && type < mNetworkPacketActivityCounters.length) {
6640 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006641 } else {
6642 return 0;
6643 }
6644 }
6645
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08006646 @Override public long getStartClockTime() {
Dianne Hackbornd48954f2015-07-22 17:20:33 -07006647 final long currentTime = System.currentTimeMillis();
6648 if (ensureStartClockTime(currentTime)) {
Joe Onoratoabded112016-02-08 16:49:39 -08006649 recordCurrentTimeChangeLocked(currentTime, mClocks.elapsedRealtime(),
6650 mClocks.uptimeMillis());
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07006651 }
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08006652 return mStartClockTime;
6653 }
6654
Dianne Hackborncd0e3352014-08-07 17:08:09 -07006655 @Override public String getStartPlatformVersion() {
6656 return mStartPlatformVersion;
6657 }
6658
6659 @Override public String getEndPlatformVersion() {
6660 return mEndPlatformVersion;
6661 }
6662
6663 @Override public int getParcelVersion() {
6664 return VERSION;
6665 }
6666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006667 @Override public boolean getIsOnBattery() {
6668 return mOnBattery;
6669 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006670
Mathew Inwoodc185f082018-08-20 14:28:54 +01006671 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006672 @Override public SparseArray<? extends BatteryStats.Uid> getUidStats() {
6673 return mUidStats;
6674 }
6675
Adam Lesinski5f056f62016-07-14 16:56:08 -07006676 private static void detachTimerIfNotNull(BatteryStatsImpl.Timer timer) {
6677 if (timer != null) {
6678 timer.detach();
6679 }
6680 }
6681
6682 private static boolean resetTimerIfNotNull(BatteryStatsImpl.Timer timer,
6683 boolean detachIfReset) {
6684 if (timer != null) {
6685 return timer.reset(detachIfReset);
6686 }
6687 return true;
6688 }
6689
Bookatz867c0d72017-03-07 18:23:42 -08006690 private static boolean resetTimerIfNotNull(DualTimer timer, boolean detachIfReset) {
6691 if (timer != null) {
6692 return timer.reset(detachIfReset);
6693 }
6694 return true;
6695 }
6696
Adam Lesinski5f056f62016-07-14 16:56:08 -07006697 private static void detachLongCounterIfNotNull(LongSamplingCounter counter) {
6698 if (counter != null) {
6699 counter.detach();
6700 }
6701 }
6702
6703 private static void resetLongCounterIfNotNull(LongSamplingCounter counter,
6704 boolean detachIfReset) {
6705 if (counter != null) {
6706 counter.reset(detachIfReset);
6707 }
6708 }
6709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006710 /**
6711 * The statistics associated with a particular uid.
6712 */
Joe Onoratoabded112016-02-08 16:49:39 -08006713 public static class Uid extends BatteryStats.Uid {
6714 /**
6715 * BatteryStatsImpl that we are associated with.
6716 */
6717 protected BatteryStatsImpl mBsi;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006719 final int mUid;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006720
Bookatz867c0d72017-03-07 18:23:42 -08006721 /** TimeBase for when uid is in background and device is on battery. */
6722 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6723 public final TimeBase mOnBatteryBackgroundTimeBase;
Bookatzc8c44962017-05-11 12:12:54 -07006724 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6725 public final TimeBase mOnBatteryScreenOffBackgroundTimeBase;
Bookatz867c0d72017-03-07 18:23:42 -08006726
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006727 boolean mWifiRunning;
6728 StopwatchTimer mWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006729
The Android Open Source Project10592532009-03-18 17:39:46 -07006730 boolean mFullWifiLockOut;
Evan Millarc64edde2009-04-18 12:26:32 -07006731 StopwatchTimer mFullWifiLockTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006732
Nick Pelly6ccaa542012-06-15 15:22:47 -07006733 boolean mWifiScanStarted;
Bookatz867c0d72017-03-07 18:23:42 -08006734 DualTimer mWifiScanTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006735
Dianne Hackborn61659e52014-07-09 16:13:01 -07006736 static final int NO_BATCHED_SCAN_STARTED = -1;
Robert Greenwalta029ea12013-09-25 16:38:12 -07006737 int mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
6738 StopwatchTimer[] mWifiBatchedScanTimer;
6739
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006740 boolean mWifiMulticastEnabled;
6741 StopwatchTimer mWifiMulticastTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006742
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006743 StopwatchTimer mAudioTurnedOnTimer;
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006744 StopwatchTimer mVideoTurnedOnTimer;
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006745 StopwatchTimer mFlashlightTurnedOnTimer;
6746 StopwatchTimer mCameraTurnedOnTimer;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006747 StopwatchTimer mForegroundActivityTimer;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006748 StopwatchTimer mForegroundServiceTimer;
Bookatzc8c44962017-05-11 12:12:54 -07006749 /** Total time spent by the uid holding any partial wakelocks. */
6750 DualTimer mAggregatedPartialWakelockTimer;
Bookatz867c0d72017-03-07 18:23:42 -08006751 DualTimer mBluetoothScanTimer;
Bookatzb1f04f32017-05-19 13:57:32 -07006752 DualTimer mBluetoothUnoptimizedScanTimer;
Bookatz956f36bf2017-04-28 09:48:17 -07006753 Counter mBluetoothScanResultCounter;
Bookatzb1f04f32017-05-19 13:57:32 -07006754 Counter mBluetoothScanResultBgCounter;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006755
Dianne Hackborna8d10942015-11-19 17:55:19 -08006756 int mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07006757 StopwatchTimer[] mProcessStateTimer;
6758
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006759 boolean mInForegroundService = false;
6760
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006761 BatchTimer mVibratorOnTimer;
6762
Dianne Hackborn617f8772009-03-31 15:04:46 -07006763 Counter[] mUserActivityCounters;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006764
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006765 LongSamplingCounter[] mNetworkByteActivityCounters;
6766 LongSamplingCounter[] mNetworkPacketActivityCounters;
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006767 LongSamplingCounter mMobileRadioActiveTime;
6768 LongSamplingCounter mMobileRadioActiveCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006770 /**
Adam Lesinski5f056f62016-07-14 16:56:08 -07006771 * How many times this UID woke up the Application Processor due to a Mobile radio packet.
6772 */
6773 private LongSamplingCounter mMobileRadioApWakeupCount;
6774
6775 /**
6776 * How many times this UID woke up the Application Processor due to a Wifi packet.
6777 */
6778 private LongSamplingCounter mWifiRadioApWakeupCount;
6779
6780 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07006781 * The amount of time this uid has kept the WiFi controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006782 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07006783 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006784 private ControllerActivityCounterImpl mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006785
6786 /**
6787 * The amount of time this uid has kept the Bluetooth controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006788 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07006789 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006790 private ControllerActivityCounterImpl mBluetoothControllerActivity;
6791
6792 /**
6793 * The amount of time this uid has kept the Modem controller in idle, tx, and rx mode.
6794 * Can be null if the UID has had no such activity.
6795 */
6796 private ControllerActivityCounterImpl mModemControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006797
6798 /**
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006799 * The CPU times we had at the last history details update.
6800 */
6801 long mLastStepUserTime;
6802 long mLastStepSystemTime;
6803 long mCurStepUserTime;
6804 long mCurStepSystemTime;
6805
Joe Onoratoabded112016-02-08 16:49:39 -08006806 LongSamplingCounter mUserCpuTime;
6807 LongSamplingCounter mSystemCpuTime;
Sudheer Shankaaf857412017-07-21 00:14:24 -07006808 LongSamplingCounter[][] mCpuClusterSpeedTimesUs;
Mike Ma3d422c32017-10-25 11:08:57 -07006809 LongSamplingCounter mCpuActiveTimeMs;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006810
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006811 LongSamplingCounterArray mCpuFreqTimeMs;
6812 LongSamplingCounterArray mScreenOffCpuFreqTimeMs;
Mike Ma3d422c32017-10-25 11:08:57 -07006813 LongSamplingCounterArray mCpuClusterTimesMs;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006814
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006815 LongSamplingCounterArray[] mProcStateTimeMs;
6816 LongSamplingCounterArray[] mProcStateScreenOffTimeMs;
6817
6818 IntArray mChildUids;
6819
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006820 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006821 * The statistics we have collected for this uid's wake locks.
6822 */
Joe Onoratoabded112016-02-08 16:49:39 -08006823 final OverflowArrayMap<Wakelock> mWakelockStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006824
6825 /**
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006826 * The statistics we have collected for this uid's syncs.
6827 */
Bookatz2bffb5b2017-04-13 11:59:33 -07006828 final OverflowArrayMap<DualTimer> mSyncStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006829
6830 /**
6831 * The statistics we have collected for this uid's jobs.
6832 */
Bookatzaa4594a2017-03-24 12:39:56 -07006833 final OverflowArrayMap<DualTimer> mJobStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006834
6835 /**
Dianne Hackborn94326cb2017-06-28 16:17:20 -07006836 * Count of the jobs that have completed and the reasons why they completed.
6837 */
6838 final ArrayMap<String, SparseIntArray> mJobCompletions = new ArrayMap<>();
6839
6840 /**
Amith Yamasani977e11f2018-02-16 11:29:54 -08006841 * Count of app launch events that had associated deferred job counts or info about
6842 * last time a job was run.
6843 */
6844 Counter mJobsDeferredEventCount;
6845
6846 /**
6847 * Count of deferred jobs that were pending when the app was launched or brought to
6848 * the foreground through a user interaction.
6849 */
6850 Counter mJobsDeferredCount;
6851
6852 /**
6853 * Sum of time since the last time a job was run for this app before it was launched.
6854 */
6855 LongSamplingCounter mJobsFreshnessTimeMs;
6856
6857 /**
6858 * Array of counts of instances where the time since the last job was run for the app
6859 * fell within one of the thresholds in {@link #JOB_FRESHNESS_BUCKETS}.
6860 */
6861 final Counter[] mJobsFreshnessBuckets;
6862
6863 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006864 * The statistics we have collected for this uid's sensor activations.
6865 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006866 final SparseArray<Sensor> mSensorStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006867
6868 /**
6869 * The statistics we have collected for this uid's processes.
6870 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006871 final ArrayMap<String, Proc> mProcessStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006872
6873 /**
6874 * The statistics we have collected for this uid's processes.
6875 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006876 final ArrayMap<String, Pkg> mPackageStats = new ArrayMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006877
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006878 /**
6879 * The transient wake stats we have collected for this uid's pids.
6880 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006881 final SparseArray<Pid> mPids = new SparseArray<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006882
Joe Onoratoabded112016-02-08 16:49:39 -08006883 public Uid(BatteryStatsImpl bsi, int uid) {
6884 mBsi = bsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006885 mUid = uid;
Joe Onoratoabded112016-02-08 16:49:39 -08006886
Bookatz867c0d72017-03-07 18:23:42 -08006887 mOnBatteryBackgroundTimeBase = new TimeBase();
6888 mOnBatteryBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
6889 mBsi.mClocks.elapsedRealtime() * 1000);
6890
Bookatzc8c44962017-05-11 12:12:54 -07006891 mOnBatteryScreenOffBackgroundTimeBase = new TimeBase();
6892 mOnBatteryScreenOffBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
6893 mBsi.mClocks.elapsedRealtime() * 1000);
6894
Joe Onoratoabded112016-02-08 16:49:39 -08006895 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6896 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Mike Ma3d422c32017-10-25 11:08:57 -07006897 mCpuActiveTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6898 mCpuClusterTimesMs = new LongSamplingCounterArray(mBsi.mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006899
Dianne Hackborn657153b2016-07-29 14:54:14 -07006900 mWakelockStats = mBsi.new OverflowArrayMap<Wakelock>(uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006901 @Override public Wakelock instantiateObject() {
6902 return new Wakelock(mBsi, Uid.this);
6903 }
6904 };
Bookatz2bffb5b2017-04-13 11:59:33 -07006905 mSyncStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
6906 @Override public DualTimer instantiateObject() {
6907 return new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
6908 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006909 }
6910 };
Bookatzaa4594a2017-03-24 12:39:56 -07006911 mJobStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
6912 @Override public DualTimer instantiateObject() {
6913 return new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
6914 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006915 }
6916 };
6917
6918 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_RUNNING,
6919 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
6920 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, this, FULL_WIFI_LOCK,
6921 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Bookatz867c0d72017-03-07 18:23:42 -08006922 mWifiScanTimer = new DualTimer(mBsi.mClocks, this, WIFI_SCAN,
6923 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006924 mWifiBatchedScanTimer = new StopwatchTimer[NUM_WIFI_BATCHED_SCAN_BINS];
Joe Onoratoabded112016-02-08 16:49:39 -08006925 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_MULTICAST_ENABLED,
6926 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006927 mProcessStateTimer = new StopwatchTimer[NUM_PROCESS_STATE];
Amith Yamasani977e11f2018-02-16 11:29:54 -08006928 mJobsDeferredEventCount = new Counter(mBsi.mOnBatteryTimeBase);
6929 mJobsDeferredCount = new Counter(mBsi.mOnBatteryTimeBase);
6930 mJobsFreshnessTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6931 mJobsFreshnessBuckets = new Counter[JOB_FRESHNESS_BUCKETS.length];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006932 }
6933
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006934 @VisibleForTesting
6935 public void setProcessStateForTest(int procState) {
6936 mProcessState = procState;
6937 }
6938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006939 @Override
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006940 public long[] getCpuFreqTimes(int which) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006941 return nullIfAllZeros(mCpuFreqTimeMs, which);
6942 }
6943
6944 @Override
6945 public long[] getScreenOffCpuFreqTimes(int which) {
6946 return nullIfAllZeros(mScreenOffCpuFreqTimeMs, which);
6947 }
6948
6949 @Override
Mike Ma3d422c32017-10-25 11:08:57 -07006950 public long getCpuActiveTime() {
6951 return mCpuActiveTimeMs.getCountLocked(STATS_SINCE_CHARGED);
6952 }
6953
6954 @Override
6955 public long[] getCpuClusterTimes() {
6956 return nullIfAllZeros(mCpuClusterTimesMs, STATS_SINCE_CHARGED);
6957 }
6958
6959
6960 @Override
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006961 public long[] getCpuFreqTimes(int which, int procState) {
6962 if (which < 0 || which >= NUM_PROCESS_STATE) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006963 return null;
6964 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006965 if (mProcStateTimeMs == null) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006966 return null;
6967 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006968 if (!mBsi.mPerProcStateCpuTimesAvailable) {
6969 mProcStateTimeMs = null;
6970 return null;
6971 }
6972 return nullIfAllZeros(mProcStateTimeMs[procState], which);
6973 }
6974
6975 @Override
6976 public long[] getScreenOffCpuFreqTimes(int which, int procState) {
6977 if (which < 0 || which >= NUM_PROCESS_STATE) {
6978 return null;
6979 }
6980 if (mProcStateScreenOffTimeMs == null) {
6981 return null;
6982 }
6983 if (!mBsi.mPerProcStateCpuTimesAvailable) {
6984 mProcStateScreenOffTimeMs = null;
6985 return null;
6986 }
6987 return nullIfAllZeros(mProcStateScreenOffTimeMs[procState], which);
6988 }
6989
6990 public void addIsolatedUid(int isolatedUid) {
6991 if (mChildUids == null) {
6992 mChildUids = new IntArray();
6993 } else if (mChildUids.indexOf(isolatedUid) >= 0) {
6994 return;
6995 }
6996 mChildUids.add(isolatedUid);
6997 }
6998
6999 public void removeIsolatedUid(int isolatedUid) {
7000 final int idx = mChildUids == null ? -1 : mChildUids.indexOf(isolatedUid);
7001 if (idx < 0) {
7002 return;
7003 }
7004 mChildUids.remove(idx);
7005 }
7006
7007 private long[] nullIfAllZeros(LongSamplingCounterArray cpuTimesMs, int which) {
7008 if (cpuTimesMs == null) {
7009 return null;
7010 }
7011 final long[] counts = cpuTimesMs.getCountsLocked(which);
7012 if (counts == null) {
7013 return null;
7014 }
7015 // Return counts only if at least one of the elements is non-zero.
7016 for (int i = counts.length - 1; i >= 0; --i) {
7017 if (counts[i] != 0) {
7018 return counts;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007019 }
7020 }
7021 return null;
7022 }
7023
Sudheer Shankae544d162017-12-28 17:06:20 -08007024 private void addProcStateTimesMs(int procState, long[] cpuTimesMs, boolean onBattery) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007025 if (mProcStateTimeMs == null) {
7026 mProcStateTimeMs = new LongSamplingCounterArray[NUM_PROCESS_STATE];
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007027 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007028 if (mProcStateTimeMs[procState] == null
7029 || mProcStateTimeMs[procState].getSize() != cpuTimesMs.length) {
7030 mProcStateTimeMs[procState] = new LongSamplingCounterArray(
7031 mBsi.mOnBatteryTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007032 }
Sudheer Shankae544d162017-12-28 17:06:20 -08007033 mProcStateTimeMs[procState].addCountLocked(cpuTimesMs, onBattery);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007034 }
7035
Sudheer Shankae544d162017-12-28 17:06:20 -08007036 private void addProcStateScreenOffTimesMs(int procState, long[] cpuTimesMs,
7037 boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007038 if (mProcStateScreenOffTimeMs == null) {
7039 mProcStateScreenOffTimeMs = new LongSamplingCounterArray[NUM_PROCESS_STATE];
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007040 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007041 if (mProcStateScreenOffTimeMs[procState] == null
7042 || mProcStateScreenOffTimeMs[procState].getSize() != cpuTimesMs.length) {
7043 mProcStateScreenOffTimeMs[procState] = new LongSamplingCounterArray(
7044 mBsi.mOnBatteryScreenOffTimeBase);
7045 }
Sudheer Shankae544d162017-12-28 17:06:20 -08007046 mProcStateScreenOffTimeMs[procState].addCountLocked(cpuTimesMs, onBatteryScreenOff);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007047 }
7048
7049 @Override
Bookatzc8c44962017-05-11 12:12:54 -07007050 public Timer getAggregatedPartialWakelockTimer() {
7051 return mAggregatedPartialWakelockTimer;
7052 }
7053
7054 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01007055 @UnsupportedAppUsage
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007056 public ArrayMap<String, ? extends BatteryStats.Uid.Wakelock> getWakelockStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007057 return mWakelockStats.getMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007058 }
7059
7060 @Override
Ahmed ElArabawyddd09692017-10-30 17:58:29 -07007061 public Timer getMulticastWakelockStats() {
7062 return mWifiMulticastTimer;
7063 }
7064
7065 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007066 public ArrayMap<String, ? extends BatteryStats.Timer> getSyncStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007067 return mSyncStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007068 }
7069
7070 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007071 public ArrayMap<String, ? extends BatteryStats.Timer> getJobStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007072 return mJobStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007073 }
7074
7075 @Override
Dianne Hackborn94326cb2017-06-28 16:17:20 -07007076 public ArrayMap<String, SparseIntArray> getJobCompletionStats() {
7077 return mJobCompletions;
7078 }
7079
7080 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01007081 @UnsupportedAppUsage
Dianne Hackborn61659e52014-07-09 16:13:01 -07007082 public SparseArray<? extends BatteryStats.Uid.Sensor> getSensorStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007083 return mSensorStats;
7084 }
7085
7086 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01007087 @UnsupportedAppUsage
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007088 public ArrayMap<String, ? extends BatteryStats.Uid.Proc> getProcessStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007089 return mProcessStats;
7090 }
7091
7092 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007093 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg> getPackageStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007094 return mPackageStats;
7095 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007096
7097 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01007098 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007099 public int getUid() {
7100 return mUid;
7101 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007102
7103 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007104 public void noteWifiRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007105 if (!mWifiRunning) {
7106 mWifiRunning = true;
7107 if (mWifiRunningTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007108 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
7109 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007110 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007111 mWifiRunningTimer.startRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007112 }
7113 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007114
Dianne Hackborn617f8772009-03-31 15:04:46 -07007115 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007116 public void noteWifiStoppedLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007117 if (mWifiRunning) {
7118 mWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007119 mWifiRunningTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007120 }
7121 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007122
Dianne Hackborn617f8772009-03-31 15:04:46 -07007123 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007124 public void noteFullWifiLockAcquiredLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07007125 if (!mFullWifiLockOut) {
7126 mFullWifiLockOut = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007127 if (mFullWifiLockTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007128 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
7129 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007130 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007131 mFullWifiLockTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007132 }
7133 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007134
The Android Open Source Project10592532009-03-18 17:39:46 -07007135 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007136 public void noteFullWifiLockReleasedLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07007137 if (mFullWifiLockOut) {
7138 mFullWifiLockOut = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007139 mFullWifiLockTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007140 }
7141 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007142
The Android Open Source Project10592532009-03-18 17:39:46 -07007143 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007144 public void noteWifiScanStartedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007145 if (!mWifiScanStarted) {
7146 mWifiScanStarted = true;
7147 if (mWifiScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007148 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
7149 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase,
7150 mOnBatteryBackgroundTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007151 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007152 mWifiScanTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007153 }
7154 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007155
The Android Open Source Project10592532009-03-18 17:39:46 -07007156 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007157 public void noteWifiScanStoppedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007158 if (mWifiScanStarted) {
7159 mWifiScanStarted = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007160 mWifiScanTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007161 }
7162 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007163
7164 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007165 public void noteWifiBatchedScanStartedLocked(int csph, long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007166 int bin = 0;
Navtej Singh Mann3c0ce5c2015-06-11 16:53:11 -07007167 while (csph > 8 && bin < NUM_WIFI_BATCHED_SCAN_BINS-1) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007168 csph = csph >> 3;
7169 bin++;
7170 }
7171
7172 if (mWifiBatchedScanBinStarted == bin) return;
7173
7174 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
7175 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007176 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007177 }
7178 mWifiBatchedScanBinStarted = bin;
7179 if (mWifiBatchedScanTimer[bin] == null) {
7180 makeWifiBatchedScanBin(bin, null);
7181 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007182 mWifiBatchedScanTimer[bin].startRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007183 }
7184
7185 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007186 public void noteWifiBatchedScanStoppedLocked(long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007187 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
7188 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007189 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007190 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
7191 }
7192 }
7193
7194 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007195 public void noteWifiMulticastEnabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007196 if (!mWifiMulticastEnabled) {
7197 mWifiMulticastEnabled = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007198 if (mWifiMulticastTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007199 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7200 WIFI_MULTICAST_ENABLED, mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007201 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007202 mWifiMulticastTimer.startRunningLocked(elapsedRealtimeMs);
Tej Singh4503e102018-01-04 14:35:01 -08007203 StatsLog.write_non_chained(
Bookatz90867622018-01-31 15:05:57 -08007204 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED, getUid(), null,
7205 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED__STATE__ON);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007206 }
7207 }
7208
7209 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007210 public void noteWifiMulticastDisabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007211 if (mWifiMulticastEnabled) {
7212 mWifiMulticastEnabled = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007213 mWifiMulticastTimer.stopRunningLocked(elapsedRealtimeMs);
Tej Singh4503e102018-01-04 14:35:01 -08007214 StatsLog.write_non_chained(
Bookatz90867622018-01-31 15:05:57 -08007215 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED, getUid(), null,
7216 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED__STATE__OFF);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007217 }
7218 }
7219
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007220 @Override
7221 public ControllerActivityCounter getWifiControllerActivity() {
7222 return mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07007223 }
7224
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007225 @Override
7226 public ControllerActivityCounter getBluetoothControllerActivity() {
7227 return mBluetoothControllerActivity;
7228 }
7229
7230 @Override
7231 public ControllerActivityCounter getModemControllerActivity() {
7232 return mModemControllerActivity;
7233 }
7234
7235 public ControllerActivityCounterImpl getOrCreateWifiControllerActivityLocked() {
7236 if (mWifiControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007237 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007238 NUM_BT_TX_LEVELS);
Adam Lesinski50e47602015-12-04 17:04:54 -08007239 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007240 return mWifiControllerActivity;
7241 }
7242
7243 public ControllerActivityCounterImpl getOrCreateBluetoothControllerActivityLocked() {
7244 if (mBluetoothControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007245 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007246 NUM_BT_TX_LEVELS);
7247 }
7248 return mBluetoothControllerActivity;
7249 }
7250
7251 public ControllerActivityCounterImpl getOrCreateModemControllerActivityLocked() {
7252 if (mModemControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007253 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007254 ModemActivityInfo.TX_POWER_LEVELS);
7255 }
7256 return mModemControllerActivity;
Adam Lesinski50e47602015-12-04 17:04:54 -08007257 }
7258
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007259 public StopwatchTimer createAudioTurnedOnTimerLocked() {
7260 if (mAudioTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007261 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
7262 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007263 }
7264 return mAudioTurnedOnTimer;
7265 }
7266
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007267 public void noteAudioTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007268 createAudioTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
7269 }
7270
7271 public void noteAudioTurnedOffLocked(long elapsedRealtimeMs) {
7272 if (mAudioTurnedOnTimer != null) {
7273 mAudioTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007274 }
7275 }
7276
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007277 public void noteResetAudioLocked(long elapsedRealtimeMs) {
7278 if (mAudioTurnedOnTimer != null) {
7279 mAudioTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007280 }
7281 }
7282
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007283 public StopwatchTimer createVideoTurnedOnTimerLocked() {
7284 if (mVideoTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007285 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
7286 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007287 }
7288 return mVideoTurnedOnTimer;
7289 }
7290
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007291 public void noteVideoTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007292 createVideoTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
7293 }
7294
7295 public void noteVideoTurnedOffLocked(long elapsedRealtimeMs) {
7296 if (mVideoTurnedOnTimer != null) {
7297 mVideoTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007298 }
7299 }
7300
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007301 public void noteResetVideoLocked(long elapsedRealtimeMs) {
7302 if (mVideoTurnedOnTimer != null) {
7303 mVideoTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007304 }
7305 }
7306
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007307 public StopwatchTimer createFlashlightTurnedOnTimerLocked() {
7308 if (mFlashlightTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007309 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7310 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007311 }
7312 return mFlashlightTurnedOnTimer;
7313 }
7314
7315 public void noteFlashlightTurnedOnLocked(long elapsedRealtimeMs) {
7316 createFlashlightTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
7317 }
7318
7319 public void noteFlashlightTurnedOffLocked(long elapsedRealtimeMs) {
7320 if (mFlashlightTurnedOnTimer != null) {
7321 mFlashlightTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
7322 }
7323 }
7324
7325 public void noteResetFlashlightLocked(long elapsedRealtimeMs) {
7326 if (mFlashlightTurnedOnTimer != null) {
7327 mFlashlightTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
7328 }
7329 }
7330
7331 public StopwatchTimer createCameraTurnedOnTimerLocked() {
7332 if (mCameraTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007333 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
7334 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007335 }
7336 return mCameraTurnedOnTimer;
7337 }
7338
7339 public void noteCameraTurnedOnLocked(long elapsedRealtimeMs) {
7340 createCameraTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
7341 }
7342
7343 public void noteCameraTurnedOffLocked(long elapsedRealtimeMs) {
7344 if (mCameraTurnedOnTimer != null) {
7345 mCameraTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
7346 }
7347 }
7348
7349 public void noteResetCameraLocked(long elapsedRealtimeMs) {
7350 if (mCameraTurnedOnTimer != null) {
7351 mCameraTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
7352 }
7353 }
7354
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007355 public StopwatchTimer createForegroundActivityTimerLocked() {
7356 if (mForegroundActivityTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007357 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7358 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007359 }
7360 return mForegroundActivityTimer;
7361 }
7362
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007363 public StopwatchTimer createForegroundServiceTimerLocked() {
7364 if (mForegroundServiceTimer == null) {
7365 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7366 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase);
7367 }
7368 return mForegroundServiceTimer;
7369 }
7370
Bookatzc8c44962017-05-11 12:12:54 -07007371 public DualTimer createAggregatedPartialWakelockTimerLocked() {
7372 if (mAggregatedPartialWakelockTimer == null) {
7373 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
7374 AGGREGATED_WAKE_TYPE_PARTIAL, null,
7375 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase);
7376 }
7377 return mAggregatedPartialWakelockTimer;
7378 }
7379
Bookatz867c0d72017-03-07 18:23:42 -08007380 public DualTimer createBluetoothScanTimerLocked() {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007381 if (mBluetoothScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007382 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
7383 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
7384 mOnBatteryBackgroundTimeBase);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007385 }
7386 return mBluetoothScanTimer;
7387 }
7388
Bookatzb1f04f32017-05-19 13:57:32 -07007389 public DualTimer createBluetoothUnoptimizedScanTimerLocked() {
7390 if (mBluetoothUnoptimizedScanTimer == null) {
7391 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
7392 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
7393 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
7394 }
7395 return mBluetoothUnoptimizedScanTimer;
7396 }
7397
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00007398 public void noteBluetoothScanStartedLocked(long elapsedRealtimeMs,
7399 boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007400 createBluetoothScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatzb1f04f32017-05-19 13:57:32 -07007401 if (isUnoptimized) {
7402 createBluetoothUnoptimizedScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
7403 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007404 }
7405
Bookatz94c5a312017-07-11 16:49:17 -07007406 public void noteBluetoothScanStoppedLocked(long elapsedRealtimeMs, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007407 if (mBluetoothScanTimer != null) {
7408 mBluetoothScanTimer.stopRunningLocked(elapsedRealtimeMs);
7409 }
Bookatz94c5a312017-07-11 16:49:17 -07007410 if (isUnoptimized && mBluetoothUnoptimizedScanTimer != null) {
Bookatzb1f04f32017-05-19 13:57:32 -07007411 mBluetoothUnoptimizedScanTimer.stopRunningLocked(elapsedRealtimeMs);
7412 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007413 }
7414
7415 public void noteResetBluetoothScanLocked(long elapsedRealtimeMs) {
7416 if (mBluetoothScanTimer != null) {
7417 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
7418 }
Bookatzb1f04f32017-05-19 13:57:32 -07007419 if (mBluetoothUnoptimizedScanTimer != null) {
7420 mBluetoothUnoptimizedScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
7421 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007422 }
7423
Bookatz956f36bf2017-04-28 09:48:17 -07007424 public Counter createBluetoothScanResultCounterLocked() {
7425 if (mBluetoothScanResultCounter == null) {
7426 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase);
7427 }
7428 return mBluetoothScanResultCounter;
7429 }
7430
Bookatzb1f04f32017-05-19 13:57:32 -07007431 public Counter createBluetoothScanResultBgCounterLocked() {
7432 if (mBluetoothScanResultBgCounter == null) {
7433 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase);
7434 }
7435 return mBluetoothScanResultBgCounter;
7436 }
7437
Bookatz4ebc0642017-05-11 12:21:19 -07007438 public void noteBluetoothScanResultsLocked(int numNewResults) {
7439 createBluetoothScanResultCounterLocked().addAtomic(numNewResults);
Bookatzb1f04f32017-05-19 13:57:32 -07007440 // Uses background timebase, so the count will only be incremented if uid in background.
7441 createBluetoothScanResultBgCounterLocked().addAtomic(numNewResults);
Bookatz956f36bf2017-04-28 09:48:17 -07007442 }
7443
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007444 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007445 public void noteActivityResumedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007446 // We always start, since we want multiple foreground PIDs to nest
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007447 createForegroundActivityTimerLocked().startRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007448 }
7449
7450 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007451 public void noteActivityPausedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007452 if (mForegroundActivityTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007453 mForegroundActivityTimer.stopRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007454 }
7455 }
7456
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007457 public void noteForegroundServiceResumedLocked(long elapsedRealtimeMs) {
7458 createForegroundServiceTimerLocked().startRunningLocked(elapsedRealtimeMs);
7459 }
7460
7461 public void noteForegroundServicePausedLocked(long elapsedRealtimeMs) {
7462 if (mForegroundServiceTimer != null) {
7463 mForegroundServiceTimer.stopRunningLocked(elapsedRealtimeMs);
7464 }
7465 }
7466
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007467 public BatchTimer createVibratorOnTimerLocked() {
7468 if (mVibratorOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007469 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
7470 mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007471 }
7472 return mVibratorOnTimer;
7473 }
7474
7475 public void noteVibratorOnLocked(long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08007476 createVibratorOnTimerLocked().addDuration(mBsi, durationMillis);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007477 }
7478
7479 public void noteVibratorOffLocked() {
7480 if (mVibratorOnTimer != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007481 mVibratorOnTimer.abortLastDuration(mBsi);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007482 }
7483 }
7484
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007485 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01007486 @UnsupportedAppUsage
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007487 public long getWifiRunningTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007488 if (mWifiRunningTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007489 return 0;
7490 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007491 return mWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007492 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07007493
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007494 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007495 public long getFullWifiLockTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007496 if (mFullWifiLockTimer == null) {
7497 return 0;
7498 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007499 return mFullWifiLockTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07007500 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007501
7502 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01007503 @UnsupportedAppUsage
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007504 public long getWifiScanTime(long elapsedRealtimeUs, int which) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007505 if (mWifiScanTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007506 return 0;
7507 }
Bookatzaa4594a2017-03-24 12:39:56 -07007508 return mWifiScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07007509 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007510
7511 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07007512 public int getWifiScanCount(int which) {
7513 if (mWifiScanTimer == null) {
7514 return 0;
7515 }
Bookatzaa4594a2017-03-24 12:39:56 -07007516 return mWifiScanTimer.getCountLocked(which);
Bookatz867c0d72017-03-07 18:23:42 -08007517 }
7518
7519 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07007520 public Timer getWifiScanTimer() {
7521 return mWifiScanTimer;
7522 }
7523
7524 @Override
Bookatz867c0d72017-03-07 18:23:42 -08007525 public int getWifiScanBackgroundCount(int which) {
Bookatzaa4594a2017-03-24 12:39:56 -07007526 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007527 return 0;
7528 }
7529 return mWifiScanTimer.getSubTimer().getCountLocked(which);
7530 }
7531
7532 @Override
7533 public long getWifiScanActualTime(final long elapsedRealtimeUs) {
7534 if (mWifiScanTimer == null) {
7535 return 0;
7536 }
7537 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
Bookatzaa4594a2017-03-24 12:39:56 -07007538 return mWifiScanTimer.getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Bookatz867c0d72017-03-07 18:23:42 -08007539 }
7540
7541 @Override
7542 public long getWifiScanBackgroundTime(final long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07007543 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007544 return 0;
7545 }
7546 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
7547 return mWifiScanTimer.getSubTimer().getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Dianne Hackborn62793e42015-03-09 11:15:41 -07007548 }
7549
7550 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07007551 public Timer getWifiScanBackgroundTimer() {
7552 if (mWifiScanTimer == null) {
7553 return null;
7554 }
7555 return mWifiScanTimer.getSubTimer();
7556 }
7557
7558 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007559 public long getWifiBatchedScanTime(int csphBin, long elapsedRealtimeUs, int which) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007560 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
7561 if (mWifiBatchedScanTimer[csphBin] == null) {
7562 return 0;
7563 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007564 return mWifiBatchedScanTimer[csphBin].getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007565 }
7566
7567 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07007568 public int getWifiBatchedScanCount(int csphBin, int which) {
7569 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
7570 if (mWifiBatchedScanTimer[csphBin] == null) {
7571 return 0;
7572 }
7573 return mWifiBatchedScanTimer[csphBin].getCountLocked(which);
7574 }
7575
7576 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007577 public long getWifiMulticastTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007578 if (mWifiMulticastTimer == null) {
7579 return 0;
7580 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007581 return mWifiMulticastTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007582 }
7583
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007584 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007585 public Timer getAudioTurnedOnTimer() {
7586 return mAudioTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007587 }
7588
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007589 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007590 public Timer getVideoTurnedOnTimer() {
7591 return mVideoTurnedOnTimer;
7592 }
7593
7594 @Override
7595 public Timer getFlashlightTurnedOnTimer() {
7596 return mFlashlightTurnedOnTimer;
7597 }
7598
7599 @Override
7600 public Timer getCameraTurnedOnTimer() {
7601 return mCameraTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007602 }
7603
Dianne Hackborn617f8772009-03-31 15:04:46 -07007604 @Override
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007605 public Timer getForegroundActivityTimer() {
7606 return mForegroundActivityTimer;
7607 }
7608
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007609 @Override
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007610 public Timer getForegroundServiceTimer() {
7611 return mForegroundServiceTimer;
7612 }
7613
7614 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007615 public Timer getBluetoothScanTimer() {
Bookatzaa4594a2017-03-24 12:39:56 -07007616 return mBluetoothScanTimer;
Bookatz867c0d72017-03-07 18:23:42 -08007617 }
7618
7619 @Override
7620 public Timer getBluetoothScanBackgroundTimer() {
7621 if (mBluetoothScanTimer == null) {
7622 return null;
7623 }
7624 return mBluetoothScanTimer.getSubTimer();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007625 }
7626
Bookatz956f36bf2017-04-28 09:48:17 -07007627 @Override
Bookatzb1f04f32017-05-19 13:57:32 -07007628 public Timer getBluetoothUnoptimizedScanTimer() {
7629 return mBluetoothUnoptimizedScanTimer;
7630 }
7631
7632 @Override
7633 public Timer getBluetoothUnoptimizedScanBackgroundTimer() {
7634 if (mBluetoothUnoptimizedScanTimer == null) {
7635 return null;
7636 }
7637 return mBluetoothUnoptimizedScanTimer.getSubTimer();
7638 }
7639
7640 @Override
Bookatz956f36bf2017-04-28 09:48:17 -07007641 public Counter getBluetoothScanResultCounter() {
7642 return mBluetoothScanResultCounter;
7643 }
7644
Bookatzb1f04f32017-05-19 13:57:32 -07007645 @Override
7646 public Counter getBluetoothScanResultBgCounter() {
7647 return mBluetoothScanResultBgCounter;
7648 }
7649
Dianne Hackborn61659e52014-07-09 16:13:01 -07007650 void makeProcessState(int i, Parcel in) {
7651 if (i < 0 || i >= NUM_PROCESS_STATE) return;
7652
7653 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007654 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
7655 mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007656 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08007657 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
7658 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007659 }
7660 }
7661
7662 @Override
7663 public long getProcessStateTime(int state, long elapsedRealtimeUs, int which) {
7664 if (state < 0 || state >= NUM_PROCESS_STATE) return 0;
7665 if (mProcessStateTimer[state] == null) {
7666 return 0;
7667 }
7668 return mProcessStateTimer[state].getTotalTimeLocked(elapsedRealtimeUs, which);
7669 }
7670
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007671 @Override
Joe Onorato713fec82016-03-04 10:34:02 -08007672 public Timer getProcessStateTimer(int state) {
7673 if (state < 0 || state >= NUM_PROCESS_STATE) return null;
7674 return mProcessStateTimer[state];
7675 }
7676
7677 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007678 public Timer getVibratorOnTimer() {
7679 return mVibratorOnTimer;
7680 }
7681
7682 @Override
Dianne Hackborn617f8772009-03-31 15:04:46 -07007683 public void noteUserActivityLocked(int type) {
7684 if (mUserActivityCounters == null) {
7685 initUserActivityLocked();
7686 }
Jeff Browndf693de2012-07-27 12:03:38 -07007687 if (type >= 0 && type < NUM_USER_ACTIVITY_TYPES) {
7688 mUserActivityCounters[type].stepAtomic();
7689 } else {
7690 Slog.w(TAG, "Unknown user activity type " + type + " was specified.",
7691 new Throwable());
7692 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07007693 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007694
Dianne Hackborn617f8772009-03-31 15:04:46 -07007695 @Override
7696 public boolean hasUserActivity() {
7697 return mUserActivityCounters != null;
7698 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007699
Dianne Hackborn617f8772009-03-31 15:04:46 -07007700 @Override
7701 public int getUserActivityCount(int type, int which) {
7702 if (mUserActivityCounters == null) {
7703 return 0;
7704 }
Evan Millarc64edde2009-04-18 12:26:32 -07007705 return mUserActivityCounters[type].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007706 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007707
Robert Greenwalta029ea12013-09-25 16:38:12 -07007708 void makeWifiBatchedScanBin(int i, Parcel in) {
7709 if (i < 0 || i >= NUM_WIFI_BATCHED_SCAN_BINS) return;
7710
Joe Onoratoabded112016-02-08 16:49:39 -08007711 ArrayList<StopwatchTimer> collected = mBsi.mWifiBatchedScanTimers.get(i);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007712 if (collected == null) {
7713 collected = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08007714 mBsi.mWifiBatchedScanTimers.put(i, collected);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007715 }
7716 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007717 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
7718 collected, mBsi.mOnBatteryTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007719 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08007720 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
7721 collected, mBsi.mOnBatteryTimeBase, in);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007722 }
7723 }
7724
7725
Dianne Hackborn617f8772009-03-31 15:04:46 -07007726 void initUserActivityLocked() {
7727 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
7728 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007729 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007730 }
7731 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007732
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007733 void noteNetworkActivityLocked(int type, long deltaBytes, long deltaPackets) {
7734 if (mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007735 initNetworkActivityLocked();
7736 }
7737 if (type >= 0 && type < NUM_NETWORK_ACTIVITY_TYPES) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007738 mNetworkByteActivityCounters[type].addCountLocked(deltaBytes);
7739 mNetworkPacketActivityCounters[type].addCountLocked(deltaPackets);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007740 } else {
7741 Slog.w(TAG, "Unknown network activity type " + type + " was specified.",
7742 new Throwable());
7743 }
7744 }
7745
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007746 void noteMobileRadioActiveTimeLocked(long batteryUptime) {
7747 if (mNetworkByteActivityCounters == null) {
7748 initNetworkActivityLocked();
7749 }
7750 mMobileRadioActiveTime.addCountLocked(batteryUptime);
7751 mMobileRadioActiveCount.addCountLocked(1);
7752 }
7753
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007754 @Override
7755 public boolean hasNetworkActivity() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007756 return mNetworkByteActivityCounters != null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007757 }
7758
7759 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007760 public long getNetworkActivityBytes(int type, int which) {
7761 if (mNetworkByteActivityCounters != null && type >= 0
7762 && type < mNetworkByteActivityCounters.length) {
7763 return mNetworkByteActivityCounters[type].getCountLocked(which);
7764 } else {
7765 return 0;
7766 }
7767 }
7768
7769 @Override
7770 public long getNetworkActivityPackets(int type, int which) {
7771 if (mNetworkPacketActivityCounters != null && type >= 0
7772 && type < mNetworkPacketActivityCounters.length) {
7773 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007774 } else {
7775 return 0;
7776 }
7777 }
7778
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007779 @Override
7780 public long getMobileRadioActiveTime(int which) {
7781 return mMobileRadioActiveTime != null
7782 ? mMobileRadioActiveTime.getCountLocked(which) : 0;
7783 }
7784
7785 @Override
7786 public int getMobileRadioActiveCount(int which) {
7787 return mMobileRadioActiveCount != null
7788 ? (int)mMobileRadioActiveCount.getCountLocked(which) : 0;
7789 }
7790
Adam Lesinskie08af192015-03-25 16:42:59 -07007791 @Override
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007792 public long getUserCpuTimeUs(int which) {
7793 return mUserCpuTime.getCountLocked(which);
7794 }
7795
7796 @Override
7797 public long getSystemCpuTimeUs(int which) {
7798 return mSystemCpuTime.getCountLocked(which);
7799 }
7800
7801 @Override
Adam Lesinski6832f392015-09-05 18:05:40 -07007802 public long getTimeAtCpuSpeed(int cluster, int step, int which) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07007803 if (mCpuClusterSpeedTimesUs != null) {
7804 if (cluster >= 0 && cluster < mCpuClusterSpeedTimesUs.length) {
7805 final LongSamplingCounter[] cpuSpeedTimesUs = mCpuClusterSpeedTimesUs[cluster];
7806 if (cpuSpeedTimesUs != null) {
7807 if (step >= 0 && step < cpuSpeedTimesUs.length) {
7808 final LongSamplingCounter c = cpuSpeedTimesUs[step];
Adam Lesinski6832f392015-09-05 18:05:40 -07007809 if (c != null) {
7810 return c.getCountLocked(which);
7811 }
7812 }
7813 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007814 }
7815 }
7816 return 0;
7817 }
7818
Adam Lesinski5f056f62016-07-14 16:56:08 -07007819 public void noteMobileRadioApWakeupLocked() {
7820 if (mMobileRadioApWakeupCount == null) {
7821 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7822 }
7823 mMobileRadioApWakeupCount.addCountLocked(1);
7824 }
7825
7826 @Override
7827 public long getMobileRadioApWakeupCount(int which) {
7828 if (mMobileRadioApWakeupCount != null) {
7829 return mMobileRadioApWakeupCount.getCountLocked(which);
7830 }
7831 return 0;
7832 }
7833
7834 public void noteWifiRadioApWakeupLocked() {
7835 if (mWifiRadioApWakeupCount == null) {
7836 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7837 }
7838 mWifiRadioApWakeupCount.addCountLocked(1);
7839 }
7840
7841 @Override
7842 public long getWifiRadioApWakeupCount(int which) {
7843 if (mWifiRadioApWakeupCount != null) {
7844 return mWifiRadioApWakeupCount.getCountLocked(which);
7845 }
7846 return 0;
7847 }
7848
Amith Yamasani977e11f2018-02-16 11:29:54 -08007849 @Override
7850 public void getDeferredJobsCheckinLineLocked(StringBuilder sb, int which) {
7851 sb.setLength(0);
7852 final int deferredEventCount = mJobsDeferredEventCount.getCountLocked(which);
7853 if (deferredEventCount == 0) {
7854 return;
7855 }
7856 final int deferredCount = mJobsDeferredCount.getCountLocked(which);
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007857 final long totalLatency = mJobsFreshnessTimeMs.getCountLocked(which);
Amith Yamasani977e11f2018-02-16 11:29:54 -08007858 sb.append(deferredEventCount); sb.append(',');
7859 sb.append(deferredCount); sb.append(',');
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007860 sb.append(totalLatency);
Amith Yamasani977e11f2018-02-16 11:29:54 -08007861 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
7862 if (mJobsFreshnessBuckets[i] == null) {
7863 sb.append(",0");
7864 } else {
7865 sb.append(",");
7866 sb.append(mJobsFreshnessBuckets[i].getCountLocked(which));
7867 }
7868 }
7869 }
7870
7871 @Override
7872 public void getDeferredJobsLineLocked(StringBuilder sb, int which) {
7873 sb.setLength(0);
7874 final int deferredEventCount = mJobsDeferredEventCount.getCountLocked(which);
7875 if (deferredEventCount == 0) {
7876 return;
7877 }
7878 final int deferredCount = mJobsDeferredCount.getCountLocked(which);
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007879 final long totalLatency = mJobsFreshnessTimeMs.getCountLocked(which);
Amith Yamasani977e11f2018-02-16 11:29:54 -08007880 sb.append("times="); sb.append(deferredEventCount); sb.append(", ");
7881 sb.append("count="); sb.append(deferredCount); sb.append(", ");
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007882 sb.append("totalLatencyMs="); sb.append(totalLatency); sb.append(", ");
Amith Yamasani977e11f2018-02-16 11:29:54 -08007883 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
7884 sb.append("<"); sb.append(JOB_FRESHNESS_BUCKETS[i]); sb.append("ms=");
7885 if (mJobsFreshnessBuckets[i] == null) {
7886 sb.append("0");
7887 } else {
7888 sb.append(mJobsFreshnessBuckets[i].getCountLocked(which));
7889 }
7890 sb.append(" ");
7891 }
7892 }
7893
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007894 void initNetworkActivityLocked() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007895 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
7896 mNetworkPacketActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007897 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007898 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7899 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007900 }
Joe Onoratoabded112016-02-08 16:49:39 -08007901 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7902 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007903 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07007904
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007905 /**
7906 * Clear all stats for this uid. Returns true if the uid is completely
7907 * inactive so can be dropped.
7908 */
Adam Lesinski5f212c82017-03-13 12:25:13 -07007909 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
Bookatz993a0be2017-07-21 09:03:23 -07007910 public boolean reset(long uptime, long realtime) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007911 boolean active = false;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007912
Bookatz993a0be2017-07-21 09:03:23 -07007913 mOnBatteryBackgroundTimeBase.init(uptime, realtime);
7914 mOnBatteryScreenOffBackgroundTimeBase.init(uptime, realtime);
7915
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007916 if (mWifiRunningTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007917 active |= !mWifiRunningTimer.reset(false);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007918 active |= mWifiRunning;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007919 }
7920 if (mFullWifiLockTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007921 active |= !mFullWifiLockTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007922 active |= mFullWifiLockOut;
7923 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07007924 if (mWifiScanTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007925 active |= !mWifiScanTimer.reset(false);
Nick Pelly6ccaa542012-06-15 15:22:47 -07007926 active |= mWifiScanStarted;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007927 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07007928 if (mWifiBatchedScanTimer != null) {
7929 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
7930 if (mWifiBatchedScanTimer[i] != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007931 active |= !mWifiBatchedScanTimer[i].reset(false);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007932 }
7933 }
7934 active |= (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED);
7935 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007936 if (mWifiMulticastTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007937 active |= !mWifiMulticastTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007938 active |= mWifiMulticastEnabled;
7939 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007940
7941 active |= !resetTimerIfNotNull(mAudioTurnedOnTimer, false);
7942 active |= !resetTimerIfNotNull(mVideoTurnedOnTimer, false);
7943 active |= !resetTimerIfNotNull(mFlashlightTurnedOnTimer, false);
7944 active |= !resetTimerIfNotNull(mCameraTurnedOnTimer, false);
7945 active |= !resetTimerIfNotNull(mForegroundActivityTimer, false);
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007946 active |= !resetTimerIfNotNull(mForegroundServiceTimer, false);
Bookatzc8c44962017-05-11 12:12:54 -07007947 active |= !resetTimerIfNotNull(mAggregatedPartialWakelockTimer, false);
Adam Lesinski5f056f62016-07-14 16:56:08 -07007948 active |= !resetTimerIfNotNull(mBluetoothScanTimer, false);
Bookatzb1f04f32017-05-19 13:57:32 -07007949 active |= !resetTimerIfNotNull(mBluetoothUnoptimizedScanTimer, false);
Bookatz956f36bf2017-04-28 09:48:17 -07007950 if (mBluetoothScanResultCounter != null) {
7951 mBluetoothScanResultCounter.reset(false);
7952 }
Bookatzb1f04f32017-05-19 13:57:32 -07007953 if (mBluetoothScanResultBgCounter != null) {
7954 mBluetoothScanResultBgCounter.reset(false);
7955 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007956
Dianne Hackborn61659e52014-07-09 16:13:01 -07007957 if (mProcessStateTimer != null) {
7958 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
7959 if (mProcessStateTimer[i] != null) {
7960 active |= !mProcessStateTimer[i].reset(false);
7961 }
7962 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08007963 active |= (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007964 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007965 if (mVibratorOnTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007966 if (mVibratorOnTimer.reset(false)) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007967 mVibratorOnTimer.detach();
7968 mVibratorOnTimer = null;
7969 } else {
7970 active = true;
7971 }
7972 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007973
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007974 if (mUserActivityCounters != null) {
7975 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
7976 mUserActivityCounters[i].reset(false);
7977 }
7978 }
7979
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007980 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007981 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007982 mNetworkByteActivityCounters[i].reset(false);
7983 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007984 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007985 mMobileRadioActiveTime.reset(false);
7986 mMobileRadioActiveCount.reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007987 }
7988
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007989 if (mWifiControllerActivity != null) {
7990 mWifiControllerActivity.reset(false);
7991 }
Adam Lesinskie08af192015-03-25 16:42:59 -07007992
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07007993 if (mBluetoothControllerActivity != null) {
7994 mBluetoothControllerActivity.reset(false);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007995 }
7996
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07007997 if (mModemControllerActivity != null) {
7998 mModemControllerActivity.reset(false);
Adam Lesinskie08af192015-03-25 16:42:59 -07007999 }
8000
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008001 mUserCpuTime.reset(false);
8002 mSystemCpuTime.reset(false);
Adam Lesinski6832f392015-09-05 18:05:40 -07008003
Sudheer Shankaaf857412017-07-21 00:14:24 -07008004 if (mCpuClusterSpeedTimesUs != null) {
8005 for (LongSamplingCounter[] speeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008006 if (speeds != null) {
8007 for (LongSamplingCounter speed : speeds) {
8008 if (speed != null) {
8009 speed.reset(false);
8010 }
8011 }
8012 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008013 }
8014 }
8015
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008016 if (mCpuFreqTimeMs != null) {
8017 mCpuFreqTimeMs.reset(false);
8018 }
8019 if (mScreenOffCpuFreqTimeMs != null) {
8020 mScreenOffCpuFreqTimeMs.reset(false);
8021 }
8022
Mike Ma3d422c32017-10-25 11:08:57 -07008023 mCpuActiveTimeMs.reset(false);
8024 mCpuClusterTimesMs.reset(false);
8025
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008026 if (mProcStateTimeMs != null) {
8027 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8028 if (counters != null) {
8029 counters.reset(false);
8030 }
8031 }
8032 }
8033 if (mProcStateScreenOffTimeMs != null) {
8034 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8035 if (counters != null) {
8036 counters.reset(false);
8037 }
8038 }
8039 }
8040
Adam Lesinski5f056f62016-07-14 16:56:08 -07008041 resetLongCounterIfNotNull(mMobileRadioApWakeupCount, false);
8042 resetLongCounterIfNotNull(mWifiRadioApWakeupCount, false);
8043
Dianne Hackbornd953c532014-08-16 18:17:38 -07008044 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
8045 for (int iw=wakeStats.size()-1; iw>=0; iw--) {
8046 Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07008047 if (wl.reset()) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008048 wakeStats.removeAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07008049 } else {
8050 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008051 }
8052 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07008053 mWakelockStats.cleanup();
Bookatz2bffb5b2017-04-13 11:59:33 -07008054 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008055 for (int is=syncStats.size()-1; is>=0; is--) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008056 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008057 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008058 syncStats.removeAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008059 timer.detach();
8060 } else {
8061 active = true;
8062 }
8063 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07008064 mSyncStats.cleanup();
Bookatzaa4594a2017-03-24 12:39:56 -07008065 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008066 for (int ij=jobStats.size()-1; ij>=0; ij--) {
Bookatzaa4594a2017-03-24 12:39:56 -07008067 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008068 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008069 jobStats.removeAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008070 timer.detach();
8071 } else {
8072 active = true;
8073 }
8074 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07008075 mJobStats.cleanup();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008076 mJobCompletions.clear();
Amith Yamasani977e11f2018-02-16 11:29:54 -08008077
8078 mJobsDeferredEventCount.reset(false);
8079 mJobsDeferredCount.reset(false);
8080 mJobsFreshnessTimeMs.reset(false);
8081 for (int ij = 0; ij < JOB_FRESHNESS_BUCKETS.length; ij++) {
8082 if (mJobsFreshnessBuckets[ij] != null) {
8083 mJobsFreshnessBuckets[ij].reset(false);
8084 }
8085 }
8086
Dianne Hackborn61659e52014-07-09 16:13:01 -07008087 for (int ise=mSensorStats.size()-1; ise>=0; ise--) {
8088 Sensor s = mSensorStats.valueAt(ise);
8089 if (s.reset()) {
8090 mSensorStats.removeAt(ise);
8091 } else {
8092 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008093 }
8094 }
Amith Yamasani977e11f2018-02-16 11:29:54 -08008095
Dianne Hackborn61659e52014-07-09 16:13:01 -07008096 for (int ip=mProcessStats.size()-1; ip>=0; ip--) {
8097 Proc proc = mProcessStats.valueAt(ip);
Dianne Hackborna8d10942015-11-19 17:55:19 -08008098 proc.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008099 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08008100 mProcessStats.clear();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008101 if (mPids.size() > 0) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008102 for (int i=mPids.size()-1; i>=0; i--) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008103 Pid pid = mPids.valueAt(i);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008104 if (pid.mWakeNesting > 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008105 active = true;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008106 } else {
8107 mPids.removeAt(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008108 }
8109 }
8110 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008111 if (mPackageStats.size() > 0) {
8112 Iterator<Map.Entry<String, Pkg>> it = mPackageStats.entrySet().iterator();
8113 while (it.hasNext()) {
8114 Map.Entry<String, Pkg> pkgEntry = it.next();
8115 Pkg p = pkgEntry.getValue();
8116 p.detach();
8117 if (p.mServiceStats.size() > 0) {
8118 Iterator<Map.Entry<String, Pkg.Serv>> it2
8119 = p.mServiceStats.entrySet().iterator();
8120 while (it2.hasNext()) {
8121 Map.Entry<String, Pkg.Serv> servEntry = it2.next();
8122 servEntry.getValue().detach();
8123 }
8124 }
8125 }
8126 mPackageStats.clear();
8127 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008128
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08008129 mLastStepUserTime = mLastStepSystemTime = 0;
8130 mCurStepUserTime = mCurStepSystemTime = 0;
8131
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008132 if (!active) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008133 if (mWifiRunningTimer != null) {
8134 mWifiRunningTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008135 }
8136 if (mFullWifiLockTimer != null) {
8137 mFullWifiLockTimer.detach();
8138 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008139 if (mWifiScanTimer != null) {
8140 mWifiScanTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008141 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008142 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8143 if (mWifiBatchedScanTimer[i] != null) {
8144 mWifiBatchedScanTimer[i].detach();
8145 }
8146 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008147 if (mWifiMulticastTimer != null) {
8148 mWifiMulticastTimer.detach();
8149 }
8150 if (mAudioTurnedOnTimer != null) {
8151 mAudioTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008152 mAudioTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008153 }
8154 if (mVideoTurnedOnTimer != null) {
8155 mVideoTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008156 mVideoTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008157 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008158 if (mFlashlightTurnedOnTimer != null) {
8159 mFlashlightTurnedOnTimer.detach();
8160 mFlashlightTurnedOnTimer = null;
8161 }
8162 if (mCameraTurnedOnTimer != null) {
8163 mCameraTurnedOnTimer.detach();
8164 mCameraTurnedOnTimer = null;
8165 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008166 if (mForegroundActivityTimer != null) {
8167 mForegroundActivityTimer.detach();
8168 mForegroundActivityTimer = null;
8169 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008170 if (mForegroundServiceTimer != null) {
8171 mForegroundServiceTimer.detach();
8172 mForegroundServiceTimer = null;
8173 }
Bookatzc8c44962017-05-11 12:12:54 -07008174 if (mAggregatedPartialWakelockTimer != null) {
8175 mAggregatedPartialWakelockTimer.detach();
8176 mAggregatedPartialWakelockTimer = null;
8177 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008178 if (mBluetoothScanTimer != null) {
8179 mBluetoothScanTimer.detach();
8180 mBluetoothScanTimer = null;
8181 }
Bookatzb1f04f32017-05-19 13:57:32 -07008182 if (mBluetoothUnoptimizedScanTimer != null) {
8183 mBluetoothUnoptimizedScanTimer.detach();
8184 mBluetoothUnoptimizedScanTimer = null;
8185 }
Bookatz956f36bf2017-04-28 09:48:17 -07008186 if (mBluetoothScanResultCounter != null) {
8187 mBluetoothScanResultCounter.detach();
8188 mBluetoothScanResultCounter = null;
8189 }
Bookatzb1f04f32017-05-19 13:57:32 -07008190 if (mBluetoothScanResultBgCounter != null) {
8191 mBluetoothScanResultBgCounter.detach();
8192 mBluetoothScanResultBgCounter = null;
8193 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008194 if (mUserActivityCounters != null) {
8195 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
8196 mUserActivityCounters[i].detach();
8197 }
8198 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008199 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008200 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008201 mNetworkByteActivityCounters[i].detach();
8202 mNetworkPacketActivityCounters[i].detach();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008203 }
8204 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008205
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008206 if (mWifiControllerActivity != null) {
8207 mWifiControllerActivity.detach();
Adam Lesinskie08af192015-03-25 16:42:59 -07008208 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008209
8210 if (mBluetoothControllerActivity != null) {
8211 mBluetoothControllerActivity.detach();
8212 }
8213
8214 if (mModemControllerActivity != null) {
8215 mModemControllerActivity.detach();
8216 }
8217
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008218 mPids.clear();
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008219
8220 mUserCpuTime.detach();
8221 mSystemCpuTime.detach();
Adam Lesinski6832f392015-09-05 18:05:40 -07008222
Sudheer Shankaaf857412017-07-21 00:14:24 -07008223 if (mCpuClusterSpeedTimesUs != null) {
8224 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008225 if (cpuSpeeds != null) {
8226 for (LongSamplingCounter c : cpuSpeeds) {
8227 if (c != null) {
8228 c.detach();
8229 }
8230 }
8231 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008232 }
8233 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008234
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008235 if (mCpuFreqTimeMs != null) {
8236 mCpuFreqTimeMs.detach();
8237 }
8238 if (mScreenOffCpuFreqTimeMs != null) {
8239 mScreenOffCpuFreqTimeMs.detach();
8240 }
Mike Ma3d422c32017-10-25 11:08:57 -07008241 mCpuActiveTimeMs.detach();
8242 mCpuClusterTimesMs.detach();
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008243
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008244 if (mProcStateTimeMs != null) {
8245 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8246 if (counters != null) {
8247 counters.detach();
8248 }
8249 }
8250 }
8251 if (mProcStateScreenOffTimeMs != null) {
8252 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8253 if (counters != null) {
8254 counters.detach();
8255 }
8256 }
8257 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008258 detachLongCounterIfNotNull(mMobileRadioApWakeupCount);
8259 detachLongCounterIfNotNull(mWifiRadioApWakeupCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008260 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008261
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008262 return !active;
8263 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008264
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008265 void writeJobCompletionsToParcelLocked(Parcel out) {
8266 int NJC = mJobCompletions.size();
8267 out.writeInt(NJC);
8268 for (int ijc=0; ijc<NJC; ijc++) {
8269 out.writeString(mJobCompletions.keyAt(ijc));
8270 SparseIntArray types = mJobCompletions.valueAt(ijc);
8271 int NT = types.size();
8272 out.writeInt(NT);
8273 for (int it=0; it<NT; it++) {
8274 out.writeInt(types.keyAt(it));
8275 out.writeInt(types.valueAt(it));
8276 }
8277 }
8278 }
8279
Bookatz867c0d72017-03-07 18:23:42 -08008280 void writeToParcelLocked(Parcel out, long uptimeUs, long elapsedRealtimeUs) {
8281 mOnBatteryBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatzc8c44962017-05-11 12:12:54 -07008282 mOnBatteryScreenOffBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08008283
Dianne Hackbornd953c532014-08-16 18:17:38 -07008284 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
8285 int NW = wakeStats.size();
Dianne Hackborn61659e52014-07-09 16:13:01 -07008286 out.writeInt(NW);
8287 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008288 out.writeString(wakeStats.keyAt(iw));
8289 Uid.Wakelock wakelock = wakeStats.valueAt(iw);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008290 wakelock.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008291 }
8292
Bookatz2bffb5b2017-04-13 11:59:33 -07008293 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008294 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008295 out.writeInt(NS);
8296 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008297 out.writeString(syncStats.keyAt(is));
Bookatz2bffb5b2017-04-13 11:59:33 -07008298 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008299 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
8300 }
8301
Bookatzaa4594a2017-03-24 12:39:56 -07008302 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008303 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008304 out.writeInt(NJ);
8305 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008306 out.writeString(jobStats.keyAt(ij));
Bookatzaa4594a2017-03-24 12:39:56 -07008307 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008308 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
8309 }
8310
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008311 writeJobCompletionsToParcelLocked(out);
8312
Amith Yamasani977e11f2018-02-16 11:29:54 -08008313 mJobsDeferredEventCount.writeToParcel(out);
8314 mJobsDeferredCount.writeToParcel(out);
8315 mJobsFreshnessTimeMs.writeToParcel(out);
8316 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
8317 Counter.writeCounterToParcel(out, mJobsFreshnessBuckets[i]);
8318 }
8319
Dianne Hackborn61659e52014-07-09 16:13:01 -07008320 int NSE = mSensorStats.size();
8321 out.writeInt(NSE);
8322 for (int ise=0; ise<NSE; ise++) {
8323 out.writeInt(mSensorStats.keyAt(ise));
8324 Uid.Sensor sensor = mSensorStats.valueAt(ise);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008325 sensor.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008326 }
8327
Dianne Hackborn61659e52014-07-09 16:13:01 -07008328 int NP = mProcessStats.size();
8329 out.writeInt(NP);
8330 for (int ip=0; ip<NP; ip++) {
8331 out.writeString(mProcessStats.keyAt(ip));
8332 Uid.Proc proc = mProcessStats.valueAt(ip);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008333 proc.writeToParcelLocked(out);
8334 }
8335
8336 out.writeInt(mPackageStats.size());
8337 for (Map.Entry<String, Uid.Pkg> pkgEntry : mPackageStats.entrySet()) {
8338 out.writeString(pkgEntry.getKey());
8339 Uid.Pkg pkg = pkgEntry.getValue();
8340 pkg.writeToParcelLocked(out);
8341 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008342
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008343 if (mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008344 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008345 mWifiRunningTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008346 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008347 out.writeInt(0);
8348 }
8349 if (mFullWifiLockTimer != null) {
8350 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008351 mFullWifiLockTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008352 } else {
8353 out.writeInt(0);
8354 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008355 if (mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008356 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008357 mWifiScanTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008358 } else {
8359 out.writeInt(0);
8360 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008361 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8362 if (mWifiBatchedScanTimer[i] != null) {
8363 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008364 mWifiBatchedScanTimer[i].writeToParcel(out, elapsedRealtimeUs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07008365 } else {
8366 out.writeInt(0);
8367 }
8368 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008369 if (mWifiMulticastTimer != null) {
8370 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008371 mWifiMulticastTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008372 } else {
8373 out.writeInt(0);
8374 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008375
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008376 if (mAudioTurnedOnTimer != null) {
8377 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008378 mAudioTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008379 } else {
8380 out.writeInt(0);
8381 }
8382 if (mVideoTurnedOnTimer != null) {
8383 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008384 mVideoTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008385 } else {
8386 out.writeInt(0);
8387 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008388 if (mFlashlightTurnedOnTimer != null) {
8389 out.writeInt(1);
8390 mFlashlightTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
8391 } else {
8392 out.writeInt(0);
8393 }
8394 if (mCameraTurnedOnTimer != null) {
8395 out.writeInt(1);
8396 mCameraTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
8397 } else {
8398 out.writeInt(0);
8399 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008400 if (mForegroundActivityTimer != null) {
8401 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008402 mForegroundActivityTimer.writeToParcel(out, elapsedRealtimeUs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008403 } else {
8404 out.writeInt(0);
8405 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008406 if (mForegroundServiceTimer != null) {
8407 out.writeInt(1);
8408 mForegroundServiceTimer.writeToParcel(out, elapsedRealtimeUs);
8409 } else {
8410 out.writeInt(0);
8411 }
Bookatzc8c44962017-05-11 12:12:54 -07008412 if (mAggregatedPartialWakelockTimer != null) {
8413 out.writeInt(1);
8414 mAggregatedPartialWakelockTimer.writeToParcel(out, elapsedRealtimeUs);
8415 } else {
8416 out.writeInt(0);
8417 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008418 if (mBluetoothScanTimer != null) {
8419 out.writeInt(1);
8420 mBluetoothScanTimer.writeToParcel(out, elapsedRealtimeUs);
8421 } else {
8422 out.writeInt(0);
8423 }
Bookatzb1f04f32017-05-19 13:57:32 -07008424 if (mBluetoothUnoptimizedScanTimer != null) {
8425 out.writeInt(1);
8426 mBluetoothUnoptimizedScanTimer.writeToParcel(out, elapsedRealtimeUs);
8427 } else {
8428 out.writeInt(0);
8429 }
Bookatz956f36bf2017-04-28 09:48:17 -07008430 if (mBluetoothScanResultCounter != null) {
8431 out.writeInt(1);
8432 mBluetoothScanResultCounter.writeToParcel(out);
8433 } else {
8434 out.writeInt(0);
8435 }
Bookatzb1f04f32017-05-19 13:57:32 -07008436 if (mBluetoothScanResultBgCounter != null) {
8437 out.writeInt(1);
8438 mBluetoothScanResultBgCounter.writeToParcel(out);
8439 } else {
8440 out.writeInt(0);
8441 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07008442 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8443 if (mProcessStateTimer[i] != null) {
8444 out.writeInt(1);
8445 mProcessStateTimer[i].writeToParcel(out, elapsedRealtimeUs);
8446 } else {
8447 out.writeInt(0);
8448 }
8449 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008450 if (mVibratorOnTimer != null) {
8451 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008452 mVibratorOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008453 } else {
8454 out.writeInt(0);
8455 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008456 if (mUserActivityCounters != null) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07008457 out.writeInt(1);
8458 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
8459 mUserActivityCounters[i].writeToParcel(out);
8460 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008461 } else {
8462 out.writeInt(0);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008463 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008464 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008465 out.writeInt(1);
8466 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008467 mNetworkByteActivityCounters[i].writeToParcel(out);
8468 mNetworkPacketActivityCounters[i].writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008469 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08008470 mMobileRadioActiveTime.writeToParcel(out);
8471 mMobileRadioActiveCount.writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008472 } else {
8473 out.writeInt(0);
8474 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008475
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008476 if (mWifiControllerActivity != null) {
8477 out.writeInt(1);
8478 mWifiControllerActivity.writeToParcel(out, 0);
8479 } else {
8480 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07008481 }
8482
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008483 if (mBluetoothControllerActivity != null) {
8484 out.writeInt(1);
8485 mBluetoothControllerActivity.writeToParcel(out, 0);
8486 } else {
8487 out.writeInt(0);
8488 }
8489
8490 if (mModemControllerActivity != null) {
8491 out.writeInt(1);
8492 mModemControllerActivity.writeToParcel(out, 0);
8493 } else {
8494 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07008495 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008496
8497 mUserCpuTime.writeToParcel(out);
8498 mSystemCpuTime.writeToParcel(out);
8499
Sudheer Shankaaf857412017-07-21 00:14:24 -07008500 if (mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008501 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -07008502 out.writeInt(mCpuClusterSpeedTimesUs.length);
8503 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008504 if (cpuSpeeds != null) {
8505 out.writeInt(1);
8506 out.writeInt(cpuSpeeds.length);
8507 for (LongSamplingCounter c : cpuSpeeds) {
8508 if (c != null) {
8509 out.writeInt(1);
8510 c.writeToParcel(out);
8511 } else {
8512 out.writeInt(0);
8513 }
8514 }
8515 } else {
8516 out.writeInt(0);
8517 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008518 }
Adam Lesinski6832f392015-09-05 18:05:40 -07008519 } else {
8520 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008521 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008522
Sudheer Shanka59f5c002017-05-15 10:57:15 -07008523 LongSamplingCounterArray.writeToParcel(out, mCpuFreqTimeMs);
8524 LongSamplingCounterArray.writeToParcel(out, mScreenOffCpuFreqTimeMs);
Mike Ma3d422c32017-10-25 11:08:57 -07008525
8526 mCpuActiveTimeMs.writeToParcel(out);
8527 mCpuClusterTimesMs.writeToParcel(out);
8528
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008529 if (mProcStateTimeMs != null) {
8530 out.writeInt(mProcStateTimeMs.length);
8531 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8532 LongSamplingCounterArray.writeToParcel(out, counters);
8533 }
8534 } else {
8535 out.writeInt(0);
8536 }
8537 if (mProcStateScreenOffTimeMs != null) {
8538 out.writeInt(mProcStateScreenOffTimeMs.length);
8539 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8540 LongSamplingCounterArray.writeToParcel(out, counters);
8541 }
8542 } else {
8543 out.writeInt(0);
8544 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008545
Adam Lesinski5f056f62016-07-14 16:56:08 -07008546 if (mMobileRadioApWakeupCount != null) {
8547 out.writeInt(1);
8548 mMobileRadioApWakeupCount.writeToParcel(out);
8549 } else {
8550 out.writeInt(0);
8551 }
8552
8553 if (mWifiRadioApWakeupCount != null) {
8554 out.writeInt(1);
8555 mWifiRadioApWakeupCount.writeToParcel(out);
8556 } else {
8557 out.writeInt(0);
8558 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008559 }
8560
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008561 void readJobCompletionsFromParcelLocked(Parcel in) {
8562 int numJobCompletions = in.readInt();
8563 mJobCompletions.clear();
8564 for (int j = 0; j < numJobCompletions; j++) {
8565 String jobName = in.readString();
8566 int numTypes = in.readInt();
8567 if (numTypes > 0) {
8568 SparseIntArray types = new SparseIntArray();
8569 for (int k = 0; k < numTypes; k++) {
8570 int type = in.readInt();
8571 int count = in.readInt();
8572 types.put(type, count);
8573 }
8574 mJobCompletions.put(jobName, types);
8575 }
8576 }
8577 }
8578
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008579 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase, Parcel in) {
Bookatz867c0d72017-03-07 18:23:42 -08008580 mOnBatteryBackgroundTimeBase.readFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -07008581 mOnBatteryScreenOffBackgroundTimeBase.readFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -08008582
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008583 int numWakelocks = in.readInt();
8584 mWakelockStats.clear();
8585 for (int j = 0; j < numWakelocks; j++) {
8586 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008587 Uid.Wakelock wakelock = new Wakelock(mBsi, this);
Bookatz5b5ec322017-05-26 09:40:38 -07008588 wakelock.readFromParcelLocked(
8589 timeBase, screenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase, in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07008590 mWakelockStats.add(wakelockName, wakelock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008591 }
8592
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008593 int numSyncs = in.readInt();
8594 mSyncStats.clear();
8595 for (int j = 0; j < numSyncs; j++) {
8596 String syncName = in.readString();
8597 if (in.readInt() != 0) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008598 mSyncStats.add(syncName, new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
8599 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008600 }
8601 }
8602
8603 int numJobs = in.readInt();
8604 mJobStats.clear();
8605 for (int j = 0; j < numJobs; j++) {
8606 String jobName = in.readString();
8607 if (in.readInt() != 0) {
Bookatzaa4594a2017-03-24 12:39:56 -07008608 mJobStats.add(jobName, new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
8609 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008610 }
8611 }
8612
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008613 readJobCompletionsFromParcelLocked(in);
8614
Amith Yamasani977e11f2018-02-16 11:29:54 -08008615 mJobsDeferredEventCount = new Counter(mBsi.mOnBatteryTimeBase, in);
8616 mJobsDeferredCount = new Counter(mBsi.mOnBatteryTimeBase, in);
8617 mJobsFreshnessTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8618 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
8619 mJobsFreshnessBuckets[i] = Counter.readCounterFromParcel(mBsi.mOnBatteryTimeBase,
8620 in);
8621 }
8622
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008623 int numSensors = in.readInt();
8624 mSensorStats.clear();
8625 for (int k = 0; k < numSensors; k++) {
8626 int sensorNumber = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008627 Uid.Sensor sensor = new Sensor(mBsi, this, sensorNumber);
Bookatz867c0d72017-03-07 18:23:42 -08008628 sensor.readFromParcelLocked(mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
8629 in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008630 mSensorStats.put(sensorNumber, sensor);
8631 }
8632
8633 int numProcs = in.readInt();
8634 mProcessStats.clear();
8635 for (int k = 0; k < numProcs; k++) {
8636 String processName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008637 Uid.Proc proc = new Proc(mBsi, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008638 proc.readFromParcelLocked(in);
8639 mProcessStats.put(processName, proc);
8640 }
8641
8642 int numPkgs = in.readInt();
8643 mPackageStats.clear();
8644 for (int l = 0; l < numPkgs; l++) {
8645 String packageName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008646 Uid.Pkg pkg = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008647 pkg.readFromParcelLocked(in);
8648 mPackageStats.put(packageName, pkg);
8649 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008650
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008651 mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008652 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008653 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
8654 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008655 } else {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008656 mWifiRunningTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008657 }
8658 mFullWifiLockOut = false;
8659 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008660 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
8661 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008662 } else {
8663 mFullWifiLockTimer = null;
8664 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008665 mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008666 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08008667 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
8668 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
8669 in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008670 } else {
Nick Pelly6ccaa542012-06-15 15:22:47 -07008671 mWifiScanTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008672 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008673 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
8674 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8675 if (in.readInt() != 0) {
8676 makeWifiBatchedScanBin(i, in);
8677 } else {
8678 mWifiBatchedScanTimer[i] = null;
8679 }
8680 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008681 mWifiMulticastEnabled = false;
8682 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008683 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_MULTICAST_ENABLED,
8684 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008685 } else {
8686 mWifiMulticastTimer = null;
8687 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008688 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008689 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
8690 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008691 } else {
8692 mAudioTurnedOnTimer = null;
8693 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008694 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008695 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
8696 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008697 } else {
8698 mVideoTurnedOnTimer = null;
8699 }
8700 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008701 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8702 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008703 } else {
8704 mFlashlightTurnedOnTimer = null;
8705 }
8706 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008707 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
8708 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008709 } else {
8710 mCameraTurnedOnTimer = null;
8711 }
8712 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008713 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8714 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008715 } else {
8716 mForegroundActivityTimer = null;
8717 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008718 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008719 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8720 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase, in);
8721 } else {
8722 mForegroundServiceTimer = null;
8723 }
8724 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -07008725 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
8726 AGGREGATED_WAKE_TYPE_PARTIAL, null,
8727 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase,
8728 in);
8729 } else {
8730 mAggregatedPartialWakelockTimer = null;
8731 }
8732 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08008733 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
8734 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
8735 mOnBatteryBackgroundTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008736 } else {
8737 mBluetoothScanTimer = null;
8738 }
Bookatz956f36bf2017-04-28 09:48:17 -07008739 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -07008740 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
8741 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
8742 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in);
8743 } else {
8744 mBluetoothUnoptimizedScanTimer = null;
8745 }
8746 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -07008747 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase, in);
8748 } else {
8749 mBluetoothScanResultCounter = null;
8750 }
Bookatzb1f04f32017-05-19 13:57:32 -07008751 if (in.readInt() != 0) {
8752 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase, in);
8753 } else {
8754 mBluetoothScanResultBgCounter = null;
8755 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08008756 mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07008757 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8758 if (in.readInt() != 0) {
8759 makeProcessState(i, in);
8760 } else {
8761 mProcessStateTimer[i] = null;
8762 }
8763 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008764 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008765 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
8766 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008767 } else {
8768 mVibratorOnTimer = null;
8769 }
8770 if (in.readInt() != 0) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07008771 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
8772 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08008773 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008774 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008775 } else {
8776 mUserActivityCounters = null;
Dianne Hackborn617f8772009-03-31 15:04:46 -07008777 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008778 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008779 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
8780 mNetworkPacketActivityCounters
8781 = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008782 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008783 mNetworkByteActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08008784 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008785 mNetworkPacketActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08008786 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008787 }
Joe Onoratoabded112016-02-08 16:49:39 -08008788 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8789 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008790 } else {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008791 mNetworkByteActivityCounters = null;
8792 mNetworkPacketActivityCounters = null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008793 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008794
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008795 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008796 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008797 NUM_WIFI_TX_LEVELS, in);
8798 } else {
8799 mWifiControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07008800 }
8801
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008802 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008803 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008804 NUM_BT_TX_LEVELS, in);
8805 } else {
8806 mBluetoothControllerActivity = null;
8807 }
8808
8809 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008810 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008811 ModemActivityInfo.TX_POWER_LEVELS, in);
8812 } else {
8813 mModemControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07008814 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008815
Joe Onoratoabded112016-02-08 16:49:39 -08008816 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8817 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008818
Adam Lesinski6832f392015-09-05 18:05:40 -07008819 if (in.readInt() != 0) {
8820 int numCpuClusters = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008821 if (mBsi.mPowerProfile != null && mBsi.mPowerProfile.getNumCpuClusters() != numCpuClusters) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008822 throw new ParcelFormatException("Incompatible number of cpu clusters");
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008823 }
Adam Lesinski6832f392015-09-05 18:05:40 -07008824
Sudheer Shankaaf857412017-07-21 00:14:24 -07008825 mCpuClusterSpeedTimesUs = new LongSamplingCounter[numCpuClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -07008826 for (int cluster = 0; cluster < numCpuClusters; cluster++) {
8827 if (in.readInt() != 0) {
8828 int numSpeeds = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008829 if (mBsi.mPowerProfile != null &&
8830 mBsi.mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != numSpeeds) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008831 throw new ParcelFormatException("Incompatible number of cpu speeds");
8832 }
8833
8834 final LongSamplingCounter[] cpuSpeeds = new LongSamplingCounter[numSpeeds];
Sudheer Shankaaf857412017-07-21 00:14:24 -07008835 mCpuClusterSpeedTimesUs[cluster] = cpuSpeeds;
Adam Lesinski6832f392015-09-05 18:05:40 -07008836 for (int speed = 0; speed < numSpeeds; speed++) {
8837 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008838 cpuSpeeds[speed] = new LongSamplingCounter(
8839 mBsi.mOnBatteryTimeBase, in);
Adam Lesinski6832f392015-09-05 18:05:40 -07008840 }
8841 }
Adam Lesinskia57a5402015-09-28 10:21:33 -07008842 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008843 mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -07008844 }
8845 }
8846 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008847 mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008848 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008849
Sudheer Shanka59f5c002017-05-15 10:57:15 -07008850 mCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(in, mBsi.mOnBatteryTimeBase);
8851 mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(
8852 in, mBsi.mOnBatteryScreenOffTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008853
Mike Ma3d422c32017-10-25 11:08:57 -07008854 mCpuActiveTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8855 mCpuClusterTimesMs = new LongSamplingCounterArray(mBsi.mOnBatteryTimeBase, in);
8856
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008857 int length = in.readInt();
8858 if (length == NUM_PROCESS_STATE) {
8859 mProcStateTimeMs = new LongSamplingCounterArray[length];
8860 for (int procState = 0; procState < length; ++procState) {
8861 mProcStateTimeMs[procState] = LongSamplingCounterArray.readFromParcel(
8862 in, mBsi.mOnBatteryTimeBase);
8863 }
8864 } else {
8865 mProcStateTimeMs = null;
8866 }
8867 length = in.readInt();
8868 if (length == NUM_PROCESS_STATE) {
8869 mProcStateScreenOffTimeMs = new LongSamplingCounterArray[length];
8870 for (int procState = 0; procState < length; ++procState) {
8871 mProcStateScreenOffTimeMs[procState] = LongSamplingCounterArray.readFromParcel(
8872 in, mBsi.mOnBatteryScreenOffTimeBase);
8873 }
8874 } else {
8875 mProcStateScreenOffTimeMs = null;
8876 }
8877
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008878 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07008879 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8880 } else {
8881 mMobileRadioApWakeupCount = null;
8882 }
8883
8884 if (in.readInt() != 0) {
8885 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8886 } else {
8887 mWifiRadioApWakeupCount = null;
8888 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008889 }
8890
Amith Yamasani977e11f2018-02-16 11:29:54 -08008891 public void noteJobsDeferredLocked(int numDeferred, long sinceLast) {
8892 mJobsDeferredEventCount.addAtomic(1);
8893 mJobsDeferredCount.addAtomic(numDeferred);
8894 if (sinceLast != 0) {
8895 // Add the total time, which can be divided by the event count to get an average
8896 mJobsFreshnessTimeMs.addCountLocked(sinceLast);
8897 // Also keep track of how many times there were in these different buckets.
8898 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
8899 if (sinceLast < JOB_FRESHNESS_BUCKETS[i]) {
8900 if (mJobsFreshnessBuckets[i] == null) {
8901 mJobsFreshnessBuckets[i] = new Counter(
8902 mBsi.mOnBatteryTimeBase);
8903 }
8904 mJobsFreshnessBuckets[i].addAtomic(1);
8905 break;
8906 }
8907 }
8908 }
8909 }
8910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008911 /**
8912 * The statistics associated with a particular wake lock.
8913 */
Joe Onoratoabded112016-02-08 16:49:39 -08008914 public static class Wakelock extends BatteryStats.Uid.Wakelock {
8915 /**
8916 * BatteryStatsImpl that we are associated with.
8917 */
8918 protected BatteryStatsImpl mBsi;
8919
8920 /**
8921 * BatteryStatsImpl that we are associated with.
8922 */
8923 protected Uid mUid;
8924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008925 /**
8926 * How long (in ms) this uid has been keeping the device partially awake.
Bookatz5b5ec322017-05-26 09:40:38 -07008927 * 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 -08008928 */
Bookatz5b5ec322017-05-26 09:40:38 -07008929 DualTimer mTimerPartial;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008930
8931 /**
8932 * How long (in ms) this uid has been keeping the device fully awake.
8933 */
Evan Millarc64edde2009-04-18 12:26:32 -07008934 StopwatchTimer mTimerFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008935
8936 /**
8937 * How long (in ms) this uid has had a window keeping the device awake.
8938 */
Evan Millarc64edde2009-04-18 12:26:32 -07008939 StopwatchTimer mTimerWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008940
8941 /**
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008942 * How long (in ms) this uid has had a draw wake lock.
Adam Lesinski9425fe22015-06-19 12:02:13 -07008943 */
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008944 StopwatchTimer mTimerDraw;
Adam Lesinski9425fe22015-06-19 12:02:13 -07008945
Joe Onoratoabded112016-02-08 16:49:39 -08008946 public Wakelock(BatteryStatsImpl bsi, Uid uid) {
8947 mBsi = bsi;
8948 mUid = uid;
8949 }
8950
Adam Lesinski9425fe22015-06-19 12:02:13 -07008951 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008952 * Reads a possibly null Timer from a Parcel. The timer is associated with the
8953 * proper timer pool from the given BatteryStatsImpl object.
8954 *
8955 * @param in the Parcel to be read from.
8956 * return a new Timer, or null.
8957 */
Joe Onorato92fd23f2016-07-25 11:18:42 -07008958 private StopwatchTimer readStopwatchTimerFromParcel(int type,
8959 ArrayList<StopwatchTimer> pool, TimeBase timeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008960 if (in.readInt() == 0) {
8961 return null;
8962 }
8963
Joe Onoratoabded112016-02-08 16:49:39 -08008964 return new StopwatchTimer(mBsi.mClocks, mUid, type, pool, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008965 }
8966
Joe Onorato92fd23f2016-07-25 11:18:42 -07008967 /**
8968 * Reads a possibly null Timer from a Parcel. The timer is associated with the
8969 * proper timer pool from the given BatteryStatsImpl object.
8970 *
8971 * @param in the Parcel to be read from.
8972 * return a new Timer, or null.
8973 */
Bookatz5b5ec322017-05-26 09:40:38 -07008974 private DualTimer readDualTimerFromParcel(int type, ArrayList<StopwatchTimer> pool,
8975 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07008976 if (in.readInt() == 0) {
8977 return null;
8978 }
8979
Bookatz5b5ec322017-05-26 09:40:38 -07008980 return new DualTimer(mBsi.mClocks, mUid, type, pool, timeBase, bgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07008981 }
8982
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008983 boolean reset() {
8984 boolean wlactive = false;
8985 if (mTimerFull != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008986 wlactive |= !mTimerFull.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008987 }
8988 if (mTimerPartial != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008989 wlactive |= !mTimerPartial.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008990 }
8991 if (mTimerWindow != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008992 wlactive |= !mTimerWindow.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008993 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008994 if (mTimerDraw != null) {
8995 wlactive |= !mTimerDraw.reset(false);
Adam Lesinski9425fe22015-06-19 12:02:13 -07008996 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008997 if (!wlactive) {
8998 if (mTimerFull != null) {
8999 mTimerFull.detach();
9000 mTimerFull = null;
9001 }
9002 if (mTimerPartial != null) {
9003 mTimerPartial.detach();
9004 mTimerPartial = null;
9005 }
9006 if (mTimerWindow != null) {
9007 mTimerWindow.detach();
9008 mTimerWindow = null;
9009 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07009010 if (mTimerDraw != null) {
9011 mTimerDraw.detach();
9012 mTimerDraw = null;
Adam Lesinski9425fe22015-06-19 12:02:13 -07009013 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009014 }
9015 return !wlactive;
9016 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009017
Bookatz5b5ec322017-05-26 09:40:38 -07009018 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase,
9019 TimeBase screenOffBgTimeBase, Parcel in) {
9020 mTimerPartial = readDualTimerFromParcel(WAKE_TYPE_PARTIAL,
9021 mBsi.mPartialTimers, screenOffTimeBase, screenOffBgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07009022 mTimerFull = readStopwatchTimerFromParcel(WAKE_TYPE_FULL,
9023 mBsi.mFullTimers, timeBase, in);
9024 mTimerWindow = readStopwatchTimerFromParcel(WAKE_TYPE_WINDOW,
9025 mBsi.mWindowTimers, timeBase, in);
9026 mTimerDraw = readStopwatchTimerFromParcel(WAKE_TYPE_DRAW,
9027 mBsi.mDrawTimers, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009028 }
9029
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009030 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
9031 Timer.writeTimerToParcel(out, mTimerPartial, elapsedRealtimeUs);
9032 Timer.writeTimerToParcel(out, mTimerFull, elapsedRealtimeUs);
9033 Timer.writeTimerToParcel(out, mTimerWindow, elapsedRealtimeUs);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07009034 Timer.writeTimerToParcel(out, mTimerDraw, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009035 }
9036
9037 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01009038 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009039 public Timer getWakeTime(int type) {
9040 switch (type) {
9041 case WAKE_TYPE_FULL: return mTimerFull;
9042 case WAKE_TYPE_PARTIAL: return mTimerPartial;
9043 case WAKE_TYPE_WINDOW: return mTimerWindow;
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07009044 case WAKE_TYPE_DRAW: return mTimerDraw;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009045 default: throw new IllegalArgumentException("type = " + type);
9046 }
9047 }
9048 }
9049
Joe Onoratoabded112016-02-08 16:49:39 -08009050 public static class Sensor extends BatteryStats.Uid.Sensor {
9051 /**
9052 * BatteryStatsImpl that we are associated with.
9053 */
9054 protected BatteryStatsImpl mBsi;
9055
9056 /**
Bookatz867c0d72017-03-07 18:23:42 -08009057 * Uid that we are associated with.
Joe Onoratoabded112016-02-08 16:49:39 -08009058 */
9059 protected Uid mUid;
9060
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009061 final int mHandle;
Bookatz867c0d72017-03-07 18:23:42 -08009062 DualTimer mTimer;
Amith Yamasaniab9ad192016-12-06 12:46:59 -08009063
Joe Onoratoabded112016-02-08 16:49:39 -08009064 public Sensor(BatteryStatsImpl bsi, Uid uid, int handle) {
9065 mBsi = bsi;
9066 mUid = uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009067 mHandle = handle;
9068 }
9069
Bookatz867c0d72017-03-07 18:23:42 -08009070 private DualTimer readTimersFromParcel(
9071 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009072 if (in.readInt() == 0) {
9073 return null;
9074 }
9075
Joe Onoratoabded112016-02-08 16:49:39 -08009076 ArrayList<StopwatchTimer> pool = mBsi.mSensorTimers.get(mHandle);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009077 if (pool == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07009078 pool = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08009079 mBsi.mSensorTimers.put(mHandle, pool);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009080 }
Bookatz867c0d72017-03-07 18:23:42 -08009081 return new DualTimer(mBsi.mClocks, mUid, 0, pool, timeBase, bgTimeBase, in);
Amith Yamasaniab9ad192016-12-06 12:46:59 -08009082 }
9083
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009084 boolean reset() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009085 if (mTimer.reset(true)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009086 mTimer = null;
9087 return true;
9088 }
9089 return false;
9090 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009091
Bookatz867c0d72017-03-07 18:23:42 -08009092 void readFromParcelLocked(TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
9093 mTimer = readTimersFromParcel(timeBase, bgTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009094 }
9095
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009096 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07009097 Timer.writeTimerToParcel(out, mTimer, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009098 }
9099
9100 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01009101 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009102 public Timer getSensorTime() {
Bookatzaa4594a2017-03-24 12:39:56 -07009103 return mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009104 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009105
9106 @Override
Bookatz867c0d72017-03-07 18:23:42 -08009107 public Timer getSensorBackgroundTime() {
9108 if (mTimer == null) {
9109 return null;
9110 }
9111 return mTimer.getSubTimer();
Amith Yamasaniab9ad192016-12-06 12:46:59 -08009112 }
9113
9114 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01009115 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009116 public int getHandle() {
9117 return mHandle;
9118 }
9119 }
9120
9121 /**
9122 * The statistics associated with a particular process.
9123 */
Joe Onoratoabded112016-02-08 16:49:39 -08009124 public static class Proc extends BatteryStats.Uid.Proc implements TimeBaseObs {
9125 /**
9126 * BatteryStatsImpl that we are associated with.
9127 */
9128 protected BatteryStatsImpl mBsi;
9129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009130 /**
Dianne Hackborncd0e3352014-08-07 17:08:09 -07009131 * The name of this process.
9132 */
9133 final String mName;
9134
9135 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -08009136 * Remains true until removed from the stats.
9137 */
9138 boolean mActive = true;
9139
9140 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07009141 * Total time (in ms) spent executing in user code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009142 */
9143 long mUserTime;
9144
9145 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07009146 * Total time (in ms) spent executing in kernel code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009147 */
9148 long mSystemTime;
9149
9150 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07009151 * Amount of time (in ms) the process was running in the foreground.
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009152 */
9153 long mForegroundTime;
9154
9155 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009156 * Number of times the process has been started.
9157 */
9158 int mStarts;
9159
9160 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009161 * Number of times the process has crashed.
9162 */
9163 int mNumCrashes;
9164
9165 /**
9166 * Number of times the process has had an ANR.
9167 */
9168 int mNumAnrs;
9169
9170 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009171 * The amount of user time loaded from a previous save.
9172 */
9173 long mLoadedUserTime;
9174
9175 /**
9176 * The amount of system time loaded from a previous save.
9177 */
9178 long mLoadedSystemTime;
9179
9180 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009181 * The amount of foreground time loaded from a previous save.
9182 */
9183 long mLoadedForegroundTime;
9184
9185 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009186 * The number of times the process has started from a previous save.
9187 */
9188 int mLoadedStarts;
9189
9190 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009191 * Number of times the process has crashed from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009192 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009193 int mLoadedNumCrashes;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009194
9195 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009196 * Number of times the process has had an ANR from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009197 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009198 int mLoadedNumAnrs;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009199
9200 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009201 * The amount of user time when last unplugged.
9202 */
9203 long mUnpluggedUserTime;
9204
9205 /**
9206 * The amount of system time when last unplugged.
9207 */
9208 long mUnpluggedSystemTime;
9209
9210 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009211 * The amount of foreground time since unplugged.
9212 */
9213 long mUnpluggedForegroundTime;
9214
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009215 /**
9216 * The number of times the process has started before unplugged.
9217 */
9218 int mUnpluggedStarts;
9219
Dianne Hackborn61659e52014-07-09 16:13:01 -07009220 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009221 * Number of times the process has crashed before unplugged.
9222 */
9223 int mUnpluggedNumCrashes;
9224
9225 /**
9226 * Number of times the process has had an ANR before unplugged.
9227 */
9228 int mUnpluggedNumAnrs;
9229
Dianne Hackborn287952c2010-09-22 22:34:31 -07009230 ArrayList<ExcessivePower> mExcessivePower;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009231
Joe Onoratoabded112016-02-08 16:49:39 -08009232 public Proc(BatteryStatsImpl bsi, String name) {
9233 mBsi = bsi;
Dianne Hackborncd0e3352014-08-07 17:08:09 -07009234 mName = name;
Joe Onoratoabded112016-02-08 16:49:39 -08009235 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009236 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07009237
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009238 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009239 mUnpluggedUserTime = mUserTime;
9240 mUnpluggedSystemTime = mSystemTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009241 mUnpluggedForegroundTime = mForegroundTime;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009242 mUnpluggedStarts = mStarts;
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009243 mUnpluggedNumCrashes = mNumCrashes;
9244 mUnpluggedNumAnrs = mNumAnrs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009245 }
9246
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009247 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009248 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009249
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009250 void detach() {
Dianne Hackborn099bc622014-01-22 13:39:16 -08009251 mActive = false;
Joe Onoratoabded112016-02-08 16:49:39 -08009252 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009253 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009254
Dianne Hackborn287952c2010-09-22 22:34:31 -07009255 public int countExcessivePowers() {
9256 return mExcessivePower != null ? mExcessivePower.size() : 0;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009257 }
9258
Dianne Hackborn287952c2010-09-22 22:34:31 -07009259 public ExcessivePower getExcessivePower(int i) {
9260 if (mExcessivePower != null) {
9261 return mExcessivePower.get(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009262 }
9263 return null;
9264 }
9265
Dianne Hackborn287952c2010-09-22 22:34:31 -07009266 public void addExcessiveCpu(long overTime, long usedTime) {
9267 if (mExcessivePower == null) {
9268 mExcessivePower = new ArrayList<ExcessivePower>();
9269 }
9270 ExcessivePower ew = new ExcessivePower();
9271 ew.type = ExcessivePower.TYPE_CPU;
9272 ew.overTime = overTime;
9273 ew.usedTime = usedTime;
9274 mExcessivePower.add(ew);
9275 }
9276
9277 void writeExcessivePowerToParcelLocked(Parcel out) {
9278 if (mExcessivePower == null) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009279 out.writeInt(0);
9280 return;
9281 }
9282
Dianne Hackborn287952c2010-09-22 22:34:31 -07009283 final int N = mExcessivePower.size();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009284 out.writeInt(N);
9285 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009286 ExcessivePower ew = mExcessivePower.get(i);
9287 out.writeInt(ew.type);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009288 out.writeLong(ew.overTime);
9289 out.writeLong(ew.usedTime);
9290 }
9291 }
9292
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009293 void readExcessivePowerFromParcelLocked(Parcel in) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009294 final int N = in.readInt();
9295 if (N == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009296 mExcessivePower = null;
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009297 return;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009298 }
9299
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08009300 if (N > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009301 throw new ParcelFormatException(
9302 "File corrupt: too many excessive power entries " + N);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08009303 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009304
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009305 mExcessivePower = new ArrayList<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009306 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009307 ExcessivePower ew = new ExcessivePower();
9308 ew.type = in.readInt();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009309 ew.overTime = in.readLong();
9310 ew.usedTime = in.readLong();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009311 mExcessivePower.add(ew);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009312 }
9313 }
9314
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009315 void writeToParcelLocked(Parcel out) {
9316 out.writeLong(mUserTime);
9317 out.writeLong(mSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009318 out.writeLong(mForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009319 out.writeInt(mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009320 out.writeInt(mNumCrashes);
9321 out.writeInt(mNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009322 out.writeLong(mLoadedUserTime);
9323 out.writeLong(mLoadedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009324 out.writeLong(mLoadedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009325 out.writeInt(mLoadedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009326 out.writeInt(mLoadedNumCrashes);
9327 out.writeInt(mLoadedNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009328 out.writeLong(mUnpluggedUserTime);
9329 out.writeLong(mUnpluggedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009330 out.writeLong(mUnpluggedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009331 out.writeInt(mUnpluggedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009332 out.writeInt(mUnpluggedNumCrashes);
9333 out.writeInt(mUnpluggedNumAnrs);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009334 writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009335 }
9336
9337 void readFromParcelLocked(Parcel in) {
9338 mUserTime = in.readLong();
9339 mSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009340 mForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009341 mStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009342 mNumCrashes = in.readInt();
9343 mNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009344 mLoadedUserTime = in.readLong();
9345 mLoadedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009346 mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009347 mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009348 mLoadedNumCrashes = in.readInt();
9349 mLoadedNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009350 mUnpluggedUserTime = in.readLong();
9351 mUnpluggedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009352 mUnpluggedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009353 mUnpluggedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009354 mUnpluggedNumCrashes = in.readInt();
9355 mUnpluggedNumAnrs = in.readInt();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009356 readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009357 }
9358
Mathew Inwoodc185f082018-08-20 14:28:54 +01009359 @UnsupportedAppUsage
Adam Lesinski06af1fa2015-05-05 17:35:35 -07009360 public void addCpuTimeLocked(int utime, int stime) {
Sudheer Shankac57729a2018-02-09 15:44:42 -08009361 addCpuTimeLocked(utime, stime, mBsi.mOnBatteryTimeBase.isRunning());
9362 }
9363
9364 public void addCpuTimeLocked(int utime, int stime, boolean isRunning) {
9365 if (isRunning) {
9366 mUserTime += utime;
9367 mSystemTime += stime;
9368 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009369 }
9370
Mathew Inwoodc185f082018-08-20 14:28:54 +01009371 @UnsupportedAppUsage
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009372 public void addForegroundTimeLocked(long ttime) {
9373 mForegroundTime += ttime;
9374 }
9375
Mathew Inwoodc185f082018-08-20 14:28:54 +01009376 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009377 public void incStartsLocked() {
9378 mStarts++;
9379 }
9380
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009381 public void incNumCrashesLocked() {
9382 mNumCrashes++;
9383 }
9384
9385 public void incNumAnrsLocked() {
9386 mNumAnrs++;
9387 }
9388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009389 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -08009390 public boolean isActive() {
9391 return mActive;
9392 }
9393
9394 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01009395 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009396 public long getUserTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009397 long val = mUserTime;
9398 if (which == STATS_CURRENT) {
9399 val -= mLoadedUserTime;
9400 } else if (which == STATS_SINCE_UNPLUGGED) {
9401 val -= mUnpluggedUserTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009402 }
9403 return val;
9404 }
9405
9406 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01009407 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009408 public long getSystemTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009409 long val = mSystemTime;
9410 if (which == STATS_CURRENT) {
9411 val -= mLoadedSystemTime;
9412 } else if (which == STATS_SINCE_UNPLUGGED) {
9413 val -= mUnpluggedSystemTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009414 }
9415 return val;
9416 }
9417
9418 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01009419 @UnsupportedAppUsage
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009420 public long getForegroundTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009421 long val = mForegroundTime;
9422 if (which == STATS_CURRENT) {
9423 val -= mLoadedForegroundTime;
9424 } else if (which == STATS_SINCE_UNPLUGGED) {
9425 val -= mUnpluggedForegroundTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009426 }
9427 return val;
9428 }
9429
9430 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +01009431 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009432 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009433 int val = mStarts;
9434 if (which == STATS_CURRENT) {
9435 val -= mLoadedStarts;
9436 } else if (which == STATS_SINCE_UNPLUGGED) {
9437 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009438 }
9439 return val;
9440 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07009441
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009442 @Override
9443 public int getNumCrashes(int which) {
9444 int val = mNumCrashes;
9445 if (which == STATS_CURRENT) {
9446 val -= mLoadedNumCrashes;
9447 } else if (which == STATS_SINCE_UNPLUGGED) {
9448 val -= mUnpluggedNumCrashes;
9449 }
9450 return val;
9451 }
9452
9453 @Override
9454 public int getNumAnrs(int which) {
9455 int val = mNumAnrs;
9456 if (which == STATS_CURRENT) {
9457 val -= mLoadedNumAnrs;
9458 } else if (which == STATS_SINCE_UNPLUGGED) {
9459 val -= mUnpluggedNumAnrs;
9460 }
9461 return val;
9462 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009463 }
9464
9465 /**
9466 * The statistics associated with a particular package.
9467 */
Joe Onoratoabded112016-02-08 16:49:39 -08009468 public static class Pkg extends BatteryStats.Uid.Pkg implements TimeBaseObs {
9469 /**
9470 * BatteryStatsImpl that we are associated with.
9471 */
9472 protected BatteryStatsImpl mBsi;
9473
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009474 /**
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009475 * Number of times wakeup alarms have occurred for this app.
Bookatz98d4d5c2017-08-01 19:07:54 -07009476 * On screen-off timebase starting in report v25.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009477 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009478 ArrayMap<String, Counter> mWakeupAlarms = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009479
9480 /**
9481 * The statics we have collected for this package's services.
9482 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009483 final ArrayMap<String, Serv> mServiceStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009484
Joe Onoratoabded112016-02-08 16:49:39 -08009485 public Pkg(BatteryStatsImpl bsi) {
9486 mBsi = bsi;
9487 mBsi.mOnBatteryScreenOffTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009488 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009489
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009490 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009491 }
9492
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009493 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009494 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009495
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009496 void detach() {
Joe Onoratoabded112016-02-08 16:49:39 -08009497 mBsi.mOnBatteryScreenOffTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009498 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009499
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009500 void readFromParcelLocked(Parcel in) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009501 int numWA = in.readInt();
9502 mWakeupAlarms.clear();
9503 for (int i=0; i<numWA; i++) {
9504 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -07009505 mWakeupAlarms.put(tag, new Counter(mBsi.mOnBatteryScreenOffTimeBase, in));
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009506 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009507
9508 int numServs = in.readInt();
9509 mServiceStats.clear();
9510 for (int m = 0; m < numServs; m++) {
9511 String serviceName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08009512 Uid.Pkg.Serv serv = new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009513 mServiceStats.put(serviceName, serv);
9514
9515 serv.readFromParcelLocked(in);
9516 }
9517 }
9518
9519 void writeToParcelLocked(Parcel out) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009520 int numWA = mWakeupAlarms.size();
9521 out.writeInt(numWA);
9522 for (int i=0; i<numWA; i++) {
9523 out.writeString(mWakeupAlarms.keyAt(i));
9524 mWakeupAlarms.valueAt(i).writeToParcel(out);
9525 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009526
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009527 final int NS = mServiceStats.size();
9528 out.writeInt(NS);
9529 for (int i=0; i<NS; i++) {
9530 out.writeString(mServiceStats.keyAt(i));
9531 Uid.Pkg.Serv serv = mServiceStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009532 serv.writeToParcelLocked(out);
9533 }
9534 }
9535
9536 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009537 public ArrayMap<String, ? extends BatteryStats.Counter> getWakeupAlarmStats() {
9538 return mWakeupAlarms;
9539 }
9540
9541 public void noteWakeupAlarmLocked(String tag) {
9542 Counter c = mWakeupAlarms.get(tag);
9543 if (c == null) {
Bookatz98d4d5c2017-08-01 19:07:54 -07009544 c = new Counter(mBsi.mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009545 mWakeupAlarms.put(tag, c);
9546 }
9547 c.stepAtomic();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009548 }
9549
9550 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009551 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg.Serv> getServiceStats() {
9552 return mServiceStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009553 }
9554
9555 /**
9556 * The statistics associated with a particular service.
9557 */
Joe Onoratoabded112016-02-08 16:49:39 -08009558 public static class Serv extends BatteryStats.Uid.Pkg.Serv implements TimeBaseObs {
9559 /**
9560 * BatteryStatsImpl that we are associated with.
9561 */
9562 protected BatteryStatsImpl mBsi;
9563
9564 /**
9565 * The android package in which this service resides.
9566 */
9567 protected Pkg mPkg;
9568
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009569 /**
9570 * Total time (ms in battery uptime) the service has been left started.
9571 */
Joe Onoratoabded112016-02-08 16:49:39 -08009572 protected long mStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009573
9574 /**
9575 * If service has been started and not yet stopped, this is
9576 * when it was started.
9577 */
Joe Onoratoabded112016-02-08 16:49:39 -08009578 protected long mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009579
9580 /**
9581 * True if we are currently running.
9582 */
Joe Onoratoabded112016-02-08 16:49:39 -08009583 protected boolean mRunning;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009584
9585 /**
9586 * Total number of times startService() has been called.
9587 */
Joe Onoratoabded112016-02-08 16:49:39 -08009588 protected int mStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009589
9590 /**
9591 * Total time (ms in battery uptime) the service has been left launched.
9592 */
Joe Onoratoabded112016-02-08 16:49:39 -08009593 protected long mLaunchedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009594
9595 /**
9596 * If service has been launched and not yet exited, this is
9597 * when it was launched (ms in battery uptime).
9598 */
Joe Onoratoabded112016-02-08 16:49:39 -08009599 protected long mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009600
9601 /**
9602 * True if we are currently launched.
9603 */
Joe Onoratoabded112016-02-08 16:49:39 -08009604 protected boolean mLaunched;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009605
9606 /**
9607 * Total number times the service has been launched.
9608 */
Joe Onoratoabded112016-02-08 16:49:39 -08009609 protected int mLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009610
9611 /**
9612 * The amount of time spent started loaded from a previous save
9613 * (ms in battery uptime).
9614 */
Joe Onoratoabded112016-02-08 16:49:39 -08009615 protected long mLoadedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009616
9617 /**
9618 * The number of starts loaded from a previous save.
9619 */
Joe Onoratoabded112016-02-08 16:49:39 -08009620 protected int mLoadedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009621
9622 /**
9623 * The number of launches loaded from a previous save.
9624 */
Joe Onoratoabded112016-02-08 16:49:39 -08009625 protected int mLoadedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009626
9627 /**
9628 * The amount of time spent started as of the last run (ms
9629 * in battery uptime).
9630 */
Joe Onoratoabded112016-02-08 16:49:39 -08009631 protected long mLastStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009632
9633 /**
9634 * The number of starts as of the last run.
9635 */
Joe Onoratoabded112016-02-08 16:49:39 -08009636 protected int mLastStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009637
9638 /**
9639 * The number of launches as of the last run.
9640 */
Joe Onoratoabded112016-02-08 16:49:39 -08009641 protected int mLastLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009642
9643 /**
9644 * The amount of time spent started when last unplugged (ms
9645 * in battery uptime).
9646 */
Joe Onoratoabded112016-02-08 16:49:39 -08009647 protected long mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009648
9649 /**
9650 * The number of starts when last unplugged.
9651 */
Joe Onoratoabded112016-02-08 16:49:39 -08009652 protected int mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009653
9654 /**
9655 * The number of launches when last unplugged.
9656 */
Joe Onoratoabded112016-02-08 16:49:39 -08009657 protected int mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009658
Joe Onoratoabded112016-02-08 16:49:39 -08009659 /**
9660 * Construct a Serv. Also adds it to the on-battery time base as a listener.
9661 */
9662 public Serv(BatteryStatsImpl bsi) {
9663 mBsi = bsi;
9664 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009665 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009666
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009667 public void onTimeStarted(long elapsedRealtime, long baseUptime,
9668 long baseRealtime) {
9669 mUnpluggedStartTime = getStartTimeToNowLocked(baseUptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009670 mUnpluggedStarts = mStarts;
9671 mUnpluggedLaunches = mLaunches;
9672 }
9673
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009674 public void onTimeStopped(long elapsedRealtime, long baseUptime,
9675 long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009676 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009677
Joe Onoratoabded112016-02-08 16:49:39 -08009678 /**
9679 * Remove this Serv as a listener from the time base.
9680 */
9681 public void detach() {
9682 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009683 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009684
Joe Onoratoabded112016-02-08 16:49:39 -08009685 public void readFromParcelLocked(Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009686 mStartTime = in.readLong();
9687 mRunningSince = in.readLong();
9688 mRunning = in.readInt() != 0;
9689 mStarts = in.readInt();
9690 mLaunchedTime = in.readLong();
9691 mLaunchedSince = in.readLong();
9692 mLaunched = in.readInt() != 0;
9693 mLaunches = in.readInt();
9694 mLoadedStartTime = in.readLong();
9695 mLoadedStarts = in.readInt();
9696 mLoadedLaunches = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07009697 mLastStartTime = 0;
9698 mLastStarts = 0;
9699 mLastLaunches = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009700 mUnpluggedStartTime = in.readLong();
9701 mUnpluggedStarts = in.readInt();
9702 mUnpluggedLaunches = in.readInt();
9703 }
9704
Joe Onoratoabded112016-02-08 16:49:39 -08009705 public void writeToParcelLocked(Parcel out) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009706 out.writeLong(mStartTime);
9707 out.writeLong(mRunningSince);
9708 out.writeInt(mRunning ? 1 : 0);
9709 out.writeInt(mStarts);
9710 out.writeLong(mLaunchedTime);
9711 out.writeLong(mLaunchedSince);
9712 out.writeInt(mLaunched ? 1 : 0);
9713 out.writeInt(mLaunches);
9714 out.writeLong(mLoadedStartTime);
9715 out.writeInt(mLoadedStarts);
9716 out.writeInt(mLoadedLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009717 out.writeLong(mUnpluggedStartTime);
9718 out.writeInt(mUnpluggedStarts);
9719 out.writeInt(mUnpluggedLaunches);
9720 }
9721
Joe Onoratoabded112016-02-08 16:49:39 -08009722 public long getLaunchTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009723 if (!mLaunched) return mLaunchedTime;
9724 return mLaunchedTime + batteryUptime - mLaunchedSince;
9725 }
9726
Joe Onoratoabded112016-02-08 16:49:39 -08009727 public long getStartTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009728 if (!mRunning) return mStartTime;
9729 return mStartTime + batteryUptime - mRunningSince;
9730 }
9731
Mathew Inwoodc185f082018-08-20 14:28:54 +01009732 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009733 public void startLaunchedLocked() {
9734 if (!mLaunched) {
9735 mLaunches++;
Joe Onoratoabded112016-02-08 16:49:39 -08009736 mLaunchedSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009737 mLaunched = true;
9738 }
9739 }
9740
Mathew Inwoodc185f082018-08-20 14:28:54 +01009741 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009742 public void stopLaunchedLocked() {
9743 if (mLaunched) {
Joe Onoratoabded112016-02-08 16:49:39 -08009744 long time = mBsi.getBatteryUptimeLocked() - mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009745 if (time > 0) {
9746 mLaunchedTime += time;
9747 } else {
9748 mLaunches--;
9749 }
9750 mLaunched = false;
9751 }
9752 }
9753
Mathew Inwoodc185f082018-08-20 14:28:54 +01009754 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009755 public void startRunningLocked() {
9756 if (!mRunning) {
9757 mStarts++;
Joe Onoratoabded112016-02-08 16:49:39 -08009758 mRunningSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009759 mRunning = true;
9760 }
9761 }
9762
Mathew Inwoodc185f082018-08-20 14:28:54 +01009763 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009764 public void stopRunningLocked() {
9765 if (mRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08009766 long time = mBsi.getBatteryUptimeLocked() - mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009767 if (time > 0) {
9768 mStartTime += time;
9769 } else {
9770 mStarts--;
9771 }
9772 mRunning = false;
9773 }
9774 }
9775
Mathew Inwoodc185f082018-08-20 14:28:54 +01009776 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009777 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -08009778 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009779 }
9780
9781 @Override
9782 public int getLaunches(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009783 int val = mLaunches;
9784 if (which == STATS_CURRENT) {
9785 val -= mLoadedLaunches;
9786 } else if (which == STATS_SINCE_UNPLUGGED) {
9787 val -= mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009788 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009789 return val;
9790 }
9791
9792 @Override
9793 public long getStartTime(long now, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009794 long val = getStartTimeToNowLocked(now);
9795 if (which == STATS_CURRENT) {
9796 val -= mLoadedStartTime;
9797 } else if (which == STATS_SINCE_UNPLUGGED) {
9798 val -= mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009799 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009800 return val;
9801 }
9802
9803 @Override
9804 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009805 int val = mStarts;
9806 if (which == STATS_CURRENT) {
9807 val -= mLoadedStarts;
9808 } else if (which == STATS_SINCE_UNPLUGGED) {
9809 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009810 }
9811
9812 return val;
9813 }
9814 }
9815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009816 final Serv newServiceStatsLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08009817 return new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009818 }
9819 }
9820
9821 /**
9822 * Retrieve the statistics object for a particular process, creating
9823 * if needed.
9824 */
9825 public Proc getProcessStatsLocked(String name) {
9826 Proc ps = mProcessStats.get(name);
9827 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08009828 ps = new Proc(mBsi, name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009829 mProcessStats.put(name, ps);
9830 }
9831
9832 return ps;
9833 }
9834
Andreas Gampe3f24e692018-02-05 13:24:28 -08009835 @GuardedBy("mBsi")
Dianne Hackborna8d10942015-11-19 17:55:19 -08009836 public void updateUidProcessStateLocked(int procState) {
9837 int uidRunningState;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009838 // Make special note of Foreground Services
9839 final boolean userAwareService =
9840 (procState == ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009841 uidRunningState = BatteryStats.mapToInternalProcessState(procState);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009842
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009843 if (mProcessState == uidRunningState && userAwareService == mInForegroundService) {
9844 return;
9845 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08009846
Bookatz867c0d72017-03-07 18:23:42 -08009847 final long elapsedRealtimeMs = mBsi.mClocks.elapsedRealtime();
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009848 if (mProcessState != uidRunningState) {
9849 final long uptimeMs = mBsi.mClocks.uptimeMillis();
Dianne Hackborna8d10942015-11-19 17:55:19 -08009850
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009851 if (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
9852 mProcessStateTimer[mProcessState].stopRunningLocked(elapsedRealtimeMs);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009853
Sudheer Shanka5c19b892018-01-05 17:25:46 -08009854 if (mBsi.trackPerProcStateCpuTimes()) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009855 if (mBsi.mPendingUids.size() == 0) {
Sudheer Shankae544d162017-12-28 17:06:20 -08009856 mBsi.mExternalSync.scheduleReadProcStateCpuTimes(
9857 mBsi.mOnBatteryTimeBase.isRunning(),
Sudheer Shankac20379e2018-02-15 00:06:21 -08009858 mBsi.mOnBatteryScreenOffTimeBase.isRunning(),
9859 mBsi.mConstants.PROC_STATE_CPU_TIMES_READ_DELAY_MS);
Mike Ma234d1822018-03-13 18:53:21 -07009860 mBsi.mNumSingleUidCpuTimeReads++;
Sudheer Shankac20379e2018-02-15 00:06:21 -08009861 } else {
Mike Ma234d1822018-03-13 18:53:21 -07009862 mBsi.mNumBatchedSingleUidCpuTimeReads++;
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009863 }
9864 if (mBsi.mPendingUids.indexOfKey(mUid) < 0
9865 || ArrayUtils.contains(CRITICAL_PROC_STATES, mProcessState)) {
9866 mBsi.mPendingUids.put(mUid, mProcessState);
9867 }
9868 } else {
9869 mBsi.mPendingUids.clear();
9870 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07009871 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009872 mProcessState = uidRunningState;
9873 if (uidRunningState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
9874 if (mProcessStateTimer[uidRunningState] == null) {
9875 makeProcessState(uidRunningState, null);
9876 }
9877 mProcessStateTimer[uidRunningState].startRunningLocked(elapsedRealtimeMs);
9878 }
9879
9880 updateOnBatteryBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
9881 updateOnBatteryScreenOffBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009882 }
Bookatz867c0d72017-03-07 18:23:42 -08009883
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009884 if (userAwareService != mInForegroundService) {
9885 if (userAwareService) {
9886 noteForegroundServiceResumedLocked(elapsedRealtimeMs);
9887 } else {
9888 noteForegroundServicePausedLocked(elapsedRealtimeMs);
9889 }
9890 mInForegroundService = userAwareService;
9891 }
Bookatz867c0d72017-03-07 18:23:42 -08009892 }
9893
Bookatzc8c44962017-05-11 12:12:54 -07009894 /** Whether to consider Uid to be in the background for background timebase purposes. */
9895 public boolean isInBackground() {
Bookatz867c0d72017-03-07 18:23:42 -08009896 // Note that PROCESS_STATE_CACHED and ActivityManager.PROCESS_STATE_NONEXISTENT is
9897 // also considered to be 'background' for our purposes, because it's not foreground.
Bookatzc8c44962017-05-11 12:12:54 -07009898 return mProcessState >= PROCESS_STATE_BACKGROUND;
9899 }
9900
9901 public boolean updateOnBatteryBgTimeBase(long uptimeUs, long realtimeUs) {
9902 boolean on = mBsi.mOnBatteryTimeBase.isRunning() && isInBackground();
9903 return mOnBatteryBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
9904 }
9905
9906 public boolean updateOnBatteryScreenOffBgTimeBase(long uptimeUs, long realtimeUs) {
9907 boolean on = mBsi.mOnBatteryScreenOffTimeBase.isRunning() && isInBackground();
9908 return mOnBatteryScreenOffBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009909 }
9910
Dianne Hackbornb5e31652010-09-07 12:13:55 -07009911 public SparseArray<? extends Pid> getPidStats() {
9912 return mPids;
9913 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009914
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009915 public Pid getPidStatsLocked(int pid) {
9916 Pid p = mPids.get(pid);
9917 if (p == null) {
9918 p = new Pid();
9919 mPids.put(pid, p);
9920 }
9921 return p;
9922 }
9923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009924 /**
9925 * Retrieve the statistics object for a particular service, creating
9926 * if needed.
9927 */
9928 public Pkg getPackageStatsLocked(String name) {
9929 Pkg ps = mPackageStats.get(name);
9930 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08009931 ps = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009932 mPackageStats.put(name, ps);
9933 }
9934
9935 return ps;
9936 }
9937
9938 /**
9939 * Retrieve the statistics object for a particular service, creating
9940 * if needed.
9941 */
9942 public Pkg.Serv getServiceStatsLocked(String pkg, String serv) {
9943 Pkg ps = getPackageStatsLocked(pkg);
9944 Pkg.Serv ss = ps.mServiceStats.get(serv);
9945 if (ss == null) {
9946 ss = ps.newServiceStatsLocked();
9947 ps.mServiceStats.put(serv, ss);
9948 }
9949
9950 return ss;
9951 }
9952
Dianne Hackbornd953c532014-08-16 18:17:38 -07009953 public void readSyncSummaryFromParcelLocked(String name, Parcel in) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009954 DualTimer timer = mSyncStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07009955 timer.readSummaryFromParcelLocked(in);
9956 mSyncStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009957 }
9958
Dianne Hackbornd953c532014-08-16 18:17:38 -07009959 public void readJobSummaryFromParcelLocked(String name, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07009960 DualTimer timer = mJobStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07009961 timer.readSummaryFromParcelLocked(in);
9962 mJobStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009963 }
9964
Dianne Hackbornd953c532014-08-16 18:17:38 -07009965 public void readWakeSummaryFromParcelLocked(String wlName, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08009966 Wakelock wl = new Wakelock(mBsi, this);
Dianne Hackbornd953c532014-08-16 18:17:38 -07009967 mWakelockStats.add(wlName, wl);
9968 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009969 getWakelockTimerLocked(wl, WAKE_TYPE_FULL).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009970 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07009971 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009972 getWakelockTimerLocked(wl, WAKE_TYPE_PARTIAL).readSummaryFromParcelLocked(in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07009973 }
9974 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009975 getWakelockTimerLocked(wl, WAKE_TYPE_WINDOW).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009976 }
Adam Lesinski9425fe22015-06-19 12:02:13 -07009977 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009978 getWakelockTimerLocked(wl, WAKE_TYPE_DRAW).readSummaryFromParcelLocked(in);
Adam Lesinski9425fe22015-06-19 12:02:13 -07009979 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009980 }
9981
Bookatz867c0d72017-03-07 18:23:42 -08009982 public DualTimer getSensorTimerLocked(int sensor, boolean create) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009983 Sensor se = mSensorStats.get(sensor);
9984 if (se == null) {
9985 if (!create) {
9986 return null;
9987 }
Joe Onoratoabded112016-02-08 16:49:39 -08009988 se = new Sensor(mBsi, this, sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009989 mSensorStats.put(sensor, se);
9990 }
Bookatz867c0d72017-03-07 18:23:42 -08009991 DualTimer t = se.mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009992 if (t != null) {
9993 return t;
9994 }
Joe Onoratoabded112016-02-08 16:49:39 -08009995 ArrayList<StopwatchTimer> timers = mBsi.mSensorTimers.get(sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009996 if (timers == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07009997 timers = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08009998 mBsi.mSensorTimers.put(sensor, timers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009999 }
Bookatz867c0d72017-03-07 18:23:42 -080010000 t = new DualTimer(mBsi.mClocks, this, BatteryStats.SENSOR, timers,
10001 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010002 se.mTimer = t;
10003 return t;
10004 }
10005
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010006 public void noteStartSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -070010007 DualTimer t = mSyncStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010008 if (t != null) {
10009 t.startRunningLocked(elapsedRealtimeMs);
10010 }
10011 }
10012
10013 public void noteStopSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -070010014 DualTimer t = mSyncStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010015 if (t != null) {
10016 t.stopRunningLocked(elapsedRealtimeMs);
10017 }
10018 }
10019
10020 public void noteStartJobLocked(String name, long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -070010021 DualTimer t = mJobStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010022 if (t != null) {
10023 t.startRunningLocked(elapsedRealtimeMs);
10024 }
10025 }
10026
Dianne Hackborn94326cb2017-06-28 16:17:20 -070010027 public void noteStopJobLocked(String name, long elapsedRealtimeMs, int stopReason) {
Bookatzaa4594a2017-03-24 12:39:56 -070010028 DualTimer t = mJobStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010029 if (t != null) {
10030 t.stopRunningLocked(elapsedRealtimeMs);
10031 }
Dianne Hackborn94326cb2017-06-28 16:17:20 -070010032 if (mBsi.mOnBatteryTimeBase.isRunning()) {
10033 SparseIntArray types = mJobCompletions.get(name);
10034 if (types == null) {
10035 types = new SparseIntArray();
10036 mJobCompletions.put(name, types);
10037 }
10038 int last = types.get(stopReason, 0);
10039 types.put(stopReason, last + 1);
10040 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010041 }
10042
Bookatz5b5ec322017-05-26 09:40:38 -070010043 public StopwatchTimer getWakelockTimerLocked(Wakelock wl, int type) {
10044 if (wl == null) {
10045 return null;
10046 }
10047 switch (type) {
10048 case WAKE_TYPE_PARTIAL: {
10049 DualTimer t = wl.mTimerPartial;
10050 if (t == null) {
10051 t = new DualTimer(mBsi.mClocks, this, WAKE_TYPE_PARTIAL,
10052 mBsi.mPartialTimers, mBsi.mOnBatteryScreenOffTimeBase,
10053 mOnBatteryScreenOffBackgroundTimeBase);
10054 wl.mTimerPartial = t;
10055 }
10056 return t;
10057 }
10058 case WAKE_TYPE_FULL: {
10059 StopwatchTimer t = wl.mTimerFull;
10060 if (t == null) {
10061 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_FULL,
10062 mBsi.mFullTimers, mBsi.mOnBatteryTimeBase);
10063 wl.mTimerFull = t;
10064 }
10065 return t;
10066 }
10067 case WAKE_TYPE_WINDOW: {
10068 StopwatchTimer t = wl.mTimerWindow;
10069 if (t == null) {
10070 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_WINDOW,
10071 mBsi.mWindowTimers, mBsi.mOnBatteryTimeBase);
10072 wl.mTimerWindow = t;
10073 }
10074 return t;
10075 }
10076 case WAKE_TYPE_DRAW: {
10077 StopwatchTimer t = wl.mTimerDraw;
10078 if (t == null) {
10079 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_DRAW,
10080 mBsi.mDrawTimers, mBsi.mOnBatteryTimeBase);
10081 wl.mTimerDraw = t;
10082 }
10083 return t;
10084 }
10085 default:
10086 throw new IllegalArgumentException("type=" + type);
10087 }
10088 }
10089
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010090 public void noteStartWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070010091 Wakelock wl = mWakelockStats.startObject(name);
10092 if (wl != null) {
Bookatz5b5ec322017-05-26 09:40:38 -070010093 getWakelockTimerLocked(wl, type).startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010094 }
Bookatzc8c44962017-05-11 12:12:54 -070010095 if (type == WAKE_TYPE_PARTIAL) {
10096 createAggregatedPartialWakelockTimerLocked().startRunningLocked(elapsedRealtimeMs);
10097 if (pid >= 0) {
10098 Pid p = getPidStatsLocked(pid);
10099 if (p.mWakeNesting++ == 0) {
10100 p.mWakeStartMs = elapsedRealtimeMs;
10101 }
Dianne Hackbornb8071d792010-09-09 16:45:15 -070010102 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010103 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010104 }
10105
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010106 public void noteStopWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070010107 Wakelock wl = mWakelockStats.stopObject(name);
10108 if (wl != null) {
Bookatzd6746242017-10-24 18:39:35 -070010109 StopwatchTimer wlt = getWakelockTimerLocked(wl, type);
10110 wlt.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010111 }
Bookatzc8c44962017-05-11 12:12:54 -070010112 if (type == WAKE_TYPE_PARTIAL) {
10113 if (mAggregatedPartialWakelockTimer != null) {
10114 mAggregatedPartialWakelockTimer.stopRunningLocked(elapsedRealtimeMs);
10115 }
10116 if (pid >= 0) {
10117 Pid p = mPids.get(pid);
10118 if (p != null && p.mWakeNesting > 0) {
10119 if (p.mWakeNesting-- == 1) {
10120 p.mWakeSumMs += elapsedRealtimeMs - p.mWakeStartMs;
10121 p.mWakeStartMs = 0;
10122 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -080010123 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010124 }
10125 }
10126 }
10127
Dianne Hackborn287952c2010-09-22 22:34:31 -070010128 public void reportExcessiveCpuLocked(String proc, long overTime, long usedTime) {
10129 Proc p = getProcessStatsLocked(proc);
10130 if (p != null) {
10131 p.addExcessiveCpu(overTime, usedTime);
10132 }
10133 }
10134
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010135 public void noteStartSensor(int sensor, long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -080010136 DualTimer t = getSensorTimerLocked(sensor, /* create= */ true);
Amith Yamasani154d1242017-02-16 10:01:48 -080010137 t.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010138 }
10139
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010140 public void noteStopSensor(int sensor, long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010141 // Don't create a timer if one doesn't already exist
Bookatz867c0d72017-03-07 18:23:42 -080010142 DualTimer t = getSensorTimerLocked(sensor, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010143 if (t != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010144 t.stopRunningLocked(elapsedRealtimeMs);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010146 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010147
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010148 public void noteStartGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -080010149 noteStartSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010150 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010151
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010152 public void noteStopGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -080010153 noteStopSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010154 }
10155
10156 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -080010157 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010158 }
10159 }
10160
Sudheer Shanka9b735c52017-05-09 18:26:18 -070010161 public long[] getCpuFreqs() {
10162 return mCpuFreqs;
10163 }
10164
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010165 public BatteryStatsImpl(File systemDir, Handler handler, PlatformIdleStateCallback cb,
10166 UserInfoProvider userInfoProvider) {
10167 this(new SystemClocks(), systemDir, handler, cb, userInfoProvider);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010168 }
10169
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010170 private BatteryStatsImpl(Clocks clocks, File systemDir, Handler handler,
10171 PlatformIdleStateCallback cb,
10172 UserInfoProvider userInfoProvider) {
Joe Onoratoabded112016-02-08 16:49:39 -080010173 init(clocks);
10174
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010175 if (systemDir != null) {
10176 mFile = new JournaledFile(new File(systemDir, "batterystats.bin"),
10177 new File(systemDir, "batterystats.bin.tmp"));
10178 } else {
10179 mFile = null;
10180 }
10181 mCheckinFile = new AtomicFile(new File(systemDir, "batterystats-checkin.bin"));
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010182 mDailyFile = new AtomicFile(new File(systemDir, "batterystats-daily.xml"));
Jeff Brown6f357d32014-01-15 20:40:55 -080010183 mHandler = new MyHandler(handler.getLooper());
Sudheer Shanka5c19b892018-01-05 17:25:46 -080010184 mConstants = new Constants(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010185 mStartCount++;
Joe Onoratoabded112016-02-08 16:49:39 -080010186 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -070010187 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -070010188 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010189 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010190 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010191 }
Joe Onoratoabded112016-02-08 16:49:39 -080010192 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase);
10193 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
10194 mOnBatteryTimeBase);
10195 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -11, null,
10196 mOnBatteryTimeBase);
10197 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
10198 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null, mOnBatteryTimeBase);
10199 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase);
10200 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase);
10201 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
10202 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i, null,
10203 mOnBatteryTimeBase);
10204 }
10205 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
10206 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010207 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010208 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010209 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010210 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010211 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010212 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
10213 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010214 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010215 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase, NUM_WIFI_TX_LEVELS);
10216 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
10217 NUM_BT_TX_LEVELS);
10218 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
10219 ModemActivityInfo.TX_POWER_LEVELS);
Joe Onoratoabded112016-02-08 16:49:39 -080010220 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null, mOnBatteryTimeBase);
10221 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
10222 mOnBatteryTimeBase);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010223 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010224 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase);
10225 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080010226 mWifiMulticastWakelockTimer = new StopwatchTimer(mClocks, null,
10227 WIFI_AGGREGATE_MULTICAST_ENABLED, null, mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -080010228 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase);
10229 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null, mOnBatteryTimeBase);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010230 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010231 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i, null,
Dianne Hackborn3251b902014-06-20 14:40:53 -070010232 mOnBatteryTimeBase);
10233 }
Joe Onoratoabded112016-02-08 16:49:39 -080010234 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
10235 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i, null,
10236 mOnBatteryTimeBase);
10237 }
10238 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
10239 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i, null,
10240 mOnBatteryTimeBase);
10241 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080010242 mWifiActiveTimer = new StopwatchTimer(mClocks, null, -900, null, mOnBatteryTimeBase);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080010243 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
10244 mGpsSignalQualityTimer[i] = new StopwatchTimer(mClocks, null, -1000-i, null,
10245 mOnBatteryTimeBase);
10246 }
Joe Onoratoabded112016-02-08 16:49:39 -080010247 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
10248 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
10249 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase);
10250 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase);
10251 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010252 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -070010253 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Mike Ma15313c92017-11-15 17:58:21 -080010254 mDischargeLightDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
10255 mDischargeDeepDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010256 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010257 mOnBattery = mOnBatteryInternal = false;
Joe Onoratoabded112016-02-08 16:49:39 -080010258 long uptime = mClocks.uptimeMillis() * 1000;
10259 long realtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010260 initTimes(uptime, realtime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070010261 mStartPlatformVersion = mEndPlatformVersion = Build.ID;
Evan Millar633a1742009-04-02 16:36:33 -070010262 mDischargeStartLevel = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010263 mDischargeUnplugLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010264 mDischargePlugLevel = -1;
Evan Millar633a1742009-04-02 16:36:33 -070010265 mDischargeCurrentLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010266 mCurrentBatteryLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010267 initDischarge();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010268 clearHistoryLocked();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010269 updateDailyDeadlineLocked();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010270 mPlatformIdleStateCallback = cb;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010271 mUserInfoProvider = userInfoProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010272 }
10273
Mathew Inwoodc185f082018-08-20 14:28:54 +010010274 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010275 public BatteryStatsImpl(Parcel p) {
Joe Onoratoabded112016-02-08 16:49:39 -080010276 this(new SystemClocks(), p);
10277 }
10278
10279 public BatteryStatsImpl(Clocks clocks, Parcel p) {
10280 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070010281 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010282 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010283 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -070010284 mHandler = null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010285 mExternalSync = null;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080010286 mConstants = new Constants(mHandler);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010287 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010288 readFromParcel(p);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010289 mPlatformIdleStateCallback = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010290 }
10291
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010292 public void setPowerProfileLocked(PowerProfile profile) {
10293 mPowerProfile = profile;
Adam Lesinski6832f392015-09-05 18:05:40 -070010294
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010295 // We need to initialize the KernelCpuSpeedReaders to read from
10296 // the first cpu of each core. Once we have the PowerProfile, we have access to this
10297 // information.
10298 final int numClusters = mPowerProfile.getNumCpuClusters();
10299 mKernelCpuSpeedReaders = new KernelCpuSpeedReader[numClusters];
10300 int firstCpuOfCluster = 0;
10301 for (int i = 0; i < numClusters; i++) {
10302 final int numSpeedSteps = mPowerProfile.getNumSpeedStepsInCpuCluster(i);
10303 mKernelCpuSpeedReaders[i] = new KernelCpuSpeedReader(firstCpuOfCluster,
10304 numSpeedSteps);
10305 firstCpuOfCluster += mPowerProfile.getNumCoresInCpuCluster(i);
10306 }
Adam Lesinskif9b20a92016-06-17 17:30:01 -070010307
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010308 if (mEstimatedBatteryCapacity == -1) {
10309 // Initialize the estimated battery capacity to a known preset one.
10310 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
Adam Lesinskie08af192015-03-25 16:42:59 -070010311 }
10312 }
10313
Dianne Hackborn0d903a82010-09-07 23:51:03 -070010314 public void setCallback(BatteryCallback cb) {
10315 mCallback = cb;
10316 }
10317
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010318 public void setRadioScanningTimeoutLocked(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -070010319 if (mPhoneSignalScanningTimer != null) {
10320 mPhoneSignalScanningTimer.setTimeout(timeout);
10321 }
10322 }
10323
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070010324 public void setExternalStatsSyncLocked(ExternalStatsSync sync) {
10325 mExternalSync = sync;
10326 }
10327
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010328 public void updateDailyDeadlineLocked() {
10329 // Get the current time.
10330 long currentTime = mDailyStartTime = System.currentTimeMillis();
10331 Calendar calDeadline = Calendar.getInstance();
10332 calDeadline.setTimeInMillis(currentTime);
10333
10334 // Move time up to the next day, ranging from 1am to 3pm.
10335 calDeadline.set(Calendar.DAY_OF_YEAR, calDeadline.get(Calendar.DAY_OF_YEAR) + 1);
10336 calDeadline.set(Calendar.MILLISECOND, 0);
10337 calDeadline.set(Calendar.SECOND, 0);
10338 calDeadline.set(Calendar.MINUTE, 0);
10339 calDeadline.set(Calendar.HOUR_OF_DAY, 1);
10340 mNextMinDailyDeadline = calDeadline.getTimeInMillis();
10341 calDeadline.set(Calendar.HOUR_OF_DAY, 3);
10342 mNextMaxDailyDeadline = calDeadline.getTimeInMillis();
10343 }
10344
10345 public void recordDailyStatsIfNeededLocked(boolean settled) {
10346 long currentTime = System.currentTimeMillis();
10347 if (currentTime >= mNextMaxDailyDeadline) {
10348 recordDailyStatsLocked();
10349 } else if (settled && currentTime >= mNextMinDailyDeadline) {
10350 recordDailyStatsLocked();
10351 } else if (currentTime < (mDailyStartTime-(1000*60*60*24))) {
10352 recordDailyStatsLocked();
10353 }
10354 }
10355
10356 public void recordDailyStatsLocked() {
10357 DailyItem item = new DailyItem();
10358 item.mStartTime = mDailyStartTime;
10359 item.mEndTime = System.currentTimeMillis();
10360 boolean hasData = false;
10361 if (mDailyDischargeStepTracker.mNumStepDurations > 0) {
10362 hasData = true;
10363 item.mDischargeSteps = new LevelStepTracker(
10364 mDailyDischargeStepTracker.mNumStepDurations,
10365 mDailyDischargeStepTracker.mStepDurations);
10366 }
10367 if (mDailyChargeStepTracker.mNumStepDurations > 0) {
10368 hasData = true;
10369 item.mChargeSteps = new LevelStepTracker(
10370 mDailyChargeStepTracker.mNumStepDurations,
10371 mDailyChargeStepTracker.mStepDurations);
10372 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010373 if (mDailyPackageChanges != null) {
10374 hasData = true;
10375 item.mPackageChanges = mDailyPackageChanges;
10376 mDailyPackageChanges = null;
10377 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010378 mDailyDischargeStepTracker.init();
10379 mDailyChargeStepTracker.init();
10380 updateDailyDeadlineLocked();
10381
10382 if (hasData) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080010383 final long startTime = SystemClock.uptimeMillis();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010384 mDailyItems.add(item);
10385 while (mDailyItems.size() > MAX_DAILY_ITEMS) {
10386 mDailyItems.remove(0);
10387 }
10388 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
10389 try {
10390 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010010391 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010392 writeDailyItemsLocked(out);
Dianne Hackborne17b4452018-01-10 13:15:40 -080010393 final long initialTime = SystemClock.uptimeMillis() - startTime;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010394 BackgroundThread.getHandler().post(new Runnable() {
10395 @Override
10396 public void run() {
10397 synchronized (mCheckinFile) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080010398 final long startTime2 = SystemClock.uptimeMillis();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010399 FileOutputStream stream = null;
10400 try {
10401 stream = mDailyFile.startWrite();
10402 memStream.writeTo(stream);
10403 stream.flush();
10404 FileUtils.sync(stream);
10405 stream.close();
10406 mDailyFile.finishWrite(stream);
Dianne Hackborne17b4452018-01-10 13:15:40 -080010407 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
10408 "batterystats-daily",
10409 initialTime + SystemClock.uptimeMillis() - startTime2);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010410 } catch (IOException e) {
10411 Slog.w("BatteryStats",
10412 "Error writing battery daily items", e);
10413 mDailyFile.failWrite(stream);
10414 }
10415 }
10416 }
10417 });
10418 } catch (IOException e) {
10419 }
10420 }
10421 }
10422
10423 private void writeDailyItemsLocked(XmlSerializer out) throws IOException {
10424 StringBuilder sb = new StringBuilder(64);
10425 out.startDocument(null, true);
10426 out.startTag(null, "daily-items");
10427 for (int i=0; i<mDailyItems.size(); i++) {
10428 final DailyItem dit = mDailyItems.get(i);
10429 out.startTag(null, "item");
10430 out.attribute(null, "start", Long.toString(dit.mStartTime));
10431 out.attribute(null, "end", Long.toString(dit.mEndTime));
10432 writeDailyLevelSteps(out, "dis", dit.mDischargeSteps, sb);
10433 writeDailyLevelSteps(out, "chg", dit.mChargeSteps, sb);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010434 if (dit.mPackageChanges != null) {
10435 for (int j=0; j<dit.mPackageChanges.size(); j++) {
10436 PackageChange pc = dit.mPackageChanges.get(j);
10437 if (pc.mUpdate) {
10438 out.startTag(null, "upd");
10439 out.attribute(null, "pkg", pc.mPackageName);
Dianne Hackborn3accca02013-09-20 09:32:11 -070010440 out.attribute(null, "ver", Long.toString(pc.mVersionCode));
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010441 out.endTag(null, "upd");
10442 } else {
10443 out.startTag(null, "rem");
10444 out.attribute(null, "pkg", pc.mPackageName);
10445 out.endTag(null, "rem");
10446 }
10447 }
10448 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010449 out.endTag(null, "item");
10450 }
10451 out.endTag(null, "daily-items");
10452 out.endDocument();
10453 }
10454
10455 private void writeDailyLevelSteps(XmlSerializer out, String tag, LevelStepTracker steps,
10456 StringBuilder tmpBuilder) throws IOException {
10457 if (steps != null) {
10458 out.startTag(null, tag);
10459 out.attribute(null, "n", Integer.toString(steps.mNumStepDurations));
10460 for (int i=0; i<steps.mNumStepDurations; i++) {
10461 out.startTag(null, "s");
10462 tmpBuilder.setLength(0);
10463 steps.encodeEntryAt(i, tmpBuilder);
10464 out.attribute(null, "v", tmpBuilder.toString());
10465 out.endTag(null, "s");
10466 }
10467 out.endTag(null, tag);
10468 }
10469 }
10470
10471 public void readDailyStatsLocked() {
10472 Slog.d(TAG, "Reading daily items from " + mDailyFile.getBaseFile());
10473 mDailyItems.clear();
10474 FileInputStream stream;
10475 try {
10476 stream = mDailyFile.openRead();
10477 } catch (FileNotFoundException e) {
10478 return;
10479 }
10480 try {
10481 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010010482 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010483 readDailyItemsLocked(parser);
10484 } catch (XmlPullParserException e) {
10485 } finally {
10486 try {
10487 stream.close();
10488 } catch (IOException e) {
10489 }
10490 }
10491 }
10492
10493 private void readDailyItemsLocked(XmlPullParser parser) {
10494 try {
10495 int type;
10496 while ((type = parser.next()) != XmlPullParser.START_TAG
10497 && type != XmlPullParser.END_DOCUMENT) {
10498 ;
10499 }
10500
10501 if (type != XmlPullParser.START_TAG) {
10502 throw new IllegalStateException("no start tag found");
10503 }
10504
10505 int outerDepth = parser.getDepth();
10506 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10507 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10508 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10509 continue;
10510 }
10511
10512 String tagName = parser.getName();
10513 if (tagName.equals("item")) {
10514 readDailyItemTagLocked(parser);
10515 } else {
10516 Slog.w(TAG, "Unknown element under <daily-items>: "
10517 + parser.getName());
10518 XmlUtils.skipCurrentTag(parser);
10519 }
10520 }
10521
10522 } catch (IllegalStateException e) {
10523 Slog.w(TAG, "Failed parsing daily " + e);
10524 } catch (NullPointerException e) {
10525 Slog.w(TAG, "Failed parsing daily " + e);
10526 } catch (NumberFormatException e) {
10527 Slog.w(TAG, "Failed parsing daily " + e);
10528 } catch (XmlPullParserException e) {
10529 Slog.w(TAG, "Failed parsing daily " + e);
10530 } catch (IOException e) {
10531 Slog.w(TAG, "Failed parsing daily " + e);
10532 } catch (IndexOutOfBoundsException e) {
10533 Slog.w(TAG, "Failed parsing daily " + e);
10534 }
10535 }
10536
10537 void readDailyItemTagLocked(XmlPullParser parser) throws NumberFormatException,
10538 XmlPullParserException, IOException {
10539 DailyItem dit = new DailyItem();
10540 String attr = parser.getAttributeValue(null, "start");
10541 if (attr != null) {
10542 dit.mStartTime = Long.parseLong(attr);
10543 }
10544 attr = parser.getAttributeValue(null, "end");
10545 if (attr != null) {
10546 dit.mEndTime = Long.parseLong(attr);
10547 }
10548 int outerDepth = parser.getDepth();
10549 int type;
10550 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10551 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10552 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10553 continue;
10554 }
10555
10556 String tagName = parser.getName();
10557 if (tagName.equals("dis")) {
10558 readDailyItemTagDetailsLocked(parser, dit, false, "dis");
10559 } else if (tagName.equals("chg")) {
10560 readDailyItemTagDetailsLocked(parser, dit, true, "chg");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010561 } else if (tagName.equals("upd")) {
10562 if (dit.mPackageChanges == null) {
10563 dit.mPackageChanges = new ArrayList<>();
10564 }
10565 PackageChange pc = new PackageChange();
10566 pc.mUpdate = true;
10567 pc.mPackageName = parser.getAttributeValue(null, "pkg");
10568 String verStr = parser.getAttributeValue(null, "ver");
Dianne Hackborn3accca02013-09-20 09:32:11 -070010569 pc.mVersionCode = verStr != null ? Long.parseLong(verStr) : 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010570 dit.mPackageChanges.add(pc);
10571 XmlUtils.skipCurrentTag(parser);
10572 } else if (tagName.equals("rem")) {
10573 if (dit.mPackageChanges == null) {
10574 dit.mPackageChanges = new ArrayList<>();
10575 }
10576 PackageChange pc = new PackageChange();
10577 pc.mUpdate = false;
10578 pc.mPackageName = parser.getAttributeValue(null, "pkg");
10579 dit.mPackageChanges.add(pc);
10580 XmlUtils.skipCurrentTag(parser);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010581 } else {
10582 Slog.w(TAG, "Unknown element under <item>: "
10583 + parser.getName());
10584 XmlUtils.skipCurrentTag(parser);
10585 }
10586 }
10587 mDailyItems.add(dit);
10588 }
10589
10590 void readDailyItemTagDetailsLocked(XmlPullParser parser, DailyItem dit, boolean isCharge,
10591 String tag)
10592 throws NumberFormatException, XmlPullParserException, IOException {
10593 final String numAttr = parser.getAttributeValue(null, "n");
10594 if (numAttr == null) {
10595 Slog.w(TAG, "Missing 'n' attribute at " + parser.getPositionDescription());
10596 XmlUtils.skipCurrentTag(parser);
10597 return;
10598 }
10599 final int num = Integer.parseInt(numAttr);
10600 LevelStepTracker steps = new LevelStepTracker(num);
10601 if (isCharge) {
10602 dit.mChargeSteps = steps;
10603 } else {
10604 dit.mDischargeSteps = steps;
10605 }
10606 int i = 0;
10607 int outerDepth = parser.getDepth();
10608 int type;
10609 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10610 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10611 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10612 continue;
10613 }
10614
10615 String tagName = parser.getName();
10616 if ("s".equals(tagName)) {
10617 if (i < num) {
10618 String valueAttr = parser.getAttributeValue(null, "v");
10619 if (valueAttr != null) {
10620 steps.decodeEntryAt(i, valueAttr);
10621 i++;
10622 }
10623 }
10624 } else {
10625 Slog.w(TAG, "Unknown element under <" + tag + ">: "
10626 + parser.getName());
10627 XmlUtils.skipCurrentTag(parser);
10628 }
10629 }
10630 steps.mNumStepDurations = i;
10631 }
10632
10633 @Override
10634 public DailyItem getDailyItemLocked(int daysAgo) {
10635 int index = mDailyItems.size()-1-daysAgo;
10636 return index >= 0 ? mDailyItems.get(index) : null;
10637 }
10638
10639 @Override
10640 public long getCurrentDailyStartTime() {
10641 return mDailyStartTime;
10642 }
10643
10644 @Override
10645 public long getNextMinDailyDeadline() {
10646 return mNextMinDailyDeadline;
10647 }
10648
10649 @Override
10650 public long getNextMaxDailyDeadline() {
10651 return mNextMaxDailyDeadline;
10652 }
10653
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010654 @Override
10655 public boolean startIteratingOldHistoryLocked() {
10656 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
10657 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010658 if ((mHistoryIterator = mHistory) == null) {
10659 return false;
10660 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010661 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010662 mHistoryReadTmp.clear();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010663 mReadOverflow = false;
10664 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010665 return true;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010666 }
10667
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010668 @Override
10669 public boolean getNextOldHistoryLocked(HistoryItem out) {
10670 boolean end = mHistoryBuffer.dataPosition() >= mHistoryBuffer.dataSize();
10671 if (!end) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010672 readHistoryDelta(mHistoryBuffer, mHistoryReadTmp);
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010673 mReadOverflow |= mHistoryReadTmp.cmd == HistoryItem.CMD_OVERFLOW;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010674 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010675 HistoryItem cur = mHistoryIterator;
10676 if (cur == null) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010677 if (!mReadOverflow && !end) {
10678 Slog.w(TAG, "Old history ends before new history!");
10679 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010680 return false;
10681 }
10682 out.setTo(cur);
10683 mHistoryIterator = cur.next;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010684 if (!mReadOverflow) {
10685 if (end) {
10686 Slog.w(TAG, "New history ends before old history!");
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010687 } else if (!out.same(mHistoryReadTmp)) {
Dianne Hackborn8c841092013-06-24 13:46:13 -070010688 PrintWriter pw = new FastPrintWriter(new LogWriter(android.util.Log.WARN, TAG));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010689 pw.println("Histories differ!");
10690 pw.println("Old history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010691 (new HistoryPrinter()).printNextItem(pw, out, 0, false, true);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010692 pw.println("New history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010693 (new HistoryPrinter()).printNextItem(pw, mHistoryReadTmp, 0, false,
10694 true);
Dianne Hackborn8c841092013-06-24 13:46:13 -070010695 pw.flush();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010696 }
10697 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010698 return true;
10699 }
10700
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010701 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010702 public void finishIteratingOldHistoryLocked() {
10703 mIteratingHistory = false;
10704 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010705 mHistoryIterator = null;
10706 }
10707
10708 public int getHistoryTotalSize() {
10709 return MAX_HISTORY_BUFFER;
10710 }
10711
10712 public int getHistoryUsedSize() {
10713 return mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010714 }
10715
10716 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +010010717 @UnsupportedAppUsage
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010718 public boolean startIteratingHistoryLocked() {
10719 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
10720 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010721 if (mHistoryBuffer.dataSize() <= 0) {
10722 return false;
10723 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010724 mHistoryBuffer.setDataPosition(0);
10725 mReadOverflow = false;
10726 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010727 mReadHistoryStrings = new String[mHistoryTagPool.size()];
10728 mReadHistoryUids = new int[mHistoryTagPool.size()];
10729 mReadHistoryChars = 0;
10730 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
10731 final HistoryTag tag = ent.getKey();
10732 final int idx = ent.getValue();
10733 mReadHistoryStrings[idx] = tag.string;
10734 mReadHistoryUids[idx] = tag.uid;
10735 mReadHistoryChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080010736 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010737 return true;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010738 }
10739
10740 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -080010741 public int getHistoryStringPoolSize() {
10742 return mReadHistoryStrings.length;
10743 }
10744
10745 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010746 public int getHistoryStringPoolBytes() {
10747 // Each entry is a fixed 12 bytes: 4 for index, 4 for uid, 4 for string size
10748 // Each string character is 2 bytes.
10749 return (mReadHistoryStrings.length * 12) + (mReadHistoryChars * 2);
10750 }
10751
10752 @Override
10753 public String getHistoryTagPoolString(int index) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080010754 return mReadHistoryStrings[index];
10755 }
10756
10757 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010758 public int getHistoryTagPoolUid(int index) {
10759 return mReadHistoryUids[index];
10760 }
10761
10762 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +010010763 @UnsupportedAppUsage
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010764 public boolean getNextHistoryLocked(HistoryItem out) {
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010765 final int pos = mHistoryBuffer.dataPosition();
10766 if (pos == 0) {
10767 out.clear();
10768 }
10769 boolean end = pos >= mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010770 if (end) {
10771 return false;
10772 }
10773
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010774 final long lastRealtime = out.time;
10775 final long lastWalltime = out.currentTime;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010776 readHistoryDelta(mHistoryBuffer, out);
Dianne Hackborn37de0982014-05-09 09:32:18 -070010777 if (out.cmd != HistoryItem.CMD_CURRENT_TIME
10778 && out.cmd != HistoryItem.CMD_RESET && lastWalltime != 0) {
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010779 out.currentTime = lastWalltime + (out.time - lastRealtime);
10780 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010781 return true;
10782 }
10783
10784 @Override
10785 public void finishIteratingHistoryLocked() {
10786 mIteratingHistory = false;
10787 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn099bc622014-01-22 13:39:16 -080010788 mReadHistoryStrings = null;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010789 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010790
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010791 @Override
Dianne Hackbornb5e31652010-09-07 12:13:55 -070010792 public long getHistoryBaseTime() {
10793 return mHistoryBaseTime;
10794 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010795
Dianne Hackbornb5e31652010-09-07 12:13:55 -070010796 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010797 public int getStartCount() {
10798 return mStartCount;
10799 }
10800
Mathew Inwoodc185f082018-08-20 14:28:54 +010010801 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010802 public boolean isOnBattery() {
10803 return mOnBattery;
10804 }
10805
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010806 public boolean isCharging() {
10807 return mCharging;
10808 }
10809
Mike Mac2f518a2017-09-19 16:06:03 -070010810 public boolean isScreenOn(int state) {
Chris Phoenix10a4a642017-09-25 13:21:00 -070010811 return state == Display.STATE_ON || state == Display.STATE_VR
10812 || state == Display.STATE_ON_SUSPEND;
Mike Mac2f518a2017-09-19 16:06:03 -070010813 }
10814
10815 public boolean isScreenOff(int state) {
10816 return state == Display.STATE_OFF;
10817 }
10818
10819 public boolean isScreenDoze(int state) {
10820 return state == Display.STATE_DOZE || state == Display.STATE_DOZE_SUSPEND;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010821 }
10822
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010823 void initTimes(long uptime, long realtime) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080010824 mStartClockTime = System.currentTimeMillis();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010825 mOnBatteryTimeBase.init(uptime, realtime);
10826 mOnBatteryScreenOffTimeBase.init(uptime, realtime);
Dianne Hackborn4590e522014-03-24 13:36:46 -070010827 mRealtime = 0;
10828 mUptime = 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010829 mRealtimeStart = realtime;
Dianne Hackborn4590e522014-03-24 13:36:46 -070010830 mUptimeStart = uptime;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010831 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010832
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010833 void initDischarge() {
10834 mLowDischargeAmountSinceCharge = 0;
10835 mHighDischargeAmountSinceCharge = 0;
10836 mDischargeAmountScreenOn = 0;
10837 mDischargeAmountScreenOnSinceCharge = 0;
10838 mDischargeAmountScreenOff = 0;
10839 mDischargeAmountScreenOffSinceCharge = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010840 mDischargeAmountScreenDoze = 0;
10841 mDischargeAmountScreenDozeSinceCharge = 0;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010842 mDischargeStepTracker.init();
10843 mChargeStepTracker.init();
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010844 mDischargeScreenOffCounter.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -070010845 mDischargeScreenDozeCounter.reset(false);
Mike Ma15313c92017-11-15 17:58:21 -080010846 mDischargeLightDozeCounter.reset(false);
10847 mDischargeDeepDozeCounter.reset(false);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010848 mDischargeCounter.reset(false);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010849 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010850
10851 public void resetAllStatsCmdLocked() {
10852 resetAllStatsLocked();
Joe Onoratoabded112016-02-08 16:49:39 -080010853 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -070010854 long uptime = mSecUptime * 1000;
Joe Onoratoabded112016-02-08 16:49:39 -080010855 long mSecRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010856 long realtime = mSecRealtime * 1000;
10857 mDischargeStartLevel = mHistoryCur.batteryLevel;
10858 pullPendingStateUpdatesLocked();
Dianne Hackborn40c87252014-03-19 16:55:40 -070010859 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010860 mDischargeCurrentLevel = mDischargeUnplugLevel = mDischargePlugLevel
10861 = mCurrentBatteryLevel = mHistoryCur.batteryLevel;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010862 mOnBatteryTimeBase.reset(uptime, realtime);
10863 mOnBatteryScreenOffTimeBase.reset(uptime, realtime);
10864 if ((mHistoryCur.states&HistoryItem.STATE_BATTERY_PLUGGED_FLAG) == 0) {
Mike Mac2f518a2017-09-19 16:06:03 -070010865 if (isScreenOn(mScreenState)) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010866 mDischargeScreenOnUnplugLevel = mHistoryCur.batteryLevel;
Mike Mac2f518a2017-09-19 16:06:03 -070010867 mDischargeScreenDozeUnplugLevel = 0;
10868 mDischargeScreenOffUnplugLevel = 0;
10869 } else if (isScreenDoze(mScreenState)) {
10870 mDischargeScreenOnUnplugLevel = 0;
10871 mDischargeScreenDozeUnplugLevel = mHistoryCur.batteryLevel;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010872 mDischargeScreenOffUnplugLevel = 0;
10873 } else {
10874 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010875 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010876 mDischargeScreenOffUnplugLevel = mHistoryCur.batteryLevel;
10877 }
10878 mDischargeAmountScreenOn = 0;
10879 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010880 mDischargeAmountScreenDoze = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010881 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070010882 initActiveHistoryEventsLocked(mSecRealtime, mSecUptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010883 }
10884
10885 private void resetAllStatsLocked() {
Adam Lesinski8ce36942016-05-26 16:05:35 -070010886 final long uptimeMillis = mClocks.uptimeMillis();
10887 final long elapsedRealtimeMillis = mClocks.elapsedRealtime();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010888 mStartCount = 0;
Adam Lesinski8ce36942016-05-26 16:05:35 -070010889 initTimes(uptimeMillis * 1000, elapsedRealtimeMillis * 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010890 mScreenOnTimer.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -070010891 mScreenDozeTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010892 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010893 mScreenBrightnessTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010894 }
Adam Lesinski1a76a622016-06-22 10:28:47 -070010895
10896 if (mPowerProfile != null) {
10897 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
10898 } else {
10899 mEstimatedBatteryCapacity = -1;
10900 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070010901 mMinLearnedBatteryCapacity = -1;
10902 mMaxLearnedBatteryCapacity = -1;
Jeff Browne95c3cd2014-05-02 16:59:26 -070010903 mInteractiveTimer.reset(false);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070010904 mPowerSaveModeEnabledTimer.reset(false);
Adam Lesinski8ce36942016-05-26 16:05:35 -070010905 mLastIdleTimeStart = elapsedRealtimeMillis;
Dianne Hackborn08c47a52015-10-15 12:38:14 -070010906 mLongestLightIdleTime = 0;
10907 mLongestFullIdleTime = 0;
10908 mDeviceIdleModeLightTimer.reset(false);
10909 mDeviceIdleModeFullTimer.reset(false);
10910 mDeviceLightIdlingTimer.reset(false);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010911 mDeviceIdlingTimer.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010912 mPhoneOnTimer.reset(false);
10913 mAudioOnTimer.reset(false);
10914 mVideoOnTimer.reset(false);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070010915 mFlashlightOnTimer.reset(false);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070010916 mCameraOnTimer.reset(false);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010917 mBluetoothScanTimer.reset(false);
Wink Saville52840902011-02-18 12:40:47 -080010918 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010919 mPhoneSignalStrengthsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010920 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010921 mPhoneSignalScanningTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010922 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010923 mPhoneDataConnectionsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010924 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010925 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010926 mNetworkByteActivityCounters[i].reset(false);
10927 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010928 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010929 mMobileRadioActiveTimer.reset(false);
10930 mMobileRadioActivePerAppTimer.reset(false);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010931 mMobileRadioActiveAdjustedTime.reset(false);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080010932 mMobileRadioActiveUnknownTime.reset(false);
10933 mMobileRadioActiveUnknownCount.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010934 mWifiOnTimer.reset(false);
10935 mGlobalWifiRunningTimer.reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010936 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010937 mWifiStateTimer[i].reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010938 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070010939 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
10940 mWifiSupplStateTimer[i].reset(false);
10941 }
10942 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
10943 mWifiSignalStrengthsTimer[i].reset(false);
10944 }
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080010945 mWifiMulticastWakelockTimer.reset(false);
Siddharth Rayb50a6842017-12-14 15:15:28 -080010946 mWifiActiveTimer.reset(false);
10947 mWifiActivity.reset(false);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080010948 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
10949 mGpsSignalQualityTimer[i].reset(false);
10950 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010951 mBluetoothActivity.reset(false);
10952 mModemActivity.reset(false);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080010953 mNumConnectivityChange = mLoadedNumConnectivityChange = mUnpluggedNumConnectivityChange = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010954
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010955 for (int i=0; i<mUidStats.size(); i++) {
Bookatz993a0be2017-07-21 09:03:23 -070010956 if (mUidStats.valueAt(i).reset(uptimeMillis * 1000, elapsedRealtimeMillis * 1000)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010957 mUidStats.remove(mUidStats.keyAt(i));
10958 i--;
10959 }
10960 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010961
Bookatz50df7112017-08-04 14:53:26 -070010962 if (mRpmStats.size() > 0) {
10963 for (SamplingTimer timer : mRpmStats.values()) {
10964 mOnBatteryTimeBase.remove(timer);
10965 }
10966 mRpmStats.clear();
10967 }
10968 if (mScreenOffRpmStats.size() > 0) {
10969 for (SamplingTimer timer : mScreenOffRpmStats.values()) {
10970 mOnBatteryScreenOffTimeBase.remove(timer);
10971 }
10972 mScreenOffRpmStats.clear();
10973 }
10974
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010975 if (mKernelWakelockStats.size() > 0) {
10976 for (SamplingTimer timer : mKernelWakelockStats.values()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010977 mOnBatteryScreenOffTimeBase.remove(timer);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010978 }
10979 mKernelWakelockStats.clear();
10980 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010981
James Carr3a226052016-07-01 14:49:52 -070010982 if (mKernelMemoryStats.size() > 0) {
10983 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
10984 mOnBatteryTimeBase.remove(mKernelMemoryStats.valueAt(i));
10985 }
10986 mKernelMemoryStats.clear();
10987 }
10988
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010989 if (mWakeupReasonStats.size() > 0) {
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070010990 for (SamplingTimer timer : mWakeupReasonStats.values()) {
10991 mOnBatteryTimeBase.remove(timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010992 }
10993 mWakeupReasonStats.clear();
10994 }
10995
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080010996 mLastHistoryStepDetails = null;
10997 mLastStepCpuUserTime = mLastStepCpuSystemTime = 0;
10998 mCurStepCpuUserTime = mCurStepCpuSystemTime = 0;
10999 mLastStepCpuUserTime = mCurStepCpuUserTime = 0;
11000 mLastStepCpuSystemTime = mCurStepCpuSystemTime = 0;
11001 mLastStepStatUserTime = mCurStepStatUserTime = 0;
11002 mLastStepStatSystemTime = mCurStepStatSystemTime = 0;
11003 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime = 0;
11004 mLastStepStatIrqTime = mCurStepStatIrqTime = 0;
11005 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime = 0;
11006 mLastStepStatIdleTime = mCurStepStatIdleTime = 0;
11007
Mike Ma234d1822018-03-13 18:53:21 -070011008 mNumAllUidCpuTimeReads = 0;
11009 mNumUidsRemoved = 0;
11010
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011011 initDischarge();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011012
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011013 clearHistoryLocked();
Fyodor Kupolov8aa51242018-04-23 12:44:51 -070011014 mHandler.sendEmptyMessage(MSG_REPORT_RESET_STATS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011015 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011016
Dianne Hackborn40c87252014-03-19 16:55:40 -070011017 private void initActiveHistoryEventsLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080011018 for (int i=0; i<HistoryItem.EVENT_COUNT; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011019 if (!mRecordAllHistory && i == HistoryItem.EVENT_PROC) {
11020 // Not recording process starts/stops.
11021 continue;
11022 }
Dianne Hackborn37de0982014-05-09 09:32:18 -070011023 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(i);
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080011024 if (active == null) {
11025 continue;
11026 }
Dianne Hackborn37de0982014-05-09 09:32:18 -070011027 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
11028 SparseIntArray uids = ent.getValue();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080011029 for (int j=0; j<uids.size(); j++) {
Dianne Hackborn37de0982014-05-09 09:32:18 -070011030 addHistoryEventLocked(elapsedRealtimeMs, uptimeMs, i, ent.getKey(),
11031 uids.keyAt(j));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080011032 }
11033 }
11034 }
11035 }
11036
Mike Mac2f518a2017-09-19 16:06:03 -070011037 void updateDischargeScreenLevelsLocked(int oldState, int newState) {
11038 updateOldDischargeScreenLevelLocked(oldState);
11039 updateNewDischargeScreenLevelLocked(newState);
11040 }
11041
11042 private void updateOldDischargeScreenLevelLocked(int state) {
11043 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011044 int diff = mDischargeScreenOnUnplugLevel - mDischargeCurrentLevel;
11045 if (diff > 0) {
11046 mDischargeAmountScreenOn += diff;
11047 mDischargeAmountScreenOnSinceCharge += diff;
11048 }
Mike Mac2f518a2017-09-19 16:06:03 -070011049 } else if (isScreenDoze(state)) {
11050 int diff = mDischargeScreenDozeUnplugLevel - mDischargeCurrentLevel;
11051 if (diff > 0) {
11052 mDischargeAmountScreenDoze += diff;
11053 mDischargeAmountScreenDozeSinceCharge += diff;
11054 }
11055 } else if (isScreenOff(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011056 int diff = mDischargeScreenOffUnplugLevel - mDischargeCurrentLevel;
11057 if (diff > 0) {
11058 mDischargeAmountScreenOff += diff;
11059 mDischargeAmountScreenOffSinceCharge += diff;
11060 }
11061 }
Mike Mac2f518a2017-09-19 16:06:03 -070011062 }
11063
11064 private void updateNewDischargeScreenLevelLocked(int state) {
11065 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011066 mDischargeScreenOnUnplugLevel = mDischargeCurrentLevel;
11067 mDischargeScreenOffUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070011068 mDischargeScreenDozeUnplugLevel = 0;
11069 } else if (isScreenDoze(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011070 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070011071 mDischargeScreenDozeUnplugLevel = mDischargeCurrentLevel;
11072 mDischargeScreenOffUnplugLevel = 0;
11073 } else if (isScreenOff(state)) {
11074 mDischargeScreenOnUnplugLevel = 0;
11075 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011076 mDischargeScreenOffUnplugLevel = mDischargeCurrentLevel;
11077 }
11078 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011079
Dianne Hackborna7c837f2014-01-15 16:20:44 -080011080 public void pullPendingStateUpdatesLocked() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -080011081 if (mOnBatteryInternal) {
Mike Mac2f518a2017-09-19 16:06:03 -070011082 updateDischargeScreenLevelsLocked(mScreenState, mScreenState);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080011083 }
Dianne Hackborna7c837f2014-01-15 16:20:44 -080011084 }
11085
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011086 private final NetworkStatsFactory mNetworkStatsFactory = new NetworkStatsFactory();
11087 private final Pools.Pool<NetworkStats> mNetworkStatsPool = new Pools.SynchronizedPool<>(6);
11088
11089 private final Object mWifiNetworkLock = new Object();
11090
11091 @GuardedBy("mWifiNetworkLock")
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011092 private String[] mWifiIfaces = EmptyArray.STRING;
11093
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011094 @GuardedBy("mWifiNetworkLock")
11095 private NetworkStats mLastWifiNetworkStats = new NetworkStats(0, -1);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011096
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011097 private final Object mModemNetworkLock = new Object();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011098
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011099 @GuardedBy("mModemNetworkLock")
11100 private String[] mModemIfaces = EmptyArray.STRING;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011101
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011102 @GuardedBy("mModemNetworkLock")
11103 private NetworkStats mLastModemNetworkStats = new NetworkStats(0, -1);
11104
11105 private NetworkStats readNetworkStatsLocked(String[] ifaces) {
11106 try {
11107 if (!ArrayUtils.isEmpty(ifaces)) {
11108 return mNetworkStatsFactory.readNetworkStatsDetail(NetworkStats.UID_ALL, ifaces,
11109 NetworkStats.TAG_NONE, mNetworkStatsPool.acquire());
11110 }
11111 } catch (IOException e) {
11112 Slog.e(TAG, "failed to read network stats for ifaces: " + Arrays.toString(ifaces));
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011113 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011114 return null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011115 }
11116
Chenjie Yu89083392018-01-11 14:53:31 -080011117 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011118 * Distribute WiFi energy info and network traffic to apps.
11119 * @param info The energy information from the WiFi controller.
11120 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011121 public void updateWifiState(@Nullable final WifiActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011122 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011123 Slog.d(TAG, "Updating wifi stats: " + Arrays.toString(mWifiIfaces));
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011124 }
11125
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011126 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070011127 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011128 synchronized (mWifiNetworkLock) {
11129 final NetworkStats latestStats = readNetworkStatsLocked(mWifiIfaces);
11130 if (latestStats != null) {
11131 delta = NetworkStats.subtract(latestStats, mLastWifiNetworkStats, null, null,
11132 mNetworkStatsPool.acquire());
11133 mNetworkStatsPool.release(mLastWifiNetworkStats);
11134 mLastWifiNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070011135 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011136 }
11137
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011138 synchronized (this) {
11139 if (!mOnBatteryInternal) {
11140 if (delta != null) {
11141 mNetworkStatsPool.release(delta);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011142 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011143 return;
11144 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011145
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011146 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
11147 SparseLongArray rxPackets = new SparseLongArray();
11148 SparseLongArray txPackets = new SparseLongArray();
11149 long totalTxPackets = 0;
11150 long totalRxPackets = 0;
11151 if (delta != null) {
11152 NetworkStats.Entry entry = new NetworkStats.Entry();
11153 final int size = delta.size();
11154 for (int i = 0; i < size; i++) {
11155 entry = delta.getValues(i, entry);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011156
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011157 if (DEBUG_ENERGY) {
11158 Slog.d(TAG, "Wifi uid " + entry.uid + ": delta rx=" + entry.rxBytes
11159 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
11160 + " txPackets=" + entry.txPackets);
11161 }
11162
11163 if (entry.rxBytes == 0 && entry.txBytes == 0) {
11164 // Skip the lookup below since there is no work to do.
11165 continue;
11166 }
11167
11168 final Uid u = getUidStatsLocked(mapUid(entry.uid));
11169 if (entry.rxBytes != 0) {
11170 u.noteNetworkActivityLocked(NETWORK_WIFI_RX_DATA, entry.rxBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -080011171 entry.rxPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011172 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11173 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_RX_DATA, entry.rxBytes,
11174 entry.rxPackets);
11175 }
11176 mNetworkByteActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
11177 entry.rxBytes);
11178 mNetworkPacketActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
11179 entry.rxPackets);
11180
11181 rxPackets.put(u.getUid(), entry.rxPackets);
11182
11183 // Sum the total number of packets so that the Rx Power can
11184 // be evenly distributed amongst the apps.
11185 totalRxPackets += entry.rxPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -080011186 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011187
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011188 if (entry.txBytes != 0) {
11189 u.noteNetworkActivityLocked(NETWORK_WIFI_TX_DATA, entry.txBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -080011190 entry.txPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011191 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11192 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_TX_DATA, entry.txBytes,
11193 entry.txPackets);
11194 }
11195 mNetworkByteActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
11196 entry.txBytes);
11197 mNetworkPacketActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
11198 entry.txPackets);
11199
11200 txPackets.put(u.getUid(), entry.txPackets);
11201
11202 // Sum the total number of packets so that the Tx Power can
11203 // be evenly distributed amongst the apps.
11204 totalTxPackets += entry.txPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -080011205 }
Adam Lesinskiba88e682015-12-08 12:06:55 -080011206 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011207 mNetworkStatsPool.release(delta);
11208 delta = null;
Adam Lesinskie08af192015-03-25 16:42:59 -070011209 }
11210
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011211 if (info != null) {
11212 mHasWifiReporting = true;
Adam Lesinskie08af192015-03-25 16:42:59 -070011213
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011214 // Measured in mAms
11215 final long txTimeMs = info.getControllerTxTimeMillis();
11216 final long rxTimeMs = info.getControllerRxTimeMillis();
Siddharth Rayb50a6842017-12-14 15:15:28 -080011217 final long scanTimeMs = info.getControllerScanTimeMillis();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011218 final long idleTimeMs = info.getControllerIdleTimeMillis();
11219 final long totalTimeMs = txTimeMs + rxTimeMs + idleTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -070011220
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011221 long leftOverRxTimeMs = rxTimeMs;
11222 long leftOverTxTimeMs = txTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -070011223
Adam Lesinskie08af192015-03-25 16:42:59 -070011224 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011225 Slog.d(TAG, "------ BEGIN WiFi power blaming ------");
11226 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
11227 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
11228 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms");
11229 Slog.d(TAG, " Total Time: " + totalTimeMs + " ms");
Siddharth Rayb50a6842017-12-14 15:15:28 -080011230 Slog.d(TAG, " Scan Time: " + scanTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070011231 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011232
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011233 long totalWifiLockTimeMs = 0;
11234 long totalScanTimeMs = 0;
11235
11236 // On the first pass, collect some totals so that we can normalize power
11237 // calculations if we need to.
11238 final int uidStatsSize = mUidStats.size();
11239 for (int i = 0; i < uidStatsSize; i++) {
11240 final Uid uid = mUidStats.valueAt(i);
11241
11242 // Sum the total scan power for all apps.
11243 totalScanTimeMs += uid.mWifiScanTimer.getTimeSinceMarkLocked(
11244 elapsedRealtimeMs * 1000) / 1000;
11245
11246 // Sum the total time holding wifi lock for all apps.
11247 totalWifiLockTimeMs += uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
11248 elapsedRealtimeMs * 1000) / 1000;
11249 }
11250
11251 if (DEBUG_ENERGY && totalScanTimeMs > rxTimeMs) {
11252 Slog.d(TAG,
11253 " !Estimated scan time > Actual rx time (" + totalScanTimeMs + " ms > "
11254 + rxTimeMs + " ms). Normalizing scan time.");
11255 }
11256 if (DEBUG_ENERGY && totalScanTimeMs > txTimeMs) {
11257 Slog.d(TAG,
11258 " !Estimated scan time > Actual tx time (" + totalScanTimeMs + " ms > "
11259 + txTimeMs + " ms). Normalizing scan time.");
11260 }
11261
11262 // Actually assign and distribute power usage to apps.
11263 for (int i = 0; i < uidStatsSize; i++) {
11264 final Uid uid = mUidStats.valueAt(i);
11265
11266 long scanTimeSinceMarkMs = uid.mWifiScanTimer.getTimeSinceMarkLocked(
11267 elapsedRealtimeMs * 1000) / 1000;
11268 if (scanTimeSinceMarkMs > 0) {
11269 // Set the new mark so that next time we get new data since this point.
11270 uid.mWifiScanTimer.setMark(elapsedRealtimeMs);
11271
11272 long scanRxTimeSinceMarkMs = scanTimeSinceMarkMs;
11273 long scanTxTimeSinceMarkMs = scanTimeSinceMarkMs;
11274
11275 // Our total scan time is more than the reported Tx/Rx time.
11276 // This is possible because the cost of a scan is approximate.
11277 // Let's normalize the result so that we evenly blame each app
11278 // scanning.
11279 //
11280 // This means that we may have apps that transmitted/received packets not be
11281 // blamed for this, but this is fine as scans are relatively more expensive.
11282 if (totalScanTimeMs > rxTimeMs) {
11283 scanRxTimeSinceMarkMs = (rxTimeMs * scanRxTimeSinceMarkMs) /
11284 totalScanTimeMs;
11285 }
11286 if (totalScanTimeMs > txTimeMs) {
11287 scanTxTimeSinceMarkMs = (txTimeMs * scanTxTimeSinceMarkMs) /
11288 totalScanTimeMs;
11289 }
11290
11291 if (DEBUG_ENERGY) {
11292 Slog.d(TAG, " ScanTime for UID " + uid.getUid() + ": Rx:"
11293 + scanRxTimeSinceMarkMs + " ms Tx:"
11294 + scanTxTimeSinceMarkMs + " ms)");
11295 }
11296
11297 ControllerActivityCounterImpl activityCounter =
11298 uid.getOrCreateWifiControllerActivityLocked();
11299 activityCounter.getRxTimeCounter().addCountLocked(scanRxTimeSinceMarkMs);
11300 activityCounter.getTxTimeCounters()[0].addCountLocked(
11301 scanTxTimeSinceMarkMs);
11302 leftOverRxTimeMs -= scanRxTimeSinceMarkMs;
11303 leftOverTxTimeMs -= scanTxTimeSinceMarkMs;
11304 }
11305
11306 // Distribute evenly the power consumed while Idle to each app holding a WiFi
11307 // lock.
11308 final long wifiLockTimeSinceMarkMs =
11309 uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
11310 elapsedRealtimeMs * 1000) / 1000;
11311 if (wifiLockTimeSinceMarkMs > 0) {
11312 // Set the new mark so that next time we get new data since this point.
11313 uid.mFullWifiLockTimer.setMark(elapsedRealtimeMs);
11314
11315 final long myIdleTimeMs = (wifiLockTimeSinceMarkMs * idleTimeMs)
11316 / totalWifiLockTimeMs;
11317 if (DEBUG_ENERGY) {
11318 Slog.d(TAG, " IdleTime for UID " + uid.getUid() + ": "
11319 + myIdleTimeMs + " ms");
11320 }
11321 uid.getOrCreateWifiControllerActivityLocked().getIdleTimeCounter()
11322 .addCountLocked(myIdleTimeMs);
11323 }
11324 }
11325
Adam Lesinskie08af192015-03-25 16:42:59 -070011326 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011327 Slog.d(TAG, " New RxPower: " + leftOverRxTimeMs + " ms");
11328 Slog.d(TAG, " New TxPower: " + leftOverTxTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070011329 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011330
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011331 // Distribute the remaining Tx power appropriately between all apps that transmitted
11332 // packets.
11333 for (int i = 0; i < txPackets.size(); i++) {
11334 final Uid uid = getUidStatsLocked(txPackets.keyAt(i));
11335 final long myTxTimeMs = (txPackets.valueAt(i) * leftOverTxTimeMs)
11336 / totalTxPackets;
11337 if (DEBUG_ENERGY) {
11338 Slog.d(TAG, " TxTime for UID " + uid.getUid() + ": " + myTxTimeMs + " ms");
11339 }
11340 uid.getOrCreateWifiControllerActivityLocked().getTxTimeCounters()[0]
11341 .addCountLocked(myTxTimeMs);
11342 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011343
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011344 // Distribute the remaining Rx power appropriately between all apps that received
11345 // packets.
11346 for (int i = 0; i < rxPackets.size(); i++) {
11347 final Uid uid = getUidStatsLocked(rxPackets.keyAt(i));
11348 final long myRxTimeMs = (rxPackets.valueAt(i) * leftOverRxTimeMs)
11349 / totalRxPackets;
11350 if (DEBUG_ENERGY) {
11351 Slog.d(TAG, " RxTime for UID " + uid.getUid() + ": " + myRxTimeMs + " ms");
11352 }
11353 uid.getOrCreateWifiControllerActivityLocked().getRxTimeCounter()
11354 .addCountLocked(myRxTimeMs);
11355 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011356
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011357 // Any left over power use will be picked up by the WiFi category in BatteryStatsHelper.
11358
11359
11360 // Update WiFi controller stats.
11361 mWifiActivity.getRxTimeCounter().addCountLocked(info.getControllerRxTimeMillis());
11362 mWifiActivity.getTxTimeCounters()[0].addCountLocked(
11363 info.getControllerTxTimeMillis());
Siddharth Rayb50a6842017-12-14 15:15:28 -080011364 mWifiActivity.getScanTimeCounter().addCountLocked(
11365 info.getControllerScanTimeMillis());
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011366 mWifiActivity.getIdleTimeCounter().addCountLocked(
11367 info.getControllerIdleTimeMillis());
11368
11369 // POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11370 final double opVolt = mPowerProfile.getAveragePower(
11371 PowerProfile.POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11372 if (opVolt != 0) {
11373 // We store the power drain as mAms.
11374 mWifiActivity.getPowerCounter().addCountLocked(
11375 (long) (info.getControllerEnergyUsed() / opVolt));
11376 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011377 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011378 }
11379 }
11380
Chenjie Yu89083392018-01-11 14:53:31 -080011381 private ModemActivityInfo mLastModemActivityInfo =
11382 new ModemActivityInfo(0, 0, 0, new int[0], 0, 0);
11383
Chenjie Yua54e54d2018-02-14 20:12:52 -080011384 private ModemActivityInfo getDeltaModemActivityInfo(ModemActivityInfo activityInfo) {
11385 if (activityInfo == null) {
11386 return null;
11387 }
11388 int[] txTimeMs = new int[ModemActivityInfo.TX_POWER_LEVELS];
11389 for (int i = 0; i < ModemActivityInfo.TX_POWER_LEVELS; i++) {
11390 txTimeMs[i] = activityInfo.getTxTimeMillis()[i]
11391 - mLastModemActivityInfo.getTxTimeMillis()[i];
11392 }
11393 ModemActivityInfo deltaInfo = new ModemActivityInfo(activityInfo.getTimestamp(),
11394 activityInfo.getSleepTimeMillis() - mLastModemActivityInfo.getSleepTimeMillis(),
11395 activityInfo.getIdleTimeMillis() - mLastModemActivityInfo.getIdleTimeMillis(),
11396 txTimeMs,
11397 activityInfo.getRxTimeMillis() - mLastModemActivityInfo.getRxTimeMillis(),
11398 activityInfo.getEnergyUsed() - mLastModemActivityInfo.getEnergyUsed());
11399 mLastModemActivityInfo = activityInfo;
11400 return deltaInfo;
11401 }
11402
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011403 /**
11404 * Distribute Cell radio energy info and network traffic to apps.
11405 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011406 public void updateMobileRadioState(@Nullable final ModemActivityInfo activityInfo) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011407 if (DEBUG_ENERGY) {
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011408 Slog.d(TAG, "Updating mobile radio stats with " + activityInfo);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011409 }
Chenjie Yua54e54d2018-02-14 20:12:52 -080011410 ModemActivityInfo deltaInfo = getDeltaModemActivityInfo(activityInfo);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011411
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011412 // Add modem tx power to history.
Chenjie Yua54e54d2018-02-14 20:12:52 -080011413 addModemTxPowerToHistory(deltaInfo);
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011414
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011415 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070011416 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011417 synchronized (mModemNetworkLock) {
11418 final NetworkStats latestStats = readNetworkStatsLocked(mModemIfaces);
11419 if (latestStats != null) {
11420 delta = NetworkStats.subtract(latestStats, mLastModemNetworkStats, null, null,
11421 mNetworkStatsPool.acquire());
11422 mNetworkStatsPool.release(mLastModemNetworkStats);
11423 mLastModemNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070011424 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011425 }
11426
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011427 synchronized (this) {
11428 if (!mOnBatteryInternal) {
11429 if (delta != null) {
11430 mNetworkStatsPool.release(delta);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011431 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011432 return;
Adam Lesinskie08af192015-03-25 16:42:59 -070011433 }
11434
Chenjie Yua54e54d2018-02-14 20:12:52 -080011435 if (deltaInfo != null) {
Siddharth Ray2038af82018-01-17 17:40:26 -080011436 mHasModemReporting = true;
11437 mModemActivity.getIdleTimeCounter().addCountLocked(
Chenjie Yua54e54d2018-02-14 20:12:52 -080011438 deltaInfo.getIdleTimeMillis());
Siddharth Rayed754702018-02-15 12:44:37 -080011439 mModemActivity.getSleepTimeCounter().addCountLocked(
11440 deltaInfo.getSleepTimeMillis());
Chenjie Yua54e54d2018-02-14 20:12:52 -080011441 mModemActivity.getRxTimeCounter().addCountLocked(deltaInfo.getRxTimeMillis());
Siddharth Ray2038af82018-01-17 17:40:26 -080011442 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
11443 mModemActivity.getTxTimeCounters()[lvl]
Chenjie Yua54e54d2018-02-14 20:12:52 -080011444 .addCountLocked(deltaInfo.getTxTimeMillis()[lvl]);
Siddharth Ray2038af82018-01-17 17:40:26 -080011445 }
11446
11447 // POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11448 final double opVolt = mPowerProfile.getAveragePower(
11449 PowerProfile.POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11450 if (opVolt != 0) {
11451 double energyUsed =
Chenjie Yua54e54d2018-02-14 20:12:52 -080011452 deltaInfo.getSleepTimeMillis() *
Siddharth Ray2038af82018-01-17 17:40:26 -080011453 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_SLEEP)
Chenjie Yua54e54d2018-02-14 20:12:52 -080011454 + deltaInfo.getIdleTimeMillis() *
Siddharth Ray2038af82018-01-17 17:40:26 -080011455 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_IDLE)
Chenjie Yua54e54d2018-02-14 20:12:52 -080011456 + deltaInfo.getRxTimeMillis() *
Siddharth Ray2038af82018-01-17 17:40:26 -080011457 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_RX);
Chenjie Yua54e54d2018-02-14 20:12:52 -080011458 int[] txTimeMs = deltaInfo.getTxTimeMillis();
Chenjie Yu89083392018-01-11 14:53:31 -080011459 for (int i = 0; i < Math.min(txTimeMs.length,
Chenjie Yua54e54d2018-02-14 20:12:52 -080011460 SignalStrength.NUM_SIGNAL_STRENGTH_BINS); i++) {
Chenjie Yu89083392018-01-11 14:53:31 -080011461 energyUsed += txTimeMs[i] * mPowerProfile.getAveragePower(
Chenjie Yua54e54d2018-02-14 20:12:52 -080011462 PowerProfile.POWER_MODEM_CONTROLLER_TX, i);
Siddharth Ray2038af82018-01-17 17:40:26 -080011463 }
11464
11465 // We store the power drain as mAms.
11466 mModemActivity.getPowerCounter().addCountLocked((long) energyUsed);
11467 }
11468 }
11469
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070011470 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011471 long radioTime = mMobileRadioActivePerAppTimer.getTimeSinceMarkLocked(
11472 elapsedRealtimeMs * 1000);
11473 mMobileRadioActivePerAppTimer.setMark(elapsedRealtimeMs);
11474
11475 long totalRxPackets = 0;
11476 long totalTxPackets = 0;
11477 if (delta != null) {
11478 NetworkStats.Entry entry = new NetworkStats.Entry();
11479 final int size = delta.size();
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011480 for (int i = 0; i < size; i++) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011481 entry = delta.getValues(i, entry);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011482 if (entry.rxPackets == 0 && entry.txPackets == 0) {
11483 continue;
11484 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011485
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011486 if (DEBUG_ENERGY) {
11487 Slog.d(TAG, "Mobile uid " + entry.uid + ": delta rx=" + entry.rxBytes
11488 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
11489 + " txPackets=" + entry.txPackets);
11490 }
11491
11492 totalRxPackets += entry.rxPackets;
11493 totalTxPackets += entry.txPackets;
11494
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011495 final Uid u = getUidStatsLocked(mapUid(entry.uid));
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011496 u.noteNetworkActivityLocked(NETWORK_MOBILE_RX_DATA, entry.rxBytes,
11497 entry.rxPackets);
11498 u.noteNetworkActivityLocked(NETWORK_MOBILE_TX_DATA, entry.txBytes,
11499 entry.txPackets);
11500 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11501 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_RX_DATA,
11502 entry.rxBytes, entry.rxPackets);
11503 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_TX_DATA,
11504 entry.txBytes, entry.txPackets);
11505 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011506
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011507 mNetworkByteActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
11508 entry.rxBytes);
11509 mNetworkByteActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
11510 entry.txBytes);
11511 mNetworkPacketActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
11512 entry.rxPackets);
11513 mNetworkPacketActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
11514 entry.txPackets);
11515 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011516
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011517 // Now distribute proportional blame to the apps that did networking.
11518 long totalPackets = totalRxPackets + totalTxPackets;
11519 if (totalPackets > 0) {
11520 for (int i = 0; i < size; i++) {
11521 entry = delta.getValues(i, entry);
11522 if (entry.rxPackets == 0 && entry.txPackets == 0) {
11523 continue;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011524 }
11525
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011526 final Uid u = getUidStatsLocked(mapUid(entry.uid));
11527
11528 // Distribute total radio active time in to this app.
11529 final long appPackets = entry.rxPackets + entry.txPackets;
11530 final long appRadioTime = (radioTime * appPackets) / totalPackets;
11531 u.noteMobileRadioActiveTimeLocked(appRadioTime);
11532
11533 // Remove this app from the totals, so that we don't lose any time
11534 // due to rounding.
11535 radioTime -= appRadioTime;
11536 totalPackets -= appPackets;
11537
Chenjie Yua54e54d2018-02-14 20:12:52 -080011538 if (deltaInfo != null) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011539 ControllerActivityCounterImpl activityCounter =
11540 u.getOrCreateModemControllerActivityLocked();
11541 if (totalRxPackets > 0 && entry.rxPackets > 0) {
Chenjie Yua54e54d2018-02-14 20:12:52 -080011542 final long rxMs = (entry.rxPackets * deltaInfo.getRxTimeMillis())
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011543 / totalRxPackets;
11544 activityCounter.getRxTimeCounter().addCountLocked(rxMs);
11545 }
11546
11547 if (totalTxPackets > 0 && entry.txPackets > 0) {
11548 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
11549 long txMs =
Chenjie Yua54e54d2018-02-14 20:12:52 -080011550 entry.txPackets * deltaInfo.getTxTimeMillis()[lvl];
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011551 txMs /= totalTxPackets;
11552 activityCounter.getTxTimeCounters()[lvl].addCountLocked(txMs);
11553 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011554 }
11555 }
11556 }
11557 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011558
11559 if (radioTime > 0) {
11560 // Whoops, there is some radio time we can't blame on an app!
11561 mMobileRadioActiveUnknownTime.addCountLocked(radioTime);
11562 mMobileRadioActiveUnknownCount.addCountLocked(1);
11563 }
11564
11565 mNetworkStatsPool.release(delta);
11566 delta = null;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011567 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011568 }
11569 }
11570
11571 /**
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011572 * Add modem tx power to history
11573 * Device is said to be in high cellular transmit power when it has spent most of the transmit
11574 * time at the highest power level.
11575 * @param activityInfo
11576 */
Siddharth Raya67fb562018-02-28 13:46:16 -080011577 private synchronized void addModemTxPowerToHistory(final ModemActivityInfo activityInfo) {
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011578 if (activityInfo == null) {
11579 return;
11580 }
11581 int[] txTimeMs = activityInfo.getTxTimeMillis();
11582 if (txTimeMs == null || txTimeMs.length != ModemActivityInfo.TX_POWER_LEVELS) {
11583 return;
11584 }
11585 final long elapsedRealtime = mClocks.elapsedRealtime();
11586 final long uptime = mClocks.uptimeMillis();
11587 int levelMaxTimeSpent = 0;
11588 for (int i = 1; i < txTimeMs.length; i++) {
11589 if (txTimeMs[i] > txTimeMs[levelMaxTimeSpent]) {
11590 levelMaxTimeSpent = i;
11591 }
11592 }
11593 if (levelMaxTimeSpent == ModemActivityInfo.TX_POWER_LEVELS - 1) {
11594 if (!mIsCellularTxPowerHigh) {
11595 mHistoryCur.states2 |= HistoryItem.STATE2_CELLULAR_HIGH_TX_POWER_FLAG;
11596 addHistoryRecordLocked(elapsedRealtime, uptime);
11597 mIsCellularTxPowerHigh = true;
11598 }
11599 return;
11600 }
11601 if (mIsCellularTxPowerHigh) {
11602 mHistoryCur.states2 &= ~HistoryItem.STATE2_CELLULAR_HIGH_TX_POWER_FLAG;
11603 addHistoryRecordLocked(elapsedRealtime, uptime);
11604 mIsCellularTxPowerHigh = false;
11605 }
11606 return;
11607 }
11608
Mike Ma561a8d92018-03-20 18:24:05 -070011609 private final class BluetoothActivityInfoCache {
11610 long idleTimeMs;
11611 long rxTimeMs;
11612 long txTimeMs;
11613 long energy;
11614
11615 SparseLongArray uidRxBytes = new SparseLongArray();
11616 SparseLongArray uidTxBytes = new SparseLongArray();
11617
11618 void set(BluetoothActivityEnergyInfo info) {
11619 idleTimeMs = info.getControllerIdleTimeMillis();
11620 rxTimeMs = info.getControllerRxTimeMillis();
11621 txTimeMs = info.getControllerTxTimeMillis();
11622 energy = info.getControllerEnergyUsed();
11623 if (info.getUidTraffic() != null) {
11624 for (UidTraffic traffic : info.getUidTraffic()) {
11625 uidRxBytes.put(traffic.getUid(), traffic.getRxBytes());
11626 uidTxBytes.put(traffic.getUid(), traffic.getTxBytes());
11627 }
11628 }
11629 }
11630 }
11631
11632 private final BluetoothActivityInfoCache mLastBluetoothActivityInfo
11633 = new BluetoothActivityInfoCache();
11634
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011635 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011636 * Distribute Bluetooth energy info and network traffic to apps.
Mike Ma561a8d92018-03-20 18:24:05 -070011637 *
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011638 * @param info The energy information from the bluetooth controller.
11639 */
11640 public void updateBluetoothStateLocked(@Nullable final BluetoothActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011641 if (DEBUG_ENERGY) {
Adam Lesinski50e47602015-12-04 17:04:54 -080011642 Slog.d(TAG, "Updating bluetooth stats: " + info);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011643 }
11644
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011645 if (info == null || !mOnBatteryInternal) {
11646 return;
11647 }
Adam Lesinskie283d332015-04-16 12:29:25 -070011648
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011649 mHasBluetoothReporting = true;
11650
Bookatz867c0d72017-03-07 18:23:42 -080011651 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Mike Ma561a8d92018-03-20 18:24:05 -070011652 final long rxTimeMs =
11653 info.getControllerRxTimeMillis() - mLastBluetoothActivityInfo.rxTimeMs;
11654 final long txTimeMs =
11655 info.getControllerTxTimeMillis() - mLastBluetoothActivityInfo.txTimeMs;
11656 final long idleTimeMs =
11657 info.getControllerIdleTimeMillis() - mLastBluetoothActivityInfo.idleTimeMs;
11658
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011659 if (DEBUG_ENERGY) {
11660 Slog.d(TAG, "------ BEGIN BLE power blaming ------");
11661 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
11662 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
Chenjie Yu89083392018-01-11 14:53:31 -080011663 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms");
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011664 }
11665
11666 long totalScanTimeMs = 0;
11667
11668 final int uidCount = mUidStats.size();
11669 for (int i = 0; i < uidCount; i++) {
11670 final Uid u = mUidStats.valueAt(i);
11671 if (u.mBluetoothScanTimer == null) {
11672 continue;
Adam Lesinskie283d332015-04-16 12:29:25 -070011673 }
Adam Lesinski50e47602015-12-04 17:04:54 -080011674
Bookatzaa4594a2017-03-24 12:39:56 -070011675 totalScanTimeMs += u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011676 elapsedRealtimeMs * 1000) / 1000;
11677 }
11678
11679 final boolean normalizeScanRxTime = (totalScanTimeMs > rxTimeMs);
11680 final boolean normalizeScanTxTime = (totalScanTimeMs > txTimeMs);
11681
11682 if (DEBUG_ENERGY) {
11683 Slog.d(TAG, "Normalizing scan power for RX=" + normalizeScanRxTime
11684 + " TX=" + normalizeScanTxTime);
11685 }
11686
11687 long leftOverRxTimeMs = rxTimeMs;
11688 long leftOverTxTimeMs = txTimeMs;
11689
11690 for (int i = 0; i < uidCount; i++) {
11691 final Uid u = mUidStats.valueAt(i);
11692 if (u.mBluetoothScanTimer == null) {
11693 continue;
11694 }
11695
Bookatzaa4594a2017-03-24 12:39:56 -070011696 long scanTimeSinceMarkMs = u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011697 elapsedRealtimeMs * 1000) / 1000;
11698 if (scanTimeSinceMarkMs > 0) {
11699 // Set the new mark so that next time we get new data since this point.
11700 u.mBluetoothScanTimer.setMark(elapsedRealtimeMs);
11701
11702 long scanTimeRxSinceMarkMs = scanTimeSinceMarkMs;
11703 long scanTimeTxSinceMarkMs = scanTimeSinceMarkMs;
11704
11705 if (normalizeScanRxTime) {
11706 // Scan time is longer than the total rx time in the controller,
11707 // so distribute the scan time proportionately. This means regular traffic
11708 // will not blamed, but scans are more expensive anyways.
11709 scanTimeRxSinceMarkMs = (rxTimeMs * scanTimeRxSinceMarkMs) / totalScanTimeMs;
11710 }
11711
11712 if (normalizeScanTxTime) {
11713 // Scan time is longer than the total tx time in the controller,
11714 // so distribute the scan time proportionately. This means regular traffic
11715 // will not blamed, but scans are more expensive anyways.
11716 scanTimeTxSinceMarkMs = (txTimeMs * scanTimeTxSinceMarkMs) / totalScanTimeMs;
11717 }
11718
11719 final ControllerActivityCounterImpl counter =
11720 u.getOrCreateBluetoothControllerActivityLocked();
11721 counter.getRxTimeCounter().addCountLocked(scanTimeRxSinceMarkMs);
11722 counter.getTxTimeCounters()[0].addCountLocked(scanTimeTxSinceMarkMs);
11723
11724 leftOverRxTimeMs -= scanTimeRxSinceMarkMs;
11725 leftOverTxTimeMs -= scanTimeTxSinceMarkMs;
11726 }
11727 }
11728
11729 if (DEBUG_ENERGY) {
Mike Ma561a8d92018-03-20 18:24:05 -070011730 Slog.d(TAG, "Left over time for traffic RX=" + leftOverRxTimeMs + " TX="
11731 + leftOverTxTimeMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011732 }
11733
11734 //
11735 // Now distribute blame to apps that did bluetooth traffic.
11736 //
11737
11738 long totalTxBytes = 0;
11739 long totalRxBytes = 0;
11740
11741 final UidTraffic[] uidTraffic = info.getUidTraffic();
Mike Ma561a8d92018-03-20 18:24:05 -070011742 final int numUids = uidTraffic != null ? uidTraffic.length : 0;
11743 for (int i = 0; i < numUids; i++) {
11744 final UidTraffic traffic = uidTraffic[i];
11745 final long rxBytes = traffic.getRxBytes() - mLastBluetoothActivityInfo.uidRxBytes.get(
11746 traffic.getUid());
11747 final long txBytes = traffic.getTxBytes() - mLastBluetoothActivityInfo.uidTxBytes.get(
11748 traffic.getUid());
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011749
11750 // Add to the global counters.
Mike Ma561a8d92018-03-20 18:24:05 -070011751 mNetworkByteActivityCounters[NETWORK_BT_RX_DATA].addCountLocked(rxBytes);
11752 mNetworkByteActivityCounters[NETWORK_BT_TX_DATA].addCountLocked(txBytes);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011753
11754 // Add to the UID counters.
11755 final Uid u = getUidStatsLocked(mapUid(traffic.getUid()));
Mike Ma561a8d92018-03-20 18:24:05 -070011756 u.noteNetworkActivityLocked(NETWORK_BT_RX_DATA, rxBytes, 0);
11757 u.noteNetworkActivityLocked(NETWORK_BT_TX_DATA, txBytes, 0);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011758
11759 // Calculate the total traffic.
Mike Ma561a8d92018-03-20 18:24:05 -070011760 totalRxBytes += rxBytes;
11761 totalTxBytes += txBytes;
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011762 }
11763
Mike Ma561a8d92018-03-20 18:24:05 -070011764 if ((totalTxBytes != 0 || totalRxBytes != 0) && (leftOverRxTimeMs != 0
11765 || leftOverTxTimeMs != 0)) {
11766 for (int i = 0; i < numUids; i++) {
11767 final UidTraffic traffic = uidTraffic[i];
11768 final int uid = traffic.getUid();
11769 final long rxBytes =
11770 traffic.getRxBytes() - mLastBluetoothActivityInfo.uidRxBytes.get(uid);
11771 final long txBytes =
11772 traffic.getTxBytes() - mLastBluetoothActivityInfo.uidTxBytes.get(uid);
Adam Lesinski50e47602015-12-04 17:04:54 -080011773
Mike Ma561a8d92018-03-20 18:24:05 -070011774 final Uid u = getUidStatsLocked(mapUid(uid));
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011775 final ControllerActivityCounterImpl counter =
11776 u.getOrCreateBluetoothControllerActivityLocked();
11777
Mike Ma561a8d92018-03-20 18:24:05 -070011778 if (totalRxBytes > 0 && rxBytes > 0) {
11779 final long timeRxMs = (leftOverRxTimeMs * rxBytes) / totalRxBytes;
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011780 if (DEBUG_ENERGY) {
Mike Ma561a8d92018-03-20 18:24:05 -070011781 Slog.d(TAG, "UID=" + uid + " rx_bytes=" + rxBytes + " rx_time=" + timeRxMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011782 }
11783 counter.getRxTimeCounter().addCountLocked(timeRxMs);
11784 leftOverRxTimeMs -= timeRxMs;
11785 }
11786
Mike Ma561a8d92018-03-20 18:24:05 -070011787 if (totalTxBytes > 0 && txBytes > 0) {
11788 final long timeTxMs = (leftOverTxTimeMs * txBytes) / totalTxBytes;
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011789 if (DEBUG_ENERGY) {
Mike Ma561a8d92018-03-20 18:24:05 -070011790 Slog.d(TAG, "UID=" + uid + " tx_bytes=" + txBytes + " tx_time=" + timeTxMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011791 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011792 counter.getTxTimeCounters()[0].addCountLocked(timeTxMs);
11793 leftOverTxTimeMs -= timeTxMs;
11794 }
Adam Lesinski50e47602015-12-04 17:04:54 -080011795 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011796 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011797
Chenjie Yu89083392018-01-11 14:53:31 -080011798 mBluetoothActivity.getRxTimeCounter().addCountLocked(rxTimeMs);
11799 mBluetoothActivity.getTxTimeCounters()[0].addCountLocked(txTimeMs);
11800 mBluetoothActivity.getIdleTimeCounter().addCountLocked(idleTimeMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011801
11802 // POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11803 final double opVolt = mPowerProfile.getAveragePower(
11804 PowerProfile.POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11805 if (opVolt != 0) {
11806 // We store the power drain as mAms.
11807 mBluetoothActivity.getPowerCounter().addCountLocked(
Mike Ma561a8d92018-03-20 18:24:05 -070011808 (long) ((info.getControllerEnergyUsed() - mLastBluetoothActivityInfo.energy)
11809 / opVolt));
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011810 }
Mike Ma561a8d92018-03-20 18:24:05 -070011811 mLastBluetoothActivityInfo.set(info);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011812 }
11813
11814 /**
Bookatz0b8a0502017-09-13 11:51:52 -070011815 * Read and record Resource Power Manager (RPM) state and voter times.
11816 * If RPM stats were fetched more recently than RPM_STATS_UPDATE_FREQ_MS ago, uses the old data
11817 * instead of fetching it anew.
Bookatz50df7112017-08-04 14:53:26 -070011818 */
11819 public void updateRpmStatsLocked() {
11820 if (mPlatformIdleStateCallback == null) return;
Bookatz0b8a0502017-09-13 11:51:52 -070011821 long now = SystemClock.elapsedRealtime();
11822 if (now - mLastRpmStatsUpdateTimeMs >= RPM_STATS_UPDATE_FREQ_MS) {
11823 mPlatformIdleStateCallback.fillLowPowerStats(mTmpRpmStats);
11824 mLastRpmStatsUpdateTimeMs = now;
11825 }
Bookatz50df7112017-08-04 14:53:26 -070011826
11827 for (Map.Entry<String, RpmStats.PowerStatePlatformSleepState> pstate
11828 : mTmpRpmStats.mPlatformLowPowerStats.entrySet()) {
11829
11830 // Update values for this platform state.
11831 final String pName = pstate.getKey();
11832 final long pTimeUs = pstate.getValue().mTimeMs * 1000;
11833 final int pCount = pstate.getValue().mCount;
11834 getRpmTimerLocked(pName).update(pTimeUs, pCount);
Bookatz82b341172017-09-07 19:06:08 -070011835 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11836 getScreenOffRpmTimerLocked(pName).update(pTimeUs, pCount);
11837 }
Bookatz50df7112017-08-04 14:53:26 -070011838
11839 // Update values for each voter of this platform state.
11840 for (Map.Entry<String, RpmStats.PowerStateElement> voter
11841 : pstate.getValue().mVoters.entrySet()) {
11842 final String vName = pName + "." + voter.getKey();
11843 final long vTimeUs = voter.getValue().mTimeMs * 1000;
11844 final int vCount = voter.getValue().mCount;
11845 getRpmTimerLocked(vName).update(vTimeUs, vCount);
Bookatz82b341172017-09-07 19:06:08 -070011846 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11847 getScreenOffRpmTimerLocked(vName).update(vTimeUs, vCount);
11848 }
Bookatz50df7112017-08-04 14:53:26 -070011849 }
11850 }
11851
11852 for (Map.Entry<String, RpmStats.PowerStateSubsystem> subsys
11853 : mTmpRpmStats.mSubsystemLowPowerStats.entrySet()) {
11854
11855 final String subsysName = subsys.getKey();
11856 for (Map.Entry<String, RpmStats.PowerStateElement> sstate
11857 : subsys.getValue().mStates.entrySet()) {
11858 final String name = subsysName + "." + sstate.getKey();
11859 final long timeUs = sstate.getValue().mTimeMs * 1000;
11860 final int count = sstate.getValue().mCount;
11861 getRpmTimerLocked(name).update(timeUs, count);
Bookatz82b341172017-09-07 19:06:08 -070011862 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11863 getScreenOffRpmTimerLocked(name).update(timeUs, count);
11864 }
Bookatz50df7112017-08-04 14:53:26 -070011865 }
11866 }
11867 }
11868
11869 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011870 * Read and distribute kernel wake lock use across apps.
11871 */
11872 public void updateKernelWakelocksLocked() {
11873 final KernelWakelockStats wakelockStats = mKernelWakelockReader.readKernelWakelockStats(
11874 mTmpWakelockStats);
11875 if (wakelockStats == null) {
11876 // Not crashing might make board bringup easier.
11877 Slog.w(TAG, "Couldn't get kernel wake lock stats");
11878 return;
11879 }
11880
11881 for (Map.Entry<String, KernelWakelockStats.Entry> ent : wakelockStats.entrySet()) {
11882 String name = ent.getKey();
11883 KernelWakelockStats.Entry kws = ent.getValue();
11884
11885 SamplingTimer kwlt = mKernelWakelockStats.get(name);
11886 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -070011887 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011888 mKernelWakelockStats.put(name, kwlt);
11889 }
Adam Lesinskid84ad302016-05-17 18:31:02 -070011890
Adam Lesinski757c6ea2016-04-21 09:55:41 -070011891 kwlt.update(kws.mTotalTime, kws.mCount);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011892 kwlt.setUpdateVersion(kws.mVersion);
11893 }
11894
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011895 int numWakelocksSetStale = 0;
Adam Lesinskid84ad302016-05-17 18:31:02 -070011896 // Set timers to stale if they didn't appear in /d/wakeup_sources (or /proc/wakelocks)
11897 // this time.
11898 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
11899 SamplingTimer st = ent.getValue();
11900 if (st.getUpdateVersion() != wakelockStats.kernelWakelockVersion) {
11901 st.endSample();
11902 numWakelocksSetStale++;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011903 }
11904 }
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011905
Adam Lesinskid84ad302016-05-17 18:31:02 -070011906 // Record whether we've seen a non-zero time (for debugging b/22716723).
11907 if (wakelockStats.isEmpty()) {
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011908 Slog.wtf(TAG, "All kernel wakelocks had time of zero");
11909 }
11910
11911 if (numWakelocksSetStale == mKernelWakelockStats.size()) {
11912 Slog.wtf(TAG, "All kernel wakelocks were set stale. new version=" +
11913 wakelockStats.kernelWakelockVersion);
11914 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011915 }
11916
Adam Lesinski72478f02015-06-17 15:39:43 -070011917 // We use an anonymous class to access these variables,
11918 // so they can't live on the stack or they'd have to be
11919 // final MutableLong objects (more allocations).
11920 // Used in updateCpuTimeLocked().
11921 long mTempTotalCpuUserTimeUs;
11922 long mTempTotalCpuSystemTimeUs;
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011923 long[][] mWakeLockAllocationsUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070011924
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011925 /**
James Carr3a226052016-07-01 14:49:52 -070011926 * Reads the newest memory stats from the kernel.
11927 */
11928 public void updateKernelMemoryBandwidthLocked() {
11929 mKernelMemoryBandwidthStats.updateStats();
11930 LongSparseLongArray bandwidthEntries = mKernelMemoryBandwidthStats.getBandwidthEntries();
11931 final int bandwidthEntryCount = bandwidthEntries.size();
11932 int index;
11933 for (int i = 0; i < bandwidthEntryCount; i++) {
11934 SamplingTimer timer;
11935 if ((index = mKernelMemoryStats.indexOfKey(bandwidthEntries.keyAt(i))) >= 0) {
11936 timer = mKernelMemoryStats.valueAt(index);
11937 } else {
11938 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
11939 mKernelMemoryStats.put(bandwidthEntries.keyAt(i), timer);
11940 }
11941 timer.update(bandwidthEntries.valueAt(i), 1);
11942 if (DEBUG_MEMORY) {
11943 Slog.d(TAG, String.format("Added entry %d and updated timer to: "
11944 + "mUnpluggedReportedTotalTime %d size %d", bandwidthEntries.keyAt(i),
11945 mKernelMemoryStats.get(
11946 bandwidthEntries.keyAt(i)).mUnpluggedReportedTotalTime,
11947 mKernelMemoryStats.size()));
11948 }
11949 }
11950 }
11951
Sudheer Shankac57729a2018-02-09 15:44:42 -080011952 public boolean isOnBatteryLocked() {
11953 return mOnBatteryTimeBase.isRunning();
11954 }
11955
11956 public boolean isOnBatteryScreenOffLocked() {
11957 return mOnBatteryScreenOffTimeBase.isRunning();
11958 }
11959
James Carr3a226052016-07-01 14:49:52 -070011960 /**
Adam Lesinski72478f02015-06-17 15:39:43 -070011961 * Read and distribute CPU usage across apps. If their are partial wakelocks being held
11962 * and we are on battery with screen off, we give more of the cpu time to those apps holding
11963 * wakelocks. If the screen is on, we just assign the actual cpu time an app used.
Sudheer Shankac57729a2018-02-09 15:44:42 -080011964 * It's possible this will be invoked after the internal battery/screen states are updated, so
11965 * passing the appropriate battery/screen states to try attribute the cpu times to correct
11966 * buckets.
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011967 */
Andreas Gampe3f24e692018-02-05 13:24:28 -080011968 @GuardedBy("this")
Sudheer Shankac57729a2018-02-09 15:44:42 -080011969 public void updateCpuTimeLocked(boolean onBattery, boolean onBatteryScreenOff) {
Adam Lesinski52290c9c2015-09-21 16:54:52 -070011970 if (mPowerProfile == null) {
11971 return;
11972 }
11973
Adam Lesinski72478f02015-06-17 15:39:43 -070011974 if (DEBUG_ENERGY_CPU) {
11975 Slog.d(TAG, "!Cpu updating!");
11976 }
11977
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011978 if (mCpuFreqs == null) {
11979 mCpuFreqs = mKernelUidCpuFreqTimeReader.readFreqs(mPowerProfile);
11980 }
11981
Sudheer Shanka38383232017-07-25 09:55:03 -070011982 // Calculate the wakelocks we have to distribute amongst. The system is excluded as it is
11983 // usually holding the wakelock on behalf of an app.
11984 // And Only distribute cpu power to wakelocks if the screen is off and we're on battery.
11985 ArrayList<StopwatchTimer> partialTimersToConsider = null;
Sudheer Shankac57729a2018-02-09 15:44:42 -080011986 if (onBatteryScreenOff) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011987 partialTimersToConsider = new ArrayList<>();
11988 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070011989 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070011990 // Since the collection and blaming of wakelocks can be scheduled to run after
11991 // some delay, the mPartialTimers list may have new entries. We can't blame
11992 // the newly added timer for past cpu time, so we only consider timers that
11993 // were present for one round of collection. Once a timer has gone through
11994 // a round of collection, its mInList field is set to true.
Adam Lesinski72478f02015-06-17 15:39:43 -070011995 if (timer.mInList && timer.mUid != null && timer.mUid.mUid != Process.SYSTEM_UID) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011996 partialTimersToConsider.add(timer);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011997 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011998 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011999 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012000 markPartialTimersAsEligible();
Adam Lesinski72478f02015-06-17 15:39:43 -070012001
Sudheer Shanka38383232017-07-25 09:55:03 -070012002 // When the battery is not on, we don't attribute the cpu times to any timers but we still
12003 // need to take the snapshots.
Sudheer Shankac57729a2018-02-09 15:44:42 -080012004 if (!onBattery) {
Sudheer Shanka38383232017-07-25 09:55:03 -070012005 mKernelUidCpuTimeReader.readDelta(null);
12006 mKernelUidCpuFreqTimeReader.readDelta(null);
Mike Ma234d1822018-03-13 18:53:21 -070012007 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080012008 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
12009 mKernelUidCpuActiveTimeReader.readDelta(null);
12010 mKernelUidCpuClusterTimeReader.readDelta(null);
Mike Ma234d1822018-03-13 18:53:21 -070012011 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080012012 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012013 for (int cluster = mKernelCpuSpeedReaders.length - 1; cluster >= 0; --cluster) {
12014 mKernelCpuSpeedReaders[cluster].readDelta();
12015 }
12016 return;
12017 }
Adam Lesinski72478f02015-06-17 15:39:43 -070012018
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070012019 mUserInfoProvider.refreshUserIds();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012020 final SparseLongArray updatedUids = mKernelUidCpuFreqTimeReader.perClusterTimesAvailable()
12021 ? null : new SparseLongArray();
Sudheer Shankac57729a2018-02-09 15:44:42 -080012022 readKernelUidCpuTimesLocked(partialTimersToConsider, updatedUids, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012023 // updatedUids=null means /proc/uid_time_in_state provides snapshots of per-cluster cpu
12024 // freqs, so no need to approximate these values.
12025 if (updatedUids != null) {
Sudheer Shankac57729a2018-02-09 15:44:42 -080012026 updateClusterSpeedTimes(updatedUids, onBattery);
Sudheer Shanka671985f2017-05-19 11:33:42 -070012027 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080012028 readKernelUidCpuFreqTimesLocked(partialTimersToConsider, onBattery, onBatteryScreenOff);
Mike Ma234d1822018-03-13 18:53:21 -070012029 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080012030 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
Sudheer Shankac57729a2018-02-09 15:44:42 -080012031 readKernelUidCpuActiveTimesLocked(onBattery);
12032 readKernelUidCpuClusterTimesLocked(onBattery);
Mike Ma234d1822018-03-13 18:53:21 -070012033 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080012034 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012035 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012036
Sudheer Shanka38383232017-07-25 09:55:03 -070012037 /**
12038 * Mark the current partial timers as gone through a collection so that they will be
12039 * considered in the next cpu times distribution to wakelock holders.
12040 */
12041 @VisibleForTesting
12042 public void markPartialTimersAsEligible() {
12043 if (ArrayUtils.referenceEquals(mPartialTimers, mLastPartialTimers)) {
12044 // No difference, so each timer is now considered for the next collection.
12045 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
12046 mPartialTimers.get(i).mInList = true;
12047 }
12048 } else {
12049 // The lists are different, meaning we added (or removed a timer) since the last
12050 // collection.
12051 for (int i = mLastPartialTimers.size() - 1; i >= 0; --i) {
12052 mLastPartialTimers.get(i).mInList = false;
12053 }
12054 mLastPartialTimers.clear();
Adam Lesinski72478f02015-06-17 15:39:43 -070012055
Sudheer Shanka38383232017-07-25 09:55:03 -070012056 // Mark the current timers as gone through a collection.
12057 final int numPartialTimers = mPartialTimers.size();
12058 for (int i = 0; i < numPartialTimers; ++i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070012059 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070012060 timer.mInList = true;
12061 mLastPartialTimers.add(timer);
Adam Lesinski72478f02015-06-17 15:39:43 -070012062 }
12063 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012064 }
Adam Lesinski72478f02015-06-17 15:39:43 -070012065
Sudheer Shanka38383232017-07-25 09:55:03 -070012066 /**
12067 * Take snapshot of cpu times (aggregated over all uids) at different frequencies and
12068 * calculate cpu times spent by each uid at different frequencies.
12069 *
12070 * @param updatedUids The uids for which times spent at different frequencies are calculated.
12071 */
12072 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012073 public void updateClusterSpeedTimes(@NonNull SparseLongArray updatedUids, boolean onBattery) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070012074 long totalCpuClustersTimeMs = 0;
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012075 // Read the time spent for each cluster at various cpu frequencies.
Sudheer Shankaaf857412017-07-21 00:14:24 -070012076 final long[][] clusterSpeedTimesMs = new long[mKernelCpuSpeedReaders.length][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012077 for (int cluster = 0; cluster < mKernelCpuSpeedReaders.length; cluster++) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070012078 clusterSpeedTimesMs[cluster] = mKernelCpuSpeedReaders[cluster].readDelta();
12079 if (clusterSpeedTimesMs[cluster] != null) {
12080 for (int speed = clusterSpeedTimesMs[cluster].length - 1; speed >= 0; --speed) {
12081 totalCpuClustersTimeMs += clusterSpeedTimesMs[cluster][speed];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012082 }
12083 }
12084 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070012085 if (totalCpuClustersTimeMs != 0) {
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012086 // We have cpu times per freq aggregated over all uids but we need the times per uid.
12087 // So, we distribute total time spent by an uid to different cpu freqs based on the
12088 // amount of time cpu was running at that freq.
12089 final int updatedUidsCount = updatedUids.size();
12090 for (int i = 0; i < updatedUidsCount; ++i) {
12091 final Uid u = getUidStatsLocked(updatedUids.keyAt(i));
Sudheer Shankaaf857412017-07-21 00:14:24 -070012092 final long appCpuTimeUs = updatedUids.valueAt(i);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012093 // Add the cpu speeds to this UID.
12094 final int numClusters = mPowerProfile.getNumCpuClusters();
Sudheer Shanka38383232017-07-25 09:55:03 -070012095 if (u.mCpuClusterSpeedTimesUs == null ||
12096 u.mCpuClusterSpeedTimesUs.length != numClusters) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070012097 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012098 }
12099
Sudheer Shankaaf857412017-07-21 00:14:24 -070012100 for (int cluster = 0; cluster < clusterSpeedTimesMs.length; cluster++) {
12101 final int speedsInCluster = clusterSpeedTimesMs[cluster].length;
12102 if (u.mCpuClusterSpeedTimesUs[cluster] == null || speedsInCluster !=
12103 u.mCpuClusterSpeedTimesUs[cluster].length) {
12104 u.mCpuClusterSpeedTimesUs[cluster]
12105 = new LongSamplingCounter[speedsInCluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012106 }
12107
Sudheer Shankaaf857412017-07-21 00:14:24 -070012108 final LongSamplingCounter[] cpuSpeeds = u.mCpuClusterSpeedTimesUs[cluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012109 for (int speed = 0; speed < speedsInCluster; speed++) {
12110 if (cpuSpeeds[speed] == null) {
12111 cpuSpeeds[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
12112 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070012113 cpuSpeeds[speed].addCountLocked(appCpuTimeUs
12114 * clusterSpeedTimesMs[cluster][speed]
Sudheer Shankac57729a2018-02-09 15:44:42 -080012115 / totalCpuClustersTimeMs, onBattery);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012116 }
12117 }
12118 }
12119 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012120 }
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012121
Sudheer Shanka38383232017-07-25 09:55:03 -070012122 /**
12123 * Take a snapshot of the cpu times spent by each uid and update the corresponding counters.
12124 * If {@param partialTimers} is not null and empty, then we assign a portion of cpu times to
12125 * wakelock holders.
12126 *
12127 * @param partialTimers The wakelock holders among which the cpu times will be distributed.
12128 * @param updatedUids If not null, then the uids found in the snapshot will be added to this.
12129 */
12130 @VisibleForTesting
12131 public void readKernelUidCpuTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers,
Sudheer Shankac57729a2018-02-09 15:44:42 -080012132 @Nullable SparseLongArray updatedUids, boolean onBattery) {
Sudheer Shanka38383232017-07-25 09:55:03 -070012133 mTempTotalCpuUserTimeUs = mTempTotalCpuSystemTimeUs = 0;
12134 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
12135 final long startTimeMs = mClocks.uptimeMillis();
Adam Lesinski72478f02015-06-17 15:39:43 -070012136
Sudheer Shanka38383232017-07-25 09:55:03 -070012137 mKernelUidCpuTimeReader.readDelta((uid, userTimeUs, systemTimeUs) -> {
12138 uid = mapUid(uid);
12139 if (Process.isIsolated(uid)) {
12140 // This could happen if the isolated uid mapping was removed before that process
12141 // was actually killed.
12142 mKernelUidCpuTimeReader.removeUid(uid);
12143 Slog.d(TAG, "Got readings for an isolated uid with no mapping: " + uid);
12144 return;
12145 }
12146 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12147 Slog.d(TAG, "Got readings for an invalid user's uid " + uid);
12148 mKernelUidCpuTimeReader.removeUid(uid);
12149 return;
12150 }
12151 final Uid u = getUidStatsLocked(uid);
12152
12153 // Accumulate the total system and user time.
12154 mTempTotalCpuUserTimeUs += userTimeUs;
12155 mTempTotalCpuSystemTimeUs += systemTimeUs;
12156
12157 StringBuilder sb = null;
12158 if (DEBUG_ENERGY_CPU) {
12159 sb = new StringBuilder();
12160 sb.append(" got time for uid=").append(u.mUid).append(": u=");
12161 TimeUtils.formatDuration(userTimeUs / 1000, sb);
12162 sb.append(" s=");
12163 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
12164 sb.append("\n");
12165 }
12166
12167 if (numWakelocks > 0) {
12168 // We have wakelocks being held, so only give a portion of the
12169 // time to the process. The rest will be distributed among wakelock
12170 // holders.
12171 userTimeUs = (userTimeUs * WAKE_LOCK_WEIGHT) / 100;
12172 systemTimeUs = (systemTimeUs * WAKE_LOCK_WEIGHT) / 100;
12173 }
12174
12175 if (sb != null) {
12176 sb.append(" adding to uid=").append(u.mUid).append(": u=");
12177 TimeUtils.formatDuration(userTimeUs / 1000, sb);
12178 sb.append(" s=");
12179 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
12180 Slog.d(TAG, sb.toString());
12181 }
12182
Sudheer Shankac57729a2018-02-09 15:44:42 -080012183 u.mUserCpuTime.addCountLocked(userTimeUs, onBattery);
12184 u.mSystemCpuTime.addCountLocked(systemTimeUs, onBattery);
Sudheer Shanka38383232017-07-25 09:55:03 -070012185 if (updatedUids != null) {
12186 updatedUids.put(u.getUid(), userTimeUs + systemTimeUs);
12187 }
12188 });
12189
12190 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12191 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12192 Slog.d(TAG, "Reading cpu stats took " + elapsedTimeMs + "ms");
12193 }
12194
12195 if (numWakelocks > 0) {
12196 // Distribute a portion of the total cpu time to wakelock holders.
12197 mTempTotalCpuUserTimeUs = (mTempTotalCpuUserTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
12198 mTempTotalCpuSystemTimeUs =
12199 (mTempTotalCpuSystemTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
12200
12201 for (int i = 0; i < numWakelocks; ++i) {
12202 final StopwatchTimer timer = partialTimers.get(i);
12203 final int userTimeUs = (int) (mTempTotalCpuUserTimeUs / (numWakelocks - i));
12204 final int systemTimeUs = (int) (mTempTotalCpuSystemTimeUs / (numWakelocks - i));
12205
12206 if (DEBUG_ENERGY_CPU) {
12207 final StringBuilder sb = new StringBuilder();
12208 sb.append(" Distributing wakelock uid=").append(timer.mUid.mUid)
12209 .append(": u=");
12210 TimeUtils.formatDuration(userTimeUs / 1000, sb);
12211 sb.append(" s=");
12212 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
12213 Slog.d(TAG, sb.toString());
12214 }
12215
Sudheer Shankac57729a2018-02-09 15:44:42 -080012216 timer.mUid.mUserCpuTime.addCountLocked(userTimeUs, onBattery);
12217 timer.mUid.mSystemCpuTime.addCountLocked(systemTimeUs, onBattery);
Sudheer Shanka38383232017-07-25 09:55:03 -070012218 if (updatedUids != null) {
12219 final int uid = timer.mUid.getUid();
12220 updatedUids.put(uid, updatedUids.get(uid, 0) + userTimeUs + systemTimeUs);
12221 }
12222
12223 final Uid.Proc proc = timer.mUid.getProcessStatsLocked("*wakelock*");
Sudheer Shankac57729a2018-02-09 15:44:42 -080012224 proc.addCpuTimeLocked(userTimeUs / 1000, systemTimeUs / 1000, onBattery);
Sudheer Shanka38383232017-07-25 09:55:03 -070012225
12226 mTempTotalCpuUserTimeUs -= userTimeUs;
12227 mTempTotalCpuSystemTimeUs -= systemTimeUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070012228 }
12229 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070012230 }
12231
Sudheer Shanka38383232017-07-25 09:55:03 -070012232 /**
12233 * Take a snapshot of the cpu times spent by each uid in each freq and update the
12234 * corresponding counters.
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012235 *
12236 * @param partialTimers The wakelock holders among which the cpu freq times will be distributed.
Sudheer Shanka38383232017-07-25 09:55:03 -070012237 */
12238 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012239 public void readKernelUidCpuFreqTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers,
12240 boolean onBattery, boolean onBatteryScreenOff) {
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012241 final boolean perClusterTimesAvailable =
12242 mKernelUidCpuFreqTimeReader.perClusterTimesAvailable();
12243 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
12244 final int numClusters = mPowerProfile.getNumCpuClusters();
12245 mWakeLockAllocationsUs = null;
Sudheer Shankaac5b88f2017-12-11 15:36:35 -080012246 final long startTimeMs = mClocks.uptimeMillis();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012247 mKernelUidCpuFreqTimeReader.readDelta((uid, cpuFreqTimeMs) -> {
12248 uid = mapUid(uid);
12249 if (Process.isIsolated(uid)) {
12250 mKernelUidCpuFreqTimeReader.removeUid(uid);
12251 Slog.d(TAG, "Got freq readings for an isolated uid with no mapping: " + uid);
12252 return;
Sudheer Shanka38383232017-07-25 09:55:03 -070012253 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012254 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12255 Slog.d(TAG, "Got freq readings for an invalid user's uid " + uid);
12256 mKernelUidCpuFreqTimeReader.removeUid(uid);
12257 return;
12258 }
12259 final Uid u = getUidStatsLocked(uid);
12260 if (u.mCpuFreqTimeMs == null || u.mCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
12261 u.mCpuFreqTimeMs = new LongSamplingCounterArray(mOnBatteryTimeBase);
12262 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080012263 u.mCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012264 if (u.mScreenOffCpuFreqTimeMs == null ||
12265 u.mScreenOffCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
12266 u.mScreenOffCpuFreqTimeMs = new LongSamplingCounterArray(
12267 mOnBatteryScreenOffTimeBase);
12268 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080012269 u.mScreenOffCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs, onBatteryScreenOff);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012270
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012271 if (perClusterTimesAvailable) {
12272 if (u.mCpuClusterSpeedTimesUs == null ||
12273 u.mCpuClusterSpeedTimesUs.length != numClusters) {
12274 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070012275 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012276 if (numWakelocks > 0 && mWakeLockAllocationsUs == null) {
12277 mWakeLockAllocationsUs = new long[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070012278 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012279
12280 int freqIndex = 0;
12281 for (int cluster = 0; cluster < numClusters; ++cluster) {
12282 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
12283 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
12284 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
12285 u.mCpuClusterSpeedTimesUs[cluster]
12286 = new LongSamplingCounter[speedsInCluster];
12287 }
12288 if (numWakelocks > 0 && mWakeLockAllocationsUs[cluster] == null) {
12289 mWakeLockAllocationsUs[cluster] = new long[speedsInCluster];
12290 }
12291 final LongSamplingCounter[] cpuTimesUs = u.mCpuClusterSpeedTimesUs[cluster];
12292 for (int speed = 0; speed < speedsInCluster; ++speed) {
12293 if (cpuTimesUs[speed] == null) {
12294 cpuTimesUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
12295 }
12296 final long appAllocationUs;
12297 if (mWakeLockAllocationsUs != null) {
12298 appAllocationUs =
12299 (cpuFreqTimeMs[freqIndex] * 1000 * WAKE_LOCK_WEIGHT) / 100;
12300 mWakeLockAllocationsUs[cluster][speed] +=
12301 (cpuFreqTimeMs[freqIndex] * 1000 - appAllocationUs);
12302 } else {
12303 appAllocationUs = cpuFreqTimeMs[freqIndex] * 1000;
12304 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080012305 cpuTimesUs[speed].addCountLocked(appAllocationUs, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012306 freqIndex++;
12307 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012308 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012309 }
12310 });
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012311
Sudheer Shankaac5b88f2017-12-11 15:36:35 -080012312 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12313 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12314 Slog.d(TAG, "Reading cpu freq times took " + elapsedTimeMs + "ms");
12315 }
12316
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012317 if (mWakeLockAllocationsUs != null) {
12318 for (int i = 0; i < numWakelocks; ++i) {
12319 final Uid u = partialTimers.get(i).mUid;
12320 if (u.mCpuClusterSpeedTimesUs == null ||
12321 u.mCpuClusterSpeedTimesUs.length != numClusters) {
12322 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
12323 }
12324
12325 for (int cluster = 0; cluster < numClusters; ++cluster) {
12326 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
12327 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
12328 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
12329 u.mCpuClusterSpeedTimesUs[cluster]
12330 = new LongSamplingCounter[speedsInCluster];
12331 }
12332 final LongSamplingCounter[] cpuTimeUs = u.mCpuClusterSpeedTimesUs[cluster];
12333 for (int speed = 0; speed < speedsInCluster; ++speed) {
12334 if (cpuTimeUs[speed] == null) {
12335 cpuTimeUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
12336 }
12337 final long allocationUs =
12338 mWakeLockAllocationsUs[cluster][speed] / (numWakelocks - i);
Sudheer Shankac57729a2018-02-09 15:44:42 -080012339 cpuTimeUs[speed].addCountLocked(allocationUs, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012340 mWakeLockAllocationsUs[cluster][speed] -= allocationUs;
12341 }
12342 }
12343 }
12344 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012345 }
12346
Mike Ma3d422c32017-10-25 11:08:57 -070012347 /**
12348 * Take a snapshot of the cpu active times spent by each uid and update the corresponding
12349 * counters.
12350 */
12351 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012352 public void readKernelUidCpuActiveTimesLocked(boolean onBattery) {
Mike Ma3d422c32017-10-25 11:08:57 -070012353 final long startTimeMs = mClocks.uptimeMillis();
Mike Ma2ab01442018-02-13 14:22:47 -080012354 mKernelUidCpuActiveTimeReader.readDelta((uid, cpuActiveTimesMs) -> {
Mike Ma3d422c32017-10-25 11:08:57 -070012355 uid = mapUid(uid);
12356 if (Process.isIsolated(uid)) {
12357 mKernelUidCpuActiveTimeReader.removeUid(uid);
12358 Slog.w(TAG, "Got active times for an isolated uid with no mapping: " + uid);
12359 return;
12360 }
12361 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12362 Slog.w(TAG, "Got active times for an invalid user's uid " + uid);
12363 mKernelUidCpuActiveTimeReader.removeUid(uid);
12364 return;
12365 }
12366 final Uid u = getUidStatsLocked(uid);
Mike Ma2ab01442018-02-13 14:22:47 -080012367 u.mCpuActiveTimeMs.addCountLocked(cpuActiveTimesMs, onBattery);
Mike Ma3d422c32017-10-25 11:08:57 -070012368 });
12369
12370 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12371 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12372 Slog.d(TAG, "Reading cpu active times took " + elapsedTimeMs + "ms");
12373 }
12374 }
12375
12376 /**
12377 * Take a snapshot of the cpu cluster times spent by each uid and update the corresponding
12378 * counters.
12379 */
12380 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012381 public void readKernelUidCpuClusterTimesLocked(boolean onBattery) {
Mike Ma3d422c32017-10-25 11:08:57 -070012382 final long startTimeMs = mClocks.uptimeMillis();
Mike Ma2ab01442018-02-13 14:22:47 -080012383 mKernelUidCpuClusterTimeReader.readDelta((uid, cpuClusterTimesMs) -> {
Mike Ma3d422c32017-10-25 11:08:57 -070012384 uid = mapUid(uid);
12385 if (Process.isIsolated(uid)) {
12386 mKernelUidCpuClusterTimeReader.removeUid(uid);
12387 Slog.w(TAG, "Got cluster times for an isolated uid with no mapping: " + uid);
12388 return;
12389 }
12390 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12391 Slog.w(TAG, "Got cluster times for an invalid user's uid " + uid);
12392 mKernelUidCpuClusterTimeReader.removeUid(uid);
12393 return;
12394 }
12395 final Uid u = getUidStatsLocked(uid);
Mike Ma2ab01442018-02-13 14:22:47 -080012396 u.mCpuClusterTimesMs.addCountLocked(cpuClusterTimesMs, onBattery);
Mike Ma3d422c32017-10-25 11:08:57 -070012397 });
12398
12399 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12400 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12401 Slog.d(TAG, "Reading cpu cluster times took " + elapsedTimeMs + "ms");
12402 }
12403 }
12404
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012405 boolean setChargingLocked(boolean charging) {
12406 if (mCharging != charging) {
12407 mCharging = charging;
12408 if (charging) {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012409 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012410 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012411 mHistoryCur.states2 &= ~HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012412 }
12413 mHandler.sendEmptyMessage(MSG_REPORT_CHARGING);
12414 return true;
12415 }
12416 return false;
12417 }
12418
Andreas Gampe3f24e692018-02-05 13:24:28 -080012419 @GuardedBy("this")
Mike Mac2f518a2017-09-19 16:06:03 -070012420 protected void setOnBatteryLocked(final long mSecRealtime, final long mSecUptime,
12421 final boolean onBattery, final int oldStatus, final int level, final int chargeUAh) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012422 boolean doWrite = false;
12423 Message m = mHandler.obtainMessage(MSG_REPORT_POWER_CHANGE);
12424 m.arg1 = onBattery ? 1 : 0;
12425 mHandler.sendMessage(m);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012426
Dianne Hackborn40c87252014-03-19 16:55:40 -070012427 final long uptime = mSecUptime * 1000;
12428 final long realtime = mSecRealtime * 1000;
Mike Mac2f518a2017-09-19 16:06:03 -070012429 final int screenState = mScreenState;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012430 if (onBattery) {
12431 // We will reset our status if we are unplugging after the
12432 // battery was last full, or the level is at 100, or
12433 // we have gone through a significant charge (from a very low
12434 // level to a now very high level).
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080012435 boolean reset = false;
Dianne Hackborn9a755432014-05-15 17:05:22 -070012436 if (!mNoAutoReset && (oldStatus == BatteryManager.BATTERY_STATUS_FULL
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012437 || level >= 90
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070012438 || (mDischargeCurrentLevel < 20 && level >= 80)
12439 || (getHighDischargeAmountSinceCharge() >= 200
12440 && mHistoryBuffer.dataSize() >= MAX_HISTORY_BUFFER))) {
Dianne Hackborn73d6a822014-09-29 10:52:47 -070012441 Slog.i(TAG, "Resetting battery stats: level=" + level + " status=" + oldStatus
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070012442 + " dischargeLevel=" + mDischargeCurrentLevel
Dianne Hackborn73d6a822014-09-29 10:52:47 -070012443 + " lowAmount=" + getLowDischargeAmountSinceCharge()
12444 + " highAmount=" + getHighDischargeAmountSinceCharge());
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012445 // Before we write, collect a snapshot of the final aggregated
12446 // stats to be reported in the next checkin. Only do this if we have
12447 // a sufficient amount of data to make it interesting.
12448 if (getLowDischargeAmountSinceCharge() >= 20) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080012449 final long startTime = SystemClock.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012450 final Parcel parcel = Parcel.obtain();
12451 writeSummaryToParcel(parcel, true);
Dianne Hackborne17b4452018-01-10 13:15:40 -080012452 final long initialTime = SystemClock.uptimeMillis() - startTime;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012453 BackgroundThread.getHandler().post(new Runnable() {
12454 @Override public void run() {
12455 synchronized (mCheckinFile) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080012456 final long startTime2 = SystemClock.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012457 FileOutputStream stream = null;
12458 try {
12459 stream = mCheckinFile.startWrite();
12460 stream.write(parcel.marshall());
12461 stream.flush();
12462 FileUtils.sync(stream);
12463 stream.close();
12464 mCheckinFile.finishWrite(stream);
Dianne Hackborne17b4452018-01-10 13:15:40 -080012465 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
12466 "batterystats-checkin",
12467 initialTime + SystemClock.uptimeMillis() - startTime2);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012468 } catch (IOException e) {
12469 Slog.w("BatteryStats",
12470 "Error writing checkin battery statistics", e);
12471 mCheckinFile.failWrite(stream);
12472 } finally {
12473 parcel.recycle();
12474 }
12475 }
12476 }
12477 });
12478 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012479 doWrite = true;
12480 resetAllStatsLocked();
Ying Wai (Daniel) Fan442ab762017-01-31 22:00:10 -080012481 if (chargeUAh > 0 && level > 0) {
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012482 // Only use the reported coulomb charge value if it is supported and reported.
Ying Wai (Daniel) Fan9238b612017-01-18 15:50:19 -080012483 mEstimatedBatteryCapacity = (int) ((chargeUAh / 1000) / (level / 100.0));
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012484 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012485 mDischargeStartLevel = level;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080012486 reset = true;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012487 mDischargeStepTracker.init();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012488 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012489 if (mCharging) {
12490 setChargingLocked(false);
12491 }
12492 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080012493 mOnBattery = mOnBatteryInternal = true;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012494 mLastDischargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070012495 mMinDischargeStepLevel = level;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012496 mDischargeStepTracker.clearTime();
12497 mDailyDischargeStepTracker.clearTime();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012498 mInitStepMode = mCurStepMode;
12499 mModStepMode = 0;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012500 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012501 mHistoryCur.batteryLevel = (byte)level;
12502 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
12503 if (DEBUG_HISTORY) Slog.v(TAG, "Battery unplugged to: "
12504 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012505 if (reset) {
12506 mRecordingHistory = true;
12507 startRecordingHistory(mSecRealtime, mSecUptime, reset);
12508 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070012509 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012510 mDischargeCurrentLevel = mDischargeUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070012511 if (isScreenOn(screenState)) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012512 mDischargeScreenOnUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070012513 mDischargeScreenDozeUnplugLevel = 0;
12514 mDischargeScreenOffUnplugLevel = 0;
12515 } else if (isScreenDoze(screenState)) {
12516 mDischargeScreenOnUnplugLevel = 0;
12517 mDischargeScreenDozeUnplugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012518 mDischargeScreenOffUnplugLevel = 0;
12519 } else {
12520 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012521 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012522 mDischargeScreenOffUnplugLevel = level;
12523 }
12524 mDischargeAmountScreenOn = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012525 mDischargeAmountScreenDoze = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012526 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012527 updateTimeBasesLocked(true, screenState, uptime, realtime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012528 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012529 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080012530 mOnBattery = mOnBatteryInternal = false;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012531 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012532 mHistoryCur.batteryLevel = (byte)level;
12533 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
12534 if (DEBUG_HISTORY) Slog.v(TAG, "Battery plugged to: "
12535 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -070012536 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012537 mDischargeCurrentLevel = mDischargePlugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012538 if (level < mDischargeUnplugLevel) {
12539 mLowDischargeAmountSinceCharge += mDischargeUnplugLevel-level-1;
12540 mHighDischargeAmountSinceCharge += mDischargeUnplugLevel-level;
12541 }
Mike Mac2f518a2017-09-19 16:06:03 -070012542 updateDischargeScreenLevelsLocked(screenState, screenState);
12543 updateTimeBasesLocked(false, screenState, uptime, realtime);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012544 mChargeStepTracker.init();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012545 mLastChargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070012546 mMaxChargeStepLevel = level;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012547 mInitStepMode = mCurStepMode;
12548 mModStepMode = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012549 }
12550 if (doWrite || (mLastWriteTime + (60 * 1000)) < mSecRealtime) {
12551 if (mFile != null) {
12552 writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012553 }
12554 }
12555 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012556
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012557 private void startRecordingHistory(final long elapsedRealtimeMs, final long uptimeMs,
12558 boolean reset) {
12559 mRecordingHistory = true;
12560 mHistoryCur.currentTime = System.currentTimeMillis();
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012561 addHistoryBufferLocked(elapsedRealtimeMs,
Dianne Hackborn37de0982014-05-09 09:32:18 -070012562 reset ? HistoryItem.CMD_RESET : HistoryItem.CMD_CURRENT_TIME,
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012563 mHistoryCur);
12564 mHistoryCur.currentTime = 0;
12565 if (reset) {
12566 initActiveHistoryEventsLocked(elapsedRealtimeMs, uptimeMs);
12567 }
12568 }
12569
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012570 private void recordCurrentTimeChangeLocked(final long currentTime, final long elapsedRealtimeMs,
12571 final long uptimeMs) {
12572 if (mRecordingHistory) {
12573 mHistoryCur.currentTime = currentTime;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012574 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_CURRENT_TIME, mHistoryCur);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012575 mHistoryCur.currentTime = 0;
12576 }
12577 }
12578
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080012579 private void recordShutdownLocked(final long elapsedRealtimeMs, final long uptimeMs) {
12580 if (mRecordingHistory) {
12581 mHistoryCur.currentTime = System.currentTimeMillis();
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012582 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_SHUTDOWN, mHistoryCur);
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080012583 mHistoryCur.currentTime = 0;
12584 }
12585 }
12586
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012587 private void scheduleSyncExternalStatsLocked(String reason, int updateFlags) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012588 if (mExternalSync != null) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012589 mExternalSync.scheduleSync(reason, updateFlags);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070012590 }
12591 }
12592
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012593 // This should probably be exposed in the API, though it's not critical
Bookatz1a1b0462018-01-12 11:47:03 -080012594 public static final int BATTERY_PLUGGED_NONE = OsProtoEnums.BATTERY_PLUGGED_NONE; // = 0
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012595
Andreas Gampe3f24e692018-02-05 13:24:28 -080012596 @GuardedBy("this")
Bookatz8c6571b2017-10-24 15:04:41 -070012597 public void setBatteryStateLocked(final int status, final int health, final int plugType,
12598 final int level, /* not final */ int temp, final int volt, final int chargeUAh,
12599 final int chargeFullUAh) {
Adam Lesinski29ddfe52017-03-29 19:29:00 -070012600 // Temperature is encoded without the signed bit, so clamp any negative temperatures to 0.
12601 temp = Math.max(0, temp);
12602
Bookatz8c6571b2017-10-24 15:04:41 -070012603 reportChangesToStatsLog(mHaveBatteryLevel ? mHistoryCur : null,
Tej Singh40298312018-02-16 00:15:09 -080012604 status, plugType, level);
Bookatz8c6571b2017-10-24 15:04:41 -070012605
Sudheer Shankac57729a2018-02-09 15:44:42 -080012606 final boolean onBattery = isOnBattery(plugType, status);
Joe Onoratoabded112016-02-08 16:49:39 -080012607 final long uptime = mClocks.uptimeMillis();
12608 final long elapsedRealtime = mClocks.elapsedRealtime();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012609 if (!mHaveBatteryLevel) {
12610 mHaveBatteryLevel = true;
12611 // We start out assuming that the device is plugged in (not
12612 // on battery). If our first report is now that we are indeed
12613 // plugged in, then twiddle our state to correctly reflect that
12614 // since we won't be going through the full setOnBattery().
12615 if (onBattery == mOnBattery) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012616 if (onBattery) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012617 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012618 } else {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012619 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012620 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012621 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012622 // Always start out assuming charging, that will be updated later.
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012623 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012624 mHistoryCur.batteryStatus = (byte)status;
12625 mHistoryCur.batteryLevel = (byte)level;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012626 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012627 mMaxChargeStepLevel = mMinDischargeStepLevel =
12628 mLastChargeStepLevel = mLastDischargeStepLevel = level;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012629 mLastChargingStateLevel = level;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012630 } else if (mCurrentBatteryLevel != level || mOnBattery != onBattery) {
12631 recordDailyStatsIfNeededLocked(level >= 100 && onBattery);
12632 }
12633 int oldStatus = mHistoryCur.batteryStatus;
12634 if (onBattery) {
12635 mDischargeCurrentLevel = level;
12636 if (!mRecordingHistory) {
12637 mRecordingHistory = true;
12638 startRecordingHistory(elapsedRealtime, uptime, true);
12639 }
Todd Poynor1acf06a2017-12-07 19:19:35 -080012640 } else if (level < 96 &&
12641 status != BatteryManager.BATTERY_STATUS_UNKNOWN) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012642 if (!mRecordingHistory) {
12643 mRecordingHistory = true;
12644 startRecordingHistory(elapsedRealtime, uptime, true);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012645 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070012646 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012647 mCurrentBatteryLevel = level;
12648 if (mDischargePlugLevel < 0) {
12649 mDischargePlugLevel = level;
Marco Nelissend8593312009-04-30 14:45:06 -070012650 }
Adam Lesinski926969b2016-04-28 17:31:12 -070012651
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012652 if (onBattery != mOnBattery) {
12653 mHistoryCur.batteryLevel = (byte)level;
12654 mHistoryCur.batteryStatus = (byte)status;
12655 mHistoryCur.batteryHealth = (byte)health;
12656 mHistoryCur.batteryPlugType = (byte)plugType;
12657 mHistoryCur.batteryTemperature = (short)temp;
12658 mHistoryCur.batteryVoltage = (char)volt;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012659 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
12660 // Only record discharges
12661 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
12662 mDischargeCounter.addCountLocked(chargeDiff);
12663 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070012664 if (isScreenDoze(mScreenState)) {
12665 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
12666 }
Mike Ma15313c92017-11-15 17:58:21 -080012667 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
12668 mDischargeLightDozeCounter.addCountLocked(chargeDiff);
12669 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
12670 mDischargeDeepDozeCounter.addCountLocked(chargeDiff);
12671 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012672 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012673 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012674 setOnBatteryLocked(elapsedRealtime, uptime, onBattery, oldStatus, level, chargeUAh);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012675 } else {
12676 boolean changed = false;
12677 if (mHistoryCur.batteryLevel != level) {
12678 mHistoryCur.batteryLevel = (byte)level;
12679 changed = true;
Marco Nelissend8593312009-04-30 14:45:06 -070012680
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012681 // TODO(adamlesinski): Schedule the creation of a HistoryStepDetails record
12682 // which will pull external stats.
Sudheer Shanka0719c6a2018-04-24 11:12:11 -070012683 mExternalSync.scheduleSyncDueToBatteryLevelChange(
12684 mConstants.BATTERY_LEVEL_COLLECTION_DELAY_MS);
Evan Millarc64edde2009-04-18 12:26:32 -070012685 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012686 if (mHistoryCur.batteryStatus != status) {
12687 mHistoryCur.batteryStatus = (byte)status;
12688 changed = true;
12689 }
12690 if (mHistoryCur.batteryHealth != health) {
12691 mHistoryCur.batteryHealth = (byte)health;
12692 changed = true;
12693 }
12694 if (mHistoryCur.batteryPlugType != plugType) {
12695 mHistoryCur.batteryPlugType = (byte)plugType;
12696 changed = true;
12697 }
12698 if (temp >= (mHistoryCur.batteryTemperature+10)
12699 || temp <= (mHistoryCur.batteryTemperature-10)) {
12700 mHistoryCur.batteryTemperature = (short)temp;
12701 changed = true;
12702 }
12703 if (volt > (mHistoryCur.batteryVoltage+20)
12704 || volt < (mHistoryCur.batteryVoltage-20)) {
12705 mHistoryCur.batteryVoltage = (char)volt;
12706 changed = true;
12707 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012708 if (chargeUAh >= (mHistoryCur.batteryChargeUAh+10)
12709 || chargeUAh <= (mHistoryCur.batteryChargeUAh-10)) {
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012710 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
12711 // Only record discharges
12712 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
12713 mDischargeCounter.addCountLocked(chargeDiff);
12714 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070012715 if (isScreenDoze(mScreenState)) {
12716 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
12717 }
Mike Ma15313c92017-11-15 17:58:21 -080012718 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
12719 mDischargeLightDozeCounter.addCountLocked(chargeDiff);
12720 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
12721 mDischargeDeepDozeCounter.addCountLocked(chargeDiff);
12722 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012723 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012724 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski926969b2016-04-28 17:31:12 -070012725 changed = true;
12726 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012727 long modeBits = (((long)mInitStepMode) << STEP_LEVEL_INITIAL_MODE_SHIFT)
12728 | (((long)mModStepMode) << STEP_LEVEL_MODIFIED_MODE_SHIFT)
12729 | (((long)(level&0xff)) << STEP_LEVEL_LEVEL_SHIFT);
12730 if (onBattery) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012731 changed |= setChargingLocked(false);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012732 if (mLastDischargeStepLevel != level && mMinDischargeStepLevel > level) {
12733 mDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
12734 modeBits, elapsedRealtime);
12735 mDailyDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
12736 modeBits, elapsedRealtime);
12737 mLastDischargeStepLevel = level;
12738 mMinDischargeStepLevel = level;
12739 mInitStepMode = mCurStepMode;
12740 mModStepMode = 0;
12741 }
12742 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012743 if (level >= 90) {
12744 // If the battery level is at least 90%, always consider the device to be
12745 // charging even if it happens to go down a level.
12746 changed |= setChargingLocked(true);
12747 mLastChargeStepLevel = level;
12748 } if (!mCharging) {
12749 if (mLastChargeStepLevel < level) {
12750 // We have not reporting that we are charging, but the level has now
12751 // gone up, so consider the state to be charging.
12752 changed |= setChargingLocked(true);
12753 mLastChargeStepLevel = level;
12754 }
12755 } else {
12756 if (mLastChargeStepLevel > level) {
12757 // We had reported that the device was charging, but here we are with
12758 // power connected and the level going down. Looks like the current
12759 // power supplied isn't enough, so consider the device to now be
12760 // discharging.
12761 changed |= setChargingLocked(false);
12762 mLastChargeStepLevel = level;
12763 }
12764 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012765 if (mLastChargeStepLevel != level && mMaxChargeStepLevel < level) {
12766 mChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
12767 modeBits, elapsedRealtime);
12768 mDailyChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
12769 modeBits, elapsedRealtime);
12770 mLastChargeStepLevel = level;
12771 mMaxChargeStepLevel = level;
12772 mInitStepMode = mCurStepMode;
12773 mModStepMode = 0;
Evan Millarc64edde2009-04-18 12:26:32 -070012774 }
12775 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012776 if (changed) {
12777 addHistoryRecordLocked(elapsedRealtime, uptime);
12778 }
Evan Millarc64edde2009-04-18 12:26:32 -070012779 }
Todd Poynor1acf06a2017-12-07 19:19:35 -080012780 if (!onBattery &&
12781 (status == BatteryManager.BATTERY_STATUS_FULL ||
12782 status == BatteryManager.BATTERY_STATUS_UNKNOWN)) {
12783 // We don't record history while we are plugged in and fully charged
12784 // (or when battery is not present). The next time we are
12785 // unplugged, history will be cleared.
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012786 mRecordingHistory = DEBUG;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080012787 }
Adam Lesinski041d9172016-12-12 12:03:56 -080012788
Jocelyn Dangc627d102017-04-14 13:15:14 -070012789 if (mMinLearnedBatteryCapacity == -1) {
12790 mMinLearnedBatteryCapacity = chargeFullUAh;
12791 } else {
12792 Math.min(mMinLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski041d9172016-12-12 12:03:56 -080012793 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070012794 mMaxLearnedBatteryCapacity = Math.max(mMaxLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski33dac552015-03-09 15:24:48 -070012795 }
12796
Sudheer Shankac57729a2018-02-09 15:44:42 -080012797 public static boolean isOnBattery(int plugType, int status) {
12798 return plugType == BATTERY_PLUGGED_NONE && status != BatteryManager.BATTERY_STATUS_UNKNOWN;
12799 }
12800
Bookatz8c6571b2017-10-24 15:04:41 -070012801 // Inform StatsLog of setBatteryState changes.
12802 // If this is the first reporting, pass in recentPast == null.
12803 private void reportChangesToStatsLog(HistoryItem recentPast,
Tej Singh40298312018-02-16 00:15:09 -080012804 final int status, final int plugType, final int level) {
Bookatz8c6571b2017-10-24 15:04:41 -070012805
12806 if (recentPast == null || recentPast.batteryStatus != status) {
12807 StatsLog.write(StatsLog.CHARGING_STATE_CHANGED, status);
12808 }
12809 if (recentPast == null || recentPast.batteryPlugType != plugType) {
12810 StatsLog.write(StatsLog.PLUGGED_STATE_CHANGED, plugType);
12811 }
12812 if (recentPast == null || recentPast.batteryLevel != level) {
12813 StatsLog.write(StatsLog.BATTERY_LEVEL_CHANGED, level);
12814 }
Bookatz8c6571b2017-10-24 15:04:41 -070012815 }
12816
Mathew Inwoodc185f082018-08-20 14:28:54 +010012817 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012818 public long getAwakeTimeBattery() {
12819 return computeBatteryUptime(getBatteryUptimeLocked(), STATS_CURRENT);
12820 }
12821
Mathew Inwoodc185f082018-08-20 14:28:54 +010012822 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012823 public long getAwakeTimePlugged() {
Joe Onoratoabded112016-02-08 16:49:39 -080012824 return (mClocks.uptimeMillis() * 1000) - getAwakeTimeBattery();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012825 }
12826
12827 @Override
12828 public long computeUptime(long curTime, int which) {
12829 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012830 case STATS_SINCE_CHARGED: return mUptime + (curTime-mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012831 case STATS_CURRENT: return (curTime-mUptimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070012832 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getUptimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012833 }
12834 return 0;
12835 }
12836
12837 @Override
12838 public long computeRealtime(long curTime, int which) {
12839 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012840 case STATS_SINCE_CHARGED: return mRealtime + (curTime-mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012841 case STATS_CURRENT: return (curTime-mRealtimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070012842 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getRealtimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012843 }
12844 return 0;
12845 }
12846
12847 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +010012848 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012849 public long computeBatteryUptime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012850 return mOnBatteryTimeBase.computeUptime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012851 }
12852
12853 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +010012854 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012855 public long computeBatteryRealtime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012856 return mOnBatteryTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012857 }
12858
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012859 @Override
12860 public long computeBatteryScreenOffUptime(long curTime, int which) {
12861 return mOnBatteryScreenOffTimeBase.computeUptime(curTime, which);
12862 }
12863
12864 @Override
12865 public long computeBatteryScreenOffRealtime(long curTime, int which) {
12866 return mOnBatteryScreenOffTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012867 }
12868
Dianne Hackborn260c5022014-04-29 11:23:16 -070012869 private long computeTimePerLevel(long[] steps, int numSteps) {
12870 // For now we'll do a simple average across all steps.
12871 if (numSteps <= 0) {
12872 return -1;
12873 }
12874 long total = 0;
12875 for (int i=0; i<numSteps; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012876 total += steps[i] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012877 }
12878 return total / numSteps;
12879 /*
12880 long[] buckets = new long[numSteps];
12881 int numBuckets = 0;
12882 int numToAverage = 4;
12883 int i = 0;
12884 while (i < numSteps) {
12885 long totalTime = 0;
12886 int num = 0;
12887 for (int j=0; j<numToAverage && (i+j)<numSteps; j++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012888 totalTime += steps[i+j] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012889 num++;
12890 }
12891 buckets[numBuckets] = totalTime / num;
12892 numBuckets++;
12893 numToAverage *= 2;
12894 i += num;
12895 }
12896 if (numBuckets < 1) {
12897 return -1;
12898 }
12899 long averageTime = buckets[numBuckets-1];
12900 for (i=numBuckets-2; i>=0; i--) {
12901 averageTime = (averageTime + buckets[i]) / 2;
12902 }
12903 return averageTime;
12904 */
12905 }
12906
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012907 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +010012908 @UnsupportedAppUsage
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012909 public long computeBatteryTimeRemaining(long curTime) {
12910 if (!mOnBattery) {
12911 return -1;
12912 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070012913 /* Simple implementation just looks at the average discharge per level across the
12914 entire sample period.
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012915 int discharge = (getLowDischargeAmountSinceCharge()+getHighDischargeAmountSinceCharge())/2;
12916 if (discharge < 2) {
12917 return -1;
12918 }
12919 long duration = computeBatteryRealtime(curTime, STATS_SINCE_CHARGED);
12920 if (duration < 1000*1000) {
12921 return -1;
12922 }
12923 long usPerLevel = duration/discharge;
12924 return usPerLevel * mCurrentBatteryLevel;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012925 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012926 if (mDischargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012927 return -1;
12928 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012929 long msPerLevel = mDischargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012930 if (msPerLevel <= 0) {
12931 return -1;
12932 }
12933 return (msPerLevel * mCurrentBatteryLevel) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012934 }
12935
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012936 @Override
12937 public LevelStepTracker getDischargeLevelStepTracker() {
12938 return mDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012939 }
12940
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012941 @Override
12942 public LevelStepTracker getDailyDischargeLevelStepTracker() {
12943 return mDailyDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012944 }
12945
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012946 @Override
12947 public long computeChargeTimeRemaining(long curTime) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012948 if (mOnBattery) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012949 // Not yet working.
12950 return -1;
12951 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070012952 /* Broken
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012953 int curLevel = mCurrentBatteryLevel;
12954 int plugLevel = mDischargePlugLevel;
12955 if (plugLevel < 0 || curLevel < (plugLevel+1)) {
12956 return -1;
12957 }
12958 long duration = computeBatteryRealtime(curTime, STATS_SINCE_UNPLUGGED);
12959 if (duration < 1000*1000) {
12960 return -1;
12961 }
12962 long usPerLevel = duration/(curLevel-plugLevel);
12963 return usPerLevel * (100-curLevel);
Dianne Hackborn260c5022014-04-29 11:23:16 -070012964 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012965 if (mChargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012966 return -1;
12967 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012968 long msPerLevel = mChargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012969 if (msPerLevel <= 0) {
12970 return -1;
12971 }
12972 return (msPerLevel * (100-mCurrentBatteryLevel)) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012973 }
12974
Siddharth Raya1fd0572017-11-13 14:20:47 -080012975 /*@hide */
12976 public CellularBatteryStats getCellularBatteryStats() {
12977 CellularBatteryStats s = new CellularBatteryStats();
12978 final int which = STATS_SINCE_CHARGED;
12979 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12980 final ControllerActivityCounter counter = getModemControllerActivity();
Siddharth Rayed754702018-02-15 12:44:37 -080012981 final long sleepTimeMs = counter.getSleepTimeCounter().getCountLocked(which);
Siddharth Raya1fd0572017-11-13 14:20:47 -080012982 final long idleTimeMs = counter.getIdleTimeCounter().getCountLocked(which);
12983 final long rxTimeMs = counter.getRxTimeCounter().getCountLocked(which);
12984 final long energyConsumedMaMs = counter.getPowerCounter().getCountLocked(which);
12985 long[] timeInRatMs = new long[BatteryStats.NUM_DATA_CONNECTION_TYPES];
12986 for (int i = 0; i < timeInRatMs.length; i++) {
12987 timeInRatMs[i] = getPhoneDataConnectionTime(i, rawRealTime, which) / 1000;
12988 }
12989 long[] timeInRxSignalStrengthLevelMs = new long[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
12990 for (int i = 0; i < timeInRxSignalStrengthLevelMs.length; i++) {
12991 timeInRxSignalStrengthLevelMs[i]
12992 = getPhoneSignalStrengthTime(i, rawRealTime, which) / 1000;
12993 }
12994 long[] txTimeMs = new long[Math.min(ModemActivityInfo.TX_POWER_LEVELS,
12995 counter.getTxTimeCounters().length)];
12996 long totalTxTimeMs = 0;
12997 for (int i = 0; i < txTimeMs.length; i++) {
12998 txTimeMs[i] = counter.getTxTimeCounters()[i].getCountLocked(which);
12999 totalTxTimeMs += txTimeMs[i];
13000 }
Siddharth Raya1fd0572017-11-13 14:20:47 -080013001 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
13002 s.setKernelActiveTimeMs(getMobileRadioActiveTime(rawRealTime, which) / 1000);
13003 s.setNumPacketsTx(getNetworkActivityPackets(NETWORK_MOBILE_TX_DATA, which));
13004 s.setNumBytesTx(getNetworkActivityBytes(NETWORK_MOBILE_TX_DATA, which));
13005 s.setNumPacketsRx(getNetworkActivityPackets(NETWORK_MOBILE_RX_DATA, which));
13006 s.setNumBytesRx(getNetworkActivityBytes(NETWORK_MOBILE_RX_DATA, which));
13007 s.setSleepTimeMs(sleepTimeMs);
13008 s.setIdleTimeMs(idleTimeMs);
13009 s.setRxTimeMs(rxTimeMs);
13010 s.setEnergyConsumedMaMs(energyConsumedMaMs);
13011 s.setTimeInRatMs(timeInRatMs);
13012 s.setTimeInRxSignalStrengthLevelMs(timeInRxSignalStrengthLevelMs);
13013 s.setTxTimeMs(txTimeMs);
13014 return s;
13015 }
13016
Siddharth Rayb50a6842017-12-14 15:15:28 -080013017 /*@hide */
13018 public WifiBatteryStats getWifiBatteryStats() {
13019 WifiBatteryStats s = new WifiBatteryStats();
13020 final int which = STATS_SINCE_CHARGED;
13021 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
13022 final ControllerActivityCounter counter = getWifiControllerActivity();
13023 final long idleTimeMs = counter.getIdleTimeCounter().getCountLocked(which);
13024 final long scanTimeMs = counter.getScanTimeCounter().getCountLocked(which);
13025 final long rxTimeMs = counter.getRxTimeCounter().getCountLocked(which);
13026 final long txTimeMs = counter.getTxTimeCounters()[0].getCountLocked(which);
13027 final long totalControllerActivityTimeMs
13028 = computeBatteryRealtime(SystemClock.elapsedRealtime() * 1000, which) / 1000;
13029 final long sleepTimeMs
13030 = totalControllerActivityTimeMs - (idleTimeMs + rxTimeMs + txTimeMs);
13031 final long energyConsumedMaMs = counter.getPowerCounter().getCountLocked(which);
13032 long numAppScanRequest = 0;
13033 for (int i = 0; i < mUidStats.size(); i++) {
13034 numAppScanRequest += mUidStats.valueAt(i).mWifiScanTimer.getCountLocked(which);
13035 }
13036 long[] timeInStateMs = new long[NUM_WIFI_STATES];
13037 for (int i=0; i<NUM_WIFI_STATES; i++) {
13038 timeInStateMs[i] = getWifiStateTime(i, rawRealTime, which) / 1000;
13039 }
13040 long[] timeInSupplStateMs = new long[NUM_WIFI_SUPPL_STATES];
13041 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
13042 timeInSupplStateMs[i] = getWifiSupplStateTime(i, rawRealTime, which) / 1000;
13043 }
13044 long[] timeSignalStrengthTimeMs = new long[NUM_WIFI_SIGNAL_STRENGTH_BINS];
13045 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
13046 timeSignalStrengthTimeMs[i] = getWifiSignalStrengthTime(i, rawRealTime, which) / 1000;
13047 }
13048 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
13049 s.setKernelActiveTimeMs(getWifiActiveTime(rawRealTime, which) / 1000);
13050 s.setNumPacketsTx(getNetworkActivityPackets(NETWORK_WIFI_TX_DATA, which));
13051 s.setNumBytesTx(getNetworkActivityBytes(NETWORK_WIFI_TX_DATA, which));
13052 s.setNumPacketsRx(getNetworkActivityPackets(NETWORK_WIFI_RX_DATA, which));
13053 s.setNumBytesRx(getNetworkActivityBytes(NETWORK_WIFI_RX_DATA, which));
13054 s.setSleepTimeMs(sleepTimeMs);
13055 s.setIdleTimeMs(idleTimeMs);
13056 s.setRxTimeMs(rxTimeMs);
13057 s.setTxTimeMs(txTimeMs);
13058 s.setScanTimeMs(scanTimeMs);
13059 s.setEnergyConsumedMaMs(energyConsumedMaMs);
13060 s.setNumAppScanRequest(numAppScanRequest);
13061 s.setTimeInStateMs(timeInStateMs);
13062 s.setTimeInSupplicantStateMs(timeInSupplStateMs);
13063 s.setTimeInRxSignalStrengthLevelMs(timeSignalStrengthTimeMs);
13064 return s;
13065 }
13066
Siddharth Ray78ccaf52017-12-23 16:16:21 -080013067 /*@hide */
13068 public GpsBatteryStats getGpsBatteryStats() {
13069 GpsBatteryStats s = new GpsBatteryStats();
13070 final int which = STATS_SINCE_CHARGED;
13071 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
13072 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
13073 s.setEnergyConsumedMaMs(getGpsBatteryDrainMaMs());
13074 long[] time = new long[GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS];
13075 for (int i=0; i<time.length; i++) {
13076 time[i] = getGpsSignalQualityTime(i, rawRealTime, which) / 1000;
13077 }
13078 s.setTimeInGpsSignalQualityLevel(time);
13079 return s;
13080 }
13081
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013082 @Override
13083 public LevelStepTracker getChargeLevelStepTracker() {
13084 return mChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070013085 }
13086
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013087 @Override
13088 public LevelStepTracker getDailyChargeLevelStepTracker() {
13089 return mDailyChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070013090 }
13091
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013092 @Override
13093 public ArrayList<PackageChange> getDailyPackageChanges() {
13094 return mDailyPackageChanges;
13095 }
13096
Joe Onoratoe1acd632016-02-23 13:25:10 -080013097 protected long getBatteryUptimeLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080013098 return mOnBatteryTimeBase.getUptime(mClocks.uptimeMillis() * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013099 }
13100
13101 @Override
13102 public long getBatteryUptime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013103 return mOnBatteryTimeBase.getUptime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013104 }
13105
13106 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +010013107 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013108 public long getBatteryRealtime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013109 return mOnBatteryTimeBase.getRealtime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013110 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -070013111
The Android Open Source Project10592532009-03-18 17:39:46 -070013112 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +010013113 @UnsupportedAppUsage
Evan Millar633a1742009-04-02 16:36:33 -070013114 public int getDischargeStartLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070013115 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070013116 return getDischargeStartLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070013117 }
13118 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013119
Evan Millar633a1742009-04-02 16:36:33 -070013120 public int getDischargeStartLevelLocked() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013121 return mDischargeUnplugLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070013122 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013123
The Android Open Source Project10592532009-03-18 17:39:46 -070013124 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +010013125 @UnsupportedAppUsage
Evan Millar633a1742009-04-02 16:36:33 -070013126 public int getDischargeCurrentLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070013127 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070013128 return getDischargeCurrentLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070013129 }
13130 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013131
Evan Millar633a1742009-04-02 16:36:33 -070013132 public int getDischargeCurrentLevelLocked() {
Dianne Hackborne4a59512010-12-07 11:08:07 -080013133 return mDischargeCurrentLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070013134 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013135
Amith Yamasanie43530a2009-08-21 13:11:37 -070013136 @Override
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013137 public int getLowDischargeAmountSinceCharge() {
13138 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080013139 int val = mLowDischargeAmountSinceCharge;
13140 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
13141 val += mDischargeUnplugLevel-mDischargeCurrentLevel-1;
13142 }
13143 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013144 }
13145 }
13146
13147 @Override
13148 public int getHighDischargeAmountSinceCharge() {
13149 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080013150 int val = mHighDischargeAmountSinceCharge;
13151 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
13152 val += mDischargeUnplugLevel-mDischargeCurrentLevel;
13153 }
13154 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013155 }
13156 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070013157
13158 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +010013159 @UnsupportedAppUsage
Dianne Hackborn40c87252014-03-19 16:55:40 -070013160 public int getDischargeAmount(int which) {
13161 int dischargeAmount = which == STATS_SINCE_CHARGED
13162 ? getHighDischargeAmountSinceCharge()
13163 : (getDischargeStartLevel() - getDischargeCurrentLevel());
13164 if (dischargeAmount < 0) {
13165 dischargeAmount = 0;
13166 }
13167 return dischargeAmount;
13168 }
13169
Mike Mac2f518a2017-09-19 16:06:03 -070013170 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +010013171 @UnsupportedAppUsage
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013172 public int getDischargeAmountScreenOn() {
13173 synchronized(this) {
13174 int val = mDischargeAmountScreenOn;
Mike Mac2f518a2017-09-19 16:06:03 -070013175 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013176 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
13177 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
13178 }
13179 return val;
13180 }
13181 }
13182
Mike Mac2f518a2017-09-19 16:06:03 -070013183 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013184 public int getDischargeAmountScreenOnSinceCharge() {
13185 synchronized(this) {
13186 int val = mDischargeAmountScreenOnSinceCharge;
Mike Mac2f518a2017-09-19 16:06:03 -070013187 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013188 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
13189 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
13190 }
13191 return val;
13192 }
13193 }
13194
Mike Mac2f518a2017-09-19 16:06:03 -070013195 @Override
Mathew Inwoodc185f082018-08-20 14:28:54 +010013196 @UnsupportedAppUsage
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013197 public int getDischargeAmountScreenOff() {
13198 synchronized(this) {
13199 int val = mDischargeAmountScreenOff;
Mike Mac2f518a2017-09-19 16:06:03 -070013200 if (mOnBattery && isScreenOff(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013201 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
13202 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
13203 }
Mike Mac2f518a2017-09-19 16:06:03 -070013204 // For backward compatibility, doze discharge is counted into screen off.
13205 return val + getDischargeAmountScreenDoze();
13206 }
13207 }
13208
13209 @Override
13210 public int getDischargeAmountScreenOffSinceCharge() {
13211 synchronized(this) {
13212 int val = mDischargeAmountScreenOffSinceCharge;
13213 if (mOnBattery && isScreenOff(mScreenState)
13214 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
13215 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
13216 }
13217 // For backward compatibility, doze discharge is counted into screen off.
13218 return val + getDischargeAmountScreenDozeSinceCharge();
13219 }
13220 }
13221
13222 @Override
13223 public int getDischargeAmountScreenDoze() {
13224 synchronized(this) {
13225 int val = mDischargeAmountScreenDoze;
13226 if (mOnBattery && isScreenDoze(mScreenState)
13227 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
13228 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
13229 }
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013230 return val;
13231 }
13232 }
13233
Mike Mac2f518a2017-09-19 16:06:03 -070013234 @Override
13235 public int getDischargeAmountScreenDozeSinceCharge() {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013236 synchronized(this) {
Mike Mac2f518a2017-09-19 16:06:03 -070013237 int val = mDischargeAmountScreenDozeSinceCharge;
13238 if (mOnBattery && isScreenDoze(mScreenState)
13239 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
13240 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013241 }
13242 return val;
13243 }
13244 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013246 /**
13247 * Retrieve the statistics object for a particular uid, creating if needed.
13248 */
Mathew Inwoodc185f082018-08-20 14:28:54 +010013249 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013250 public Uid getUidStatsLocked(int uid) {
13251 Uid u = mUidStats.get(uid);
13252 if (u == null) {
Joe Onoratoabded112016-02-08 16:49:39 -080013253 u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013254 mUidStats.put(uid, u);
13255 }
13256 return u;
13257 }
13258
Sudheer Shankab2f83c12017-11-13 19:25:01 -080013259 /**
13260 * Retrieve the statistics object for a particular uid. Returns null if the object is not
13261 * available.
13262 */
13263 public Uid getAvailableUidStatsLocked(int uid) {
13264 Uid u = mUidStats.get(uid);
13265 return u;
13266 }
13267
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070013268 public void onCleanupUserLocked(int userId) {
13269 final int firstUidForUser = UserHandle.getUid(userId, 0);
13270 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
Mike Ma234d1822018-03-13 18:53:21 -070013271 mPendingRemovedUids.add(
13272 new UidToRemove(firstUidForUser, lastUidForUser, mClocks.elapsedRealtime()));
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070013273 }
13274
13275 public void onUserRemovedLocked(int userId) {
13276 final int firstUidForUser = UserHandle.getUid(userId, 0);
13277 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
13278 mUidStats.put(firstUidForUser, null);
13279 mUidStats.put(lastUidForUser, null);
13280 final int firstIndex = mUidStats.indexOfKey(firstUidForUser);
13281 final int lastIndex = mUidStats.indexOfKey(lastUidForUser);
13282 mUidStats.removeAtRange(firstIndex, lastIndex - firstIndex + 1);
13283 }
13284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013285 /**
13286 * Remove the statistics object for a particular uid.
13287 */
Mathew Inwoodc185f082018-08-20 14:28:54 +010013288 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013289 public void removeUidStatsLocked(int uid) {
13290 mUidStats.remove(uid);
Mike Ma234d1822018-03-13 18:53:21 -070013291 mPendingRemovedUids.add(new UidToRemove(uid, mClocks.elapsedRealtime()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013292 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -070013293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013294 /**
13295 * Retrieve the statistics object for a particular process, creating
13296 * if needed.
13297 */
Mathew Inwoodc185f082018-08-20 14:28:54 +010013298 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013299 public Uid.Proc getProcessStatsLocked(int uid, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013300 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013301 Uid u = getUidStatsLocked(uid);
13302 return u.getProcessStatsLocked(name);
13303 }
13304
13305 /**
13306 * Retrieve the statistics object for a particular process, creating
13307 * if needed.
13308 */
Mathew Inwoodc185f082018-08-20 14:28:54 +010013309 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013310 public Uid.Pkg getPackageStatsLocked(int uid, String pkg) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013311 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013312 Uid u = getUidStatsLocked(uid);
13313 return u.getPackageStatsLocked(pkg);
13314 }
13315
13316 /**
13317 * Retrieve the statistics object for a particular service, creating
13318 * if needed.
13319 */
Mathew Inwoodc185f082018-08-20 14:28:54 +010013320 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013321 public Uid.Pkg.Serv getServiceStatsLocked(int uid, String pkg, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013322 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013323 Uid u = getUidStatsLocked(uid);
13324 return u.getServiceStatsLocked(pkg, name);
13325 }
13326
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013327 public void shutdownLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080013328 recordShutdownLocked(mClocks.elapsedRealtime(), mClocks.uptimeMillis());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013329 writeSyncLocked();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013330 mShuttingDown = true;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013331 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013332
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013333 public boolean trackPerProcStateCpuTimes() {
13334 return mConstants.TRACK_CPU_TIMES_BY_PROC_STATE && mPerProcStateCpuTimesAvailable;
13335 }
13336
13337 public void systemServicesReady(Context context) {
13338 mConstants.startObserving(context.getContentResolver());
Mike Mafbc01fc2018-04-02 10:28:28 -070013339 registerUsbStateReceiver(context);
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013340 }
13341
13342 @VisibleForTesting
13343 public final class Constants extends ContentObserver {
13344 public static final String KEY_TRACK_CPU_TIMES_BY_PROC_STATE
13345 = "track_cpu_times_by_proc_state";
Mike Mafae87da2018-01-19 20:07:20 -080013346 public static final String KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME
13347 = "track_cpu_active_cluster_time";
Sudheer Shankac20379e2018-02-15 00:06:21 -080013348 public static final String KEY_PROC_STATE_CPU_TIMES_READ_DELAY_MS
13349 = "proc_state_cpu_times_read_delay_ms";
Mike Ma2ab01442018-02-13 14:22:47 -080013350 public static final String KEY_KERNEL_UID_READERS_THROTTLE_TIME
13351 = "kernel_uid_readers_throttle_time";
Mike Ma234d1822018-03-13 18:53:21 -070013352 public static final String KEY_UID_REMOVE_DELAY_MS
13353 = "uid_remove_delay_ms";
Sudheer Shankae56013a2018-04-23 11:22:15 -070013354 public static final String KEY_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS
13355 = "external_stats_collection_rate_limit_ms";
Sudheer Shanka0719c6a2018-04-24 11:12:11 -070013356 public static final String KEY_BATTERY_LEVEL_COLLECTION_DELAY_MS
13357 = "battery_level_collection_delay_ms";
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013358
13359 private static final boolean DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE = true;
Mike Mafae87da2018-01-19 20:07:20 -080013360 private static final boolean DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME = true;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013361 private static final long DEFAULT_PROC_STATE_CPU_TIMES_READ_DELAY_MS = 5_000;
Mike Ma2ab01442018-02-13 14:22:47 -080013362 private static final long DEFAULT_KERNEL_UID_READERS_THROTTLE_TIME = 10_000;
Mike Ma234d1822018-03-13 18:53:21 -070013363 private static final long DEFAULT_UID_REMOVE_DELAY_MS = 5L * 60L * 1000L;
Sudheer Shankae56013a2018-04-23 11:22:15 -070013364 private static final long DEFAULT_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS = 600_000;
Sudheer Shanka0719c6a2018-04-24 11:12:11 -070013365 private static final long DEFAULT_BATTERY_LEVEL_COLLECTION_DELAY_MS = 300_000;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013366
13367 public boolean TRACK_CPU_TIMES_BY_PROC_STATE = DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE;
Mike Mafae87da2018-01-19 20:07:20 -080013368 public boolean TRACK_CPU_ACTIVE_CLUSTER_TIME = DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013369 public long PROC_STATE_CPU_TIMES_READ_DELAY_MS = DEFAULT_PROC_STATE_CPU_TIMES_READ_DELAY_MS;
Mike Ma2ab01442018-02-13 14:22:47 -080013370 public long KERNEL_UID_READERS_THROTTLE_TIME = DEFAULT_KERNEL_UID_READERS_THROTTLE_TIME;
Mike Ma234d1822018-03-13 18:53:21 -070013371 public long UID_REMOVE_DELAY_MS = DEFAULT_UID_REMOVE_DELAY_MS;
Sudheer Shankae56013a2018-04-23 11:22:15 -070013372 public long EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS
13373 = DEFAULT_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS;
Sudheer Shanka0719c6a2018-04-24 11:12:11 -070013374 public long BATTERY_LEVEL_COLLECTION_DELAY_MS
13375 = DEFAULT_BATTERY_LEVEL_COLLECTION_DELAY_MS;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013376
13377 private ContentResolver mResolver;
13378 private final KeyValueListParser mParser = new KeyValueListParser(',');
13379
13380 public Constants(Handler handler) {
13381 super(handler);
13382 }
13383
13384 public void startObserving(ContentResolver resolver) {
13385 mResolver = resolver;
13386 mResolver.registerContentObserver(
13387 Settings.Global.getUriFor(Settings.Global.BATTERY_STATS_CONSTANTS),
13388 false /* notifyForDescendants */, this);
13389 updateConstants();
13390 }
13391
13392 @Override
13393 public void onChange(boolean selfChange, Uri uri) {
13394 updateConstants();
13395 }
13396
13397 private void updateConstants() {
13398 synchronized (BatteryStatsImpl.this) {
13399 try {
13400 mParser.setString(Settings.Global.getString(mResolver,
13401 Settings.Global.BATTERY_STATS_CONSTANTS));
13402 } catch (IllegalArgumentException e) {
13403 // Failed to parse the settings string, log this and move on
13404 // with defaults.
13405 Slog.e(TAG, "Bad batterystats settings", e);
13406 }
13407
13408 updateTrackCpuTimesByProcStateLocked(TRACK_CPU_TIMES_BY_PROC_STATE,
13409 mParser.getBoolean(KEY_TRACK_CPU_TIMES_BY_PROC_STATE,
13410 DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE));
Mike Mafae87da2018-01-19 20:07:20 -080013411 TRACK_CPU_ACTIVE_CLUSTER_TIME = mParser.getBoolean(
13412 KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME, DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME);
Sudheer Shankac20379e2018-02-15 00:06:21 -080013413 updateProcStateCpuTimesReadDelayMs(PROC_STATE_CPU_TIMES_READ_DELAY_MS,
13414 mParser.getLong(KEY_PROC_STATE_CPU_TIMES_READ_DELAY_MS,
Mike Ma2ab01442018-02-13 14:22:47 -080013415 DEFAULT_PROC_STATE_CPU_TIMES_READ_DELAY_MS));
13416 updateKernelUidReadersThrottleTime(KERNEL_UID_READERS_THROTTLE_TIME,
13417 mParser.getLong(KEY_KERNEL_UID_READERS_THROTTLE_TIME,
13418 DEFAULT_KERNEL_UID_READERS_THROTTLE_TIME));
Mike Ma234d1822018-03-13 18:53:21 -070013419 updateUidRemoveDelay(
13420 mParser.getLong(KEY_UID_REMOVE_DELAY_MS, DEFAULT_UID_REMOVE_DELAY_MS));
Sudheer Shankae56013a2018-04-23 11:22:15 -070013421 EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS = mParser.getLong(
13422 KEY_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS,
13423 DEFAULT_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS);
Sudheer Shanka0719c6a2018-04-24 11:12:11 -070013424 BATTERY_LEVEL_COLLECTION_DELAY_MS = mParser.getLong(
13425 KEY_BATTERY_LEVEL_COLLECTION_DELAY_MS,
13426 DEFAULT_BATTERY_LEVEL_COLLECTION_DELAY_MS);
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013427 }
13428 }
13429
13430 private void updateTrackCpuTimesByProcStateLocked(boolean wasEnabled, boolean isEnabled) {
13431 TRACK_CPU_TIMES_BY_PROC_STATE = isEnabled;
13432 if (isEnabled && !wasEnabled) {
13433 mKernelSingleUidTimeReader.markDataAsStale(true);
13434 mExternalSync.scheduleCpuSyncDueToSettingChange();
Sudheer Shankac20379e2018-02-15 00:06:21 -080013435
Mike Ma234d1822018-03-13 18:53:21 -070013436 mNumSingleUidCpuTimeReads = 0;
13437 mNumBatchedSingleUidCpuTimeReads = 0;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013438 mCpuTimeReadsTrackingStartTime = mClocks.uptimeMillis();
13439 }
13440 }
13441
13442 private void updateProcStateCpuTimesReadDelayMs(long oldDelayMillis, long newDelayMillis) {
13443 PROC_STATE_CPU_TIMES_READ_DELAY_MS = newDelayMillis;
13444 if (oldDelayMillis != newDelayMillis) {
Mike Ma234d1822018-03-13 18:53:21 -070013445 mNumSingleUidCpuTimeReads = 0;
13446 mNumBatchedSingleUidCpuTimeReads = 0;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013447 mCpuTimeReadsTrackingStartTime = mClocks.uptimeMillis();
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013448 }
13449 }
13450
Mike Ma2ab01442018-02-13 14:22:47 -080013451 private void updateKernelUidReadersThrottleTime(long oldTimeMs, long newTimeMs) {
13452 KERNEL_UID_READERS_THROTTLE_TIME = newTimeMs;
13453 if (oldTimeMs != newTimeMs) {
Mike Ma69d8b3e2018-02-23 14:51:26 -080013454 mKernelUidCpuTimeReader.setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
Mike Ma2ab01442018-02-13 14:22:47 -080013455 mKernelUidCpuFreqTimeReader.setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
13456 mKernelUidCpuActiveTimeReader.setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
13457 mKernelUidCpuClusterTimeReader
13458 .setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
13459 }
13460 }
13461
Mike Ma234d1822018-03-13 18:53:21 -070013462 private void updateUidRemoveDelay(long newTimeMs) {
13463 UID_REMOVE_DELAY_MS = newTimeMs;
13464 clearPendingRemovedUids();
13465 }
13466
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013467 public void dumpLocked(PrintWriter pw) {
13468 pw.print(KEY_TRACK_CPU_TIMES_BY_PROC_STATE); pw.print("=");
13469 pw.println(TRACK_CPU_TIMES_BY_PROC_STATE);
Mike Mafae87da2018-01-19 20:07:20 -080013470 pw.print(KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME); pw.print("=");
13471 pw.println(TRACK_CPU_ACTIVE_CLUSTER_TIME);
Sudheer Shankac20379e2018-02-15 00:06:21 -080013472 pw.print(KEY_PROC_STATE_CPU_TIMES_READ_DELAY_MS); pw.print("=");
13473 pw.println(PROC_STATE_CPU_TIMES_READ_DELAY_MS);
Mike Ma2ab01442018-02-13 14:22:47 -080013474 pw.print(KEY_KERNEL_UID_READERS_THROTTLE_TIME); pw.print("=");
13475 pw.println(KERNEL_UID_READERS_THROTTLE_TIME);
Sudheer Shankae56013a2018-04-23 11:22:15 -070013476 pw.print(KEY_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS); pw.print("=");
13477 pw.println(EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS);
Sudheer Shanka0719c6a2018-04-24 11:12:11 -070013478 pw.print(KEY_BATTERY_LEVEL_COLLECTION_DELAY_MS); pw.print("=");
13479 pw.println(BATTERY_LEVEL_COLLECTION_DELAY_MS);
Sudheer Shankae56013a2018-04-23 11:22:15 -070013480 }
13481 }
13482
13483 public long getExternalStatsCollectionRateLimitMs() {
13484 synchronized (this) {
13485 return mConstants.EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013486 }
13487 }
13488
Andreas Gampe3f24e692018-02-05 13:24:28 -080013489 @GuardedBy("this")
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013490 public void dumpConstantsLocked(PrintWriter pw) {
13491 mConstants.dumpLocked(pw);
13492 }
13493
Mike Ma234d1822018-03-13 18:53:21 -070013494 @GuardedBy("this")
13495 public void dumpCpuStatsLocked(PrintWriter pw) {
13496 int size = mUidStats.size();
13497 pw.println("Per UID CPU user & system time in ms:");
13498 for (int i = 0; i < size; i++) {
13499 int u = mUidStats.keyAt(i);
13500 Uid uid = mUidStats.get(u);
13501 pw.print(" "); pw.print(u); pw.print(": ");
13502 pw.print(uid.getUserCpuTimeUs(STATS_SINCE_CHARGED) / 1000); pw.print(" ");
13503 pw.println(uid.getSystemCpuTimeUs(STATS_SINCE_CHARGED) / 1000);
13504 }
13505 pw.println("Per UID CPU active time in ms:");
13506 for (int i = 0; i < size; i++) {
13507 int u = mUidStats.keyAt(i);
13508 Uid uid = mUidStats.get(u);
13509 if (uid.getCpuActiveTime() > 0) {
13510 pw.print(" "); pw.print(u); pw.print(": "); pw.println(uid.getCpuActiveTime());
13511 }
13512 }
13513 pw.println("Per UID CPU cluster time in ms:");
13514 for (int i = 0; i < size; i++) {
13515 int u = mUidStats.keyAt(i);
13516 long[] times = mUidStats.get(u).getCpuClusterTimes();
13517 if (times != null) {
13518 pw.print(" "); pw.print(u); pw.print(": "); pw.println(Arrays.toString(times));
13519 }
13520 }
13521 pw.println("Per UID CPU frequency time in ms:");
13522 for (int i = 0; i < size; i++) {
13523 int u = mUidStats.keyAt(i);
13524 long[] times = mUidStats.get(u).getCpuFreqTimes(STATS_SINCE_CHARGED);
13525 if (times != null) {
13526 pw.print(" "); pw.print(u); pw.print(": "); pw.println(Arrays.toString(times));
13527 }
13528 }
13529 }
13530
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013531 Parcel mPendingWrite = null;
13532 final ReentrantLock mWriteLock = new ReentrantLock();
13533
13534 public void writeAsyncLocked() {
13535 writeLocked(false);
13536 }
13537
13538 public void writeSyncLocked() {
13539 writeLocked(true);
13540 }
13541
13542 void writeLocked(boolean sync) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013543 if (mFile == null) {
13544 Slog.w("BatteryStats", "writeLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013545 return;
13546 }
13547
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013548 if (mShuttingDown) {
13549 return;
13550 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013551
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013552 Parcel out = Parcel.obtain();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013553 writeSummaryToParcel(out, true);
Joe Onoratoabded112016-02-08 16:49:39 -080013554 mLastWriteTime = mClocks.elapsedRealtime();
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013555
13556 if (mPendingWrite != null) {
13557 mPendingWrite.recycle();
13558 }
13559 mPendingWrite = out;
13560
13561 if (sync) {
13562 commitPendingDataToDisk();
13563 } else {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013564 BackgroundThread.getHandler().post(new Runnable() {
13565 @Override public void run() {
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013566 commitPendingDataToDisk();
13567 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013568 });
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013569 }
13570 }
13571
Mathew Inwoodc185f082018-08-20 14:28:54 +010013572 @UnsupportedAppUsage
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013573 public void commitPendingDataToDisk() {
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070013574 final Parcel next;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013575 synchronized (this) {
13576 next = mPendingWrite;
13577 mPendingWrite = null;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070013578 if (next == null) {
13579 return;
13580 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013581 }
13582
Amith Yamasanid2450862017-02-07 15:58:24 -080013583 mWriteLock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013584 try {
Dianne Hackborne17b4452018-01-10 13:15:40 -080013585 final long startTime = SystemClock.uptimeMillis();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013586 FileOutputStream stream = new FileOutputStream(mFile.chooseForWrite());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013587 stream.write(next.marshall());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013588 stream.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070013589 FileUtils.sync(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013590 stream.close();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013591 mFile.commit();
Dianne Hackborne17b4452018-01-10 13:15:40 -080013592 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
13593 "batterystats", SystemClock.uptimeMillis() - startTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013594 } catch (IOException e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013595 Slog.w("BatteryStats", "Error writing battery statistics", e);
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013596 mFile.rollback();
13597 } finally {
13598 next.recycle();
13599 mWriteLock.unlock();
Suchi Amalapurapu8550f252009-09-29 15:20:32 -070013600 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013601 }
13602
Mathew Inwoodc185f082018-08-20 14:28:54 +010013603 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013604 public void readLocked() {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013605 if (mDailyFile != null) {
13606 readDailyStatsLocked();
13607 }
13608
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013609 if (mFile == null) {
13610 Slog.w("BatteryStats", "readLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013611 return;
13612 }
13613
13614 mUidStats.clear();
13615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013616 try {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013617 File file = mFile.chooseForRead();
13618 if (!file.exists()) {
13619 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013620 }
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013621 FileInputStream stream = new FileInputStream(file);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013622
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013623 byte[] raw = BatteryStatsHelper.readFully(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013624 Parcel in = Parcel.obtain();
13625 in.unmarshall(raw, 0, raw.length);
13626 in.setDataPosition(0);
13627 stream.close();
13628
13629 readSummaryFromParcel(in);
Dianne Hackborn00e25212014-02-19 10:49:24 -080013630 } catch(Exception e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013631 Slog.e("BatteryStats", "Error reading battery statistics", e);
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013632 resetAllStatsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013633 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013634
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013635 mEndPlatformVersion = Build.ID;
13636
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013637 if (mHistoryBuffer.dataPosition() > 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013638 mRecordingHistory = true;
Joe Onoratoabded112016-02-08 16:49:39 -080013639 final long elapsedRealtime = mClocks.elapsedRealtime();
13640 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013641 if (USE_OLD_HISTORY) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013642 addHistoryRecordLocked(elapsedRealtime, uptime, HistoryItem.CMD_START, mHistoryCur);
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013643 }
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000013644 addHistoryBufferLocked(elapsedRealtime, HistoryItem.CMD_START, mHistoryCur);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013645 startRecordingHistory(elapsedRealtime, uptime, false);
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013646 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013647
13648 recordDailyStatsIfNeededLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013649 }
13650
13651 public int describeContents() {
13652 return 0;
13653 }
13654
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013655 void readHistory(Parcel in, boolean andOldHistory) throws ParcelFormatException {
Dianne Hackbornae384452011-06-28 12:33:48 -070013656 final long historyBaseTime = in.readLong();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013657
13658 mHistoryBuffer.setDataSize(0);
13659 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013660 mHistoryTagPool.clear();
13661 mNextHistoryTagIdx = 0;
13662 mNumHistoryTagChars = 0;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013663
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013664 int numTags = in.readInt();
13665 for (int i=0; i<numTags; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080013666 int idx = in.readInt();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013667 String str = in.readString();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013668 if (str == null) {
13669 throw new ParcelFormatException("null history tag string");
13670 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013671 int uid = in.readInt();
13672 HistoryTag tag = new HistoryTag();
13673 tag.string = str;
13674 tag.uid = uid;
13675 tag.poolIdx = idx;
13676 mHistoryTagPool.put(tag, idx);
13677 if (idx >= mNextHistoryTagIdx) {
13678 mNextHistoryTagIdx = idx+1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013679 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013680 mNumHistoryTagChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013681 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013682
13683 int bufSize = in.readInt();
13684 int curPos = in.dataPosition();
13685 if (bufSize >= (MAX_MAX_HISTORY_BUFFER*3)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013686 throw new ParcelFormatException("File corrupt: history data buffer too large " +
13687 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013688 } else if ((bufSize&~3) != bufSize) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013689 throw new ParcelFormatException("File corrupt: history data buffer not aligned " +
13690 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013691 } else {
13692 if (DEBUG_HISTORY) Slog.i(TAG, "***************** READING NEW HISTORY: " + bufSize
13693 + " bytes at " + curPos);
13694 mHistoryBuffer.appendFrom(in, curPos, bufSize);
13695 in.setDataPosition(curPos + bufSize);
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013696 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013697
Dianne Hackbornae384452011-06-28 12:33:48 -070013698 if (andOldHistory) {
13699 readOldHistory(in);
13700 }
13701
13702 if (DEBUG_HISTORY) {
13703 StringBuilder sb = new StringBuilder(128);
13704 sb.append("****************** OLD mHistoryBaseTime: ");
13705 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13706 Slog.i(TAG, sb.toString());
13707 }
13708 mHistoryBaseTime = historyBaseTime;
13709 if (DEBUG_HISTORY) {
13710 StringBuilder sb = new StringBuilder(128);
13711 sb.append("****************** NEW mHistoryBaseTime: ");
13712 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13713 Slog.i(TAG, sb.toString());
13714 }
13715
13716 // We are just arbitrarily going to insert 1 minute from the sample of
13717 // the last run until samples in this run.
13718 if (mHistoryBaseTime > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -080013719 long oldnow = mClocks.elapsedRealtime();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013720 mHistoryBaseTime = mHistoryBaseTime - oldnow + 1;
Dianne Hackbornae384452011-06-28 12:33:48 -070013721 if (DEBUG_HISTORY) {
13722 StringBuilder sb = new StringBuilder(128);
13723 sb.append("****************** ADJUSTED mHistoryBaseTime: ");
13724 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13725 Slog.i(TAG, sb.toString());
13726 }
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -070013727 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013728 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013729
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013730 void readOldHistory(Parcel in) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013731 if (!USE_OLD_HISTORY) {
13732 return;
13733 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013734 mHistory = mHistoryEnd = mHistoryCache = null;
13735 long time;
Conley Owens5e3357f2011-05-02 09:59:30 -070013736 while (in.dataAvail() > 0 && (time=in.readLong()) >= 0) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013737 HistoryItem rec = new HistoryItem(time, in);
13738 addHistoryRecordLocked(rec);
13739 }
13740 }
13741
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013742 void writeHistory(Parcel out, boolean inclData, boolean andOldHistory) {
Dianne Hackbornae384452011-06-28 12:33:48 -070013743 if (DEBUG_HISTORY) {
13744 StringBuilder sb = new StringBuilder(128);
13745 sb.append("****************** WRITING mHistoryBaseTime: ");
13746 TimeUtils.formatDuration(mHistoryBaseTime, sb);
Dianne Hackborn40c87252014-03-19 16:55:40 -070013747 sb.append(" mLastHistoryElapsedRealtime: ");
13748 TimeUtils.formatDuration(mLastHistoryElapsedRealtime, sb);
Dianne Hackbornae384452011-06-28 12:33:48 -070013749 Slog.i(TAG, sb.toString());
13750 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070013751 out.writeLong(mHistoryBaseTime + mLastHistoryElapsedRealtime);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013752 if (!inclData) {
13753 out.writeInt(0);
13754 out.writeInt(0);
13755 return;
13756 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013757 out.writeInt(mHistoryTagPool.size());
13758 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
13759 HistoryTag tag = ent.getKey();
Dianne Hackborn099bc622014-01-22 13:39:16 -080013760 out.writeInt(ent.getValue());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013761 out.writeString(tag.string);
13762 out.writeInt(tag.uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -080013763 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013764 out.writeInt(mHistoryBuffer.dataSize());
13765 if (DEBUG_HISTORY) Slog.i(TAG, "***************** WRITING HISTORY: "
13766 + mHistoryBuffer.dataSize() + " bytes at " + out.dataPosition());
13767 out.appendFrom(mHistoryBuffer, 0, mHistoryBuffer.dataSize());
Dianne Hackbornae384452011-06-28 12:33:48 -070013768
13769 if (andOldHistory) {
13770 writeOldHistory(out);
13771 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013772 }
13773
13774 void writeOldHistory(Parcel out) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013775 if (!USE_OLD_HISTORY) {
13776 return;
13777 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013778 HistoryItem rec = mHistory;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013779 while (rec != null) {
13780 if (rec.time >= 0) rec.writeToParcel(out, 0);
13781 rec = rec.next;
13782 }
13783 out.writeLong(-1);
13784 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013785
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013786 public void readSummaryFromParcel(Parcel in) throws ParcelFormatException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013787 final int version = in.readInt();
13788 if (version != VERSION) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013789 Slog.w("BatteryStats", "readFromParcel: version got " + version
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013790 + ", expected " + VERSION + "; erasing old stats");
13791 return;
13792 }
13793
Dianne Hackbornae384452011-06-28 12:33:48 -070013794 readHistory(in, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013796 mStartCount = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013797 mUptime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013798 mRealtime = in.readLong();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080013799 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013800 mStartPlatformVersion = in.readString();
13801 mEndPlatformVersion = in.readString();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013802 mOnBatteryTimeBase.readSummaryFromParcel(in);
13803 mOnBatteryScreenOffTimeBase.readSummaryFromParcel(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013804 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013805 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070013806 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013807 mCurrentBatteryLevel = in.readInt();
Adam Lesinskif9b20a92016-06-17 17:30:01 -070013808 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070013809 mMinLearnedBatteryCapacity = in.readInt();
13810 mMaxLearnedBatteryCapacity = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013811 mLowDischargeAmountSinceCharge = in.readInt();
13812 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013813 mDischargeAmountScreenOnSinceCharge = in.readInt();
13814 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070013815 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013816 mDischargeStepTracker.readFromParcel(in);
13817 mChargeStepTracker.readFromParcel(in);
13818 mDailyDischargeStepTracker.readFromParcel(in);
13819 mDailyChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070013820 mDischargeCounter.readSummaryFromParcelLocked(in);
13821 mDischargeScreenOffCounter.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070013822 mDischargeScreenDozeCounter.readSummaryFromParcelLocked(in);
Mike Ma15313c92017-11-15 17:58:21 -080013823 mDischargeLightDozeCounter.readSummaryFromParcelLocked(in);
13824 mDischargeDeepDozeCounter.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013825 int NPKG = in.readInt();
13826 if (NPKG > 0) {
13827 mDailyPackageChanges = new ArrayList<>(NPKG);
13828 while (NPKG > 0) {
13829 NPKG--;
13830 PackageChange pc = new PackageChange();
13831 pc.mPackageName = in.readString();
13832 pc.mUpdate = in.readInt() != 0;
Dianne Hackborn3accca02013-09-20 09:32:11 -070013833 pc.mVersionCode = in.readLong();
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013834 mDailyPackageChanges.add(pc);
13835 }
13836 } else {
13837 mDailyPackageChanges = null;
13838 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013839 mDailyStartTime = in.readLong();
13840 mNextMinDailyDeadline = in.readLong();
13841 mNextMaxDailyDeadline = in.readLong();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013843 mStartCount++;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013844
Jeff Browne95c3cd2014-05-02 16:59:26 -070013845 mScreenState = Display.STATE_UNKNOWN;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013846 mScreenOnTimer.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070013847 mScreenDozeTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn617f8772009-03-31 15:04:46 -070013848 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
13849 mScreenBrightnessTimer[i].readSummaryFromParcelLocked(in);
13850 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070013851 mInteractive = false;
13852 mInteractiveTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013853 mPhoneOn = false;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070013854 mPowerSaveModeEnabledTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070013855 mLongestLightIdleTime = in.readLong();
13856 mLongestFullIdleTime = in.readLong();
13857 mDeviceIdleModeLightTimer.readSummaryFromParcelLocked(in);
13858 mDeviceIdleModeFullTimer.readSummaryFromParcelLocked(in);
13859 mDeviceLightIdlingTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013860 mDeviceIdlingTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013861 mPhoneOnTimer.readSummaryFromParcelLocked(in);
Wink Saville52840902011-02-18 12:40:47 -080013862 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn627bba72009-03-24 22:32:56 -070013863 mPhoneSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
13864 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070013865 mPhoneSignalScanningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013866 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
13867 mPhoneDataConnectionsTimer[i].readSummaryFromParcelLocked(in);
13868 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013869 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013870 mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
13871 mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013872 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013873 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborne13c4c02014-02-11 17:18:35 -080013874 mMobileRadioActiveTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080013875 mMobileRadioActivePerAppTimer.readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013876 mMobileRadioActiveAdjustedTime.readSummaryFromParcelLocked(in);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013877 mMobileRadioActiveUnknownTime.readSummaryFromParcelLocked(in);
13878 mMobileRadioActiveUnknownCount.readSummaryFromParcelLocked(in);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080013879 mWifiMulticastWakelockTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070013880 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
The Android Open Source Project10592532009-03-18 17:39:46 -070013881 mWifiOn = false;
13882 mWifiOnTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013883 mGlobalWifiRunning = false;
13884 mGlobalWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080013885 for (int i=0; i<NUM_WIFI_STATES; i++) {
13886 mWifiStateTimer[i].readSummaryFromParcelLocked(in);
13887 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070013888 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
13889 mWifiSupplStateTimer[i].readSummaryFromParcelLocked(in);
13890 }
13891 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
13892 mWifiSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
13893 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080013894 mWifiActiveTimer.readSummaryFromParcelLocked(in);
13895 mWifiActivity.readSummaryFromParcel(in);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080013896 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
13897 mGpsSignalQualityTimer[i].readSummaryFromParcelLocked(in);
13898 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080013899 mBluetoothActivity.readSummaryFromParcel(in);
13900 mModemActivity.readSummaryFromParcel(in);
13901 mHasWifiReporting = in.readInt() != 0;
13902 mHasBluetoothReporting = in.readInt() != 0;
13903 mHasModemReporting = in.readInt() != 0;
Adam Lesinski33dac552015-03-09 15:24:48 -070013904
Dianne Hackborn1e01d162014-12-04 17:46:42 -080013905 mNumConnectivityChange = mLoadedNumConnectivityChange = in.readInt();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013906 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -070013907 mFlashlightOnTimer.readSummaryFromParcelLocked(in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013908 mCameraOnNesting = 0;
13909 mCameraOnTimer.readSummaryFromParcelLocked(in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013910 mBluetoothScanNesting = 0;
13911 mBluetoothScanTimer.readSummaryFromParcelLocked(in);
Siddharth Rayf5e796a2018-01-22 18:18:17 -080013912 mIsCellularTxPowerHigh = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013913
Bookatz50df7112017-08-04 14:53:26 -070013914 int NRPMS = in.readInt();
13915 if (NRPMS > 10000) {
13916 throw new ParcelFormatException("File corrupt: too many rpm stats " + NRPMS);
13917 }
13918 for (int irpm = 0; irpm < NRPMS; irpm++) {
13919 if (in.readInt() != 0) {
13920 String rpmName = in.readString();
13921 getRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
13922 }
13923 }
13924 int NSORPMS = in.readInt();
13925 if (NSORPMS > 10000) {
13926 throw new ParcelFormatException("File corrupt: too many screen-off rpm stats " + NSORPMS);
13927 }
13928 for (int irpm = 0; irpm < NSORPMS; irpm++) {
13929 if (in.readInt() != 0) {
13930 String rpmName = in.readString();
13931 getScreenOffRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
13932 }
13933 }
13934
Evan Millarc64edde2009-04-18 12:26:32 -070013935 int NKW = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013936 if (NKW > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013937 throw new ParcelFormatException("File corrupt: too many kernel wake locks " + NKW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013938 }
Evan Millarc64edde2009-04-18 12:26:32 -070013939 for (int ikw = 0; ikw < NKW; ikw++) {
13940 if (in.readInt() != 0) {
13941 String kwltName = in.readString();
13942 getKernelWakelockTimerLocked(kwltName).readSummaryFromParcelLocked(in);
13943 }
13944 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070013945
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013946 int NWR = in.readInt();
13947 if (NWR > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013948 throw new ParcelFormatException("File corrupt: too many wakeup reasons " + NWR);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013949 }
13950 for (int iwr = 0; iwr < NWR; iwr++) {
13951 if (in.readInt() != 0) {
13952 String reasonName = in.readString();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070013953 getWakeupReasonTimerLocked(reasonName).readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013954 }
13955 }
13956
James Carr3a226052016-07-01 14:49:52 -070013957 int NMS = in.readInt();
13958 for (int ims = 0; ims < NMS; ims++) {
13959 if (in.readInt() != 0) {
13960 long kmstName = in.readLong();
13961 getKernelMemoryTimerLocked(kmstName).readSummaryFromParcelLocked(in);
13962 }
13963 }
13964
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013965 final int NU = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013966 if (NU > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013967 throw new ParcelFormatException("File corrupt: too many uids " + NU);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013969 for (int iu = 0; iu < NU; iu++) {
13970 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080013971 Uid u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013972 mUidStats.put(uid, u);
13973
Bookatz867c0d72017-03-07 18:23:42 -080013974 u.mOnBatteryBackgroundTimeBase.readSummaryFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -070013975 u.mOnBatteryScreenOffBackgroundTimeBase.readSummaryFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -080013976
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013977 u.mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013978 if (in.readInt() != 0) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013979 u.mWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013980 }
The Android Open Source Project10592532009-03-18 17:39:46 -070013981 u.mFullWifiLockOut = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013982 if (in.readInt() != 0) {
13983 u.mFullWifiLockTimer.readSummaryFromParcelLocked(in);
13984 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070013985 u.mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013986 if (in.readInt() != 0) {
Nick Pelly6ccaa542012-06-15 15:22:47 -070013987 u.mWifiScanTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013988 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070013989 u.mWifiBatchedScanBinStarted = Uid.NO_BATCHED_SCAN_STARTED;
13990 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
13991 if (in.readInt() != 0) {
13992 u.makeWifiBatchedScanBin(i, null);
13993 u.mWifiBatchedScanTimer[i].readSummaryFromParcelLocked(in);
13994 }
13995 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070013996 u.mWifiMulticastEnabled = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013997 if (in.readInt() != 0) {
13998 u.mWifiMulticastTimer.readSummaryFromParcelLocked(in);
13999 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014000 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014001 u.createAudioTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014002 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014003 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014004 u.createVideoTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
14005 }
14006 if (in.readInt() != 0) {
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014007 u.createFlashlightTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
14008 }
14009 if (in.readInt() != 0) {
14010 u.createCameraTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
14011 }
14012 if (in.readInt() != 0) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014013 u.createForegroundActivityTimerLocked().readSummaryFromParcelLocked(in);
14014 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014015 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070014016 u.createForegroundServiceTimerLocked().readSummaryFromParcelLocked(in);
14017 }
14018 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -070014019 u.createAggregatedPartialWakelockTimerLocked().readSummaryFromParcelLocked(in);
14020 }
14021 if (in.readInt() != 0) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014022 u.createBluetoothScanTimerLocked().readSummaryFromParcelLocked(in);
14023 }
Bookatz956f36bf2017-04-28 09:48:17 -070014024 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -070014025 u.createBluetoothUnoptimizedScanTimerLocked().readSummaryFromParcelLocked(in);
14026 }
14027 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -070014028 u.createBluetoothScanResultCounterLocked().readSummaryFromParcelLocked(in);
14029 }
Bookatzb1f04f32017-05-19 13:57:32 -070014030 if (in.readInt() != 0) {
14031 u.createBluetoothScanResultBgCounterLocked().readSummaryFromParcelLocked(in);
14032 }
Dianne Hackborna8d10942015-11-19 17:55:19 -080014033 u.mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -070014034 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
14035 if (in.readInt() != 0) {
14036 u.makeProcessState(i, null);
14037 u.mProcessStateTimer[i].readSummaryFromParcelLocked(in);
14038 }
14039 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014040 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014041 u.createVibratorOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014042 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070014043
Dianne Hackborn617f8772009-03-31 15:04:46 -070014044 if (in.readInt() != 0) {
14045 if (u.mUserActivityCounters == null) {
14046 u.initUserActivityLocked();
14047 }
14048 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
14049 u.mUserActivityCounters[i].readSummaryFromParcelLocked(in);
14050 }
14051 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014052
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014053 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014054 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014055 u.initNetworkActivityLocked();
14056 }
14057 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014058 u.mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
14059 u.mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014060 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080014061 u.mMobileRadioActiveTime.readSummaryFromParcelLocked(in);
14062 u.mMobileRadioActiveCount.readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014063 }
14064
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014065 u.mUserCpuTime.readSummaryFromParcelLocked(in);
14066 u.mSystemCpuTime.readSummaryFromParcelLocked(in);
14067
Adam Lesinski6832f392015-09-05 18:05:40 -070014068 if (in.readInt() != 0) {
14069 final int numClusters = in.readInt();
14070 if (mPowerProfile != null && mPowerProfile.getNumCpuClusters() != numClusters) {
14071 throw new ParcelFormatException("Incompatible cpu cluster arrangement");
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014072 }
Adam Lesinski6832f392015-09-05 18:05:40 -070014073
Sudheer Shankaaf857412017-07-21 00:14:24 -070014074 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -070014075 for (int cluster = 0; cluster < numClusters; cluster++) {
Adam Lesinski6832f392015-09-05 18:05:40 -070014076 if (in.readInt() != 0) {
Adam Lesinskia57a5402015-09-28 10:21:33 -070014077 final int NSB = in.readInt();
14078 if (mPowerProfile != null &&
14079 mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != NSB) {
14080 throw new ParcelFormatException("File corrupt: too many speed bins " +
14081 NSB);
14082 }
14083
Sudheer Shankaaf857412017-07-21 00:14:24 -070014084 u.mCpuClusterSpeedTimesUs[cluster] = new LongSamplingCounter[NSB];
Adam Lesinski6832f392015-09-05 18:05:40 -070014085 for (int speed = 0; speed < NSB; speed++) {
14086 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070014087 u.mCpuClusterSpeedTimesUs[cluster][speed] = new LongSamplingCounter(
Adam Lesinski6832f392015-09-05 18:05:40 -070014088 mOnBatteryTimeBase);
Sudheer Shankaaf857412017-07-21 00:14:24 -070014089 u.mCpuClusterSpeedTimesUs[cluster][speed].readSummaryFromParcelLocked(in);
Adam Lesinski6832f392015-09-05 18:05:40 -070014090 }
14091 }
Adam Lesinskia57a5402015-09-28 10:21:33 -070014092 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070014093 u.mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -070014094 }
14095 }
14096 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070014097 u.mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014098 }
14099
Sudheer Shanka59f5c002017-05-15 10:57:15 -070014100 u.mCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
14101 in, mOnBatteryTimeBase);
14102 u.mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
14103 in, mOnBatteryScreenOffTimeBase);
Mike Ma3d422c32017-10-25 11:08:57 -070014104
14105 u.mCpuActiveTimeMs.readSummaryFromParcelLocked(in);
14106 u.mCpuClusterTimesMs.readSummaryFromParcelLocked(in);
14107
Sudheer Shankab2f83c12017-11-13 19:25:01 -080014108 int length = in.readInt();
14109 if (length == Uid.NUM_PROCESS_STATE) {
14110 u.mProcStateTimeMs = new LongSamplingCounterArray[length];
14111 for (int procState = 0; procState < length; ++procState) {
14112 u.mProcStateTimeMs[procState]
14113 = LongSamplingCounterArray.readSummaryFromParcelLocked(
14114 in, mOnBatteryTimeBase);
14115 }
14116 } else {
14117 u.mProcStateTimeMs = null;
14118 }
14119 length = in.readInt();
14120 if (length == Uid.NUM_PROCESS_STATE) {
14121 u.mProcStateScreenOffTimeMs = new LongSamplingCounterArray[length];
14122 for (int procState = 0; procState < length; ++procState) {
14123 u.mProcStateScreenOffTimeMs[procState]
14124 = LongSamplingCounterArray.readSummaryFromParcelLocked(
14125 in, mOnBatteryScreenOffTimeBase);
14126 }
14127 } else {
14128 u.mProcStateScreenOffTimeMs = null;
14129 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070014130
14131 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -070014132 u.mMobileRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
14133 u.mMobileRadioApWakeupCount.readSummaryFromParcelLocked(in);
14134 } else {
14135 u.mMobileRadioApWakeupCount = null;
14136 }
14137
14138 if (in.readInt() != 0) {
14139 u.mWifiRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
14140 u.mWifiRadioApWakeupCount.readSummaryFromParcelLocked(in);
14141 } else {
14142 u.mWifiRadioApWakeupCount = null;
14143 }
14144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014145 int NW = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070014146 if (NW > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014147 throw new ParcelFormatException("File corrupt: too many wake locks " + NW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014149 for (int iw = 0; iw < NW; iw++) {
14150 String wlName = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014151 u.readWakeSummaryFromParcelLocked(wlName, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014152 }
14153
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014154 int NS = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070014155 if (NS > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014156 throw new ParcelFormatException("File corrupt: too many syncs " + NS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014157 }
14158 for (int is = 0; is < NS; is++) {
14159 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014160 u.readSyncSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014161 }
14162
14163 int NJ = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070014164 if (NJ > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014165 throw new ParcelFormatException("File corrupt: too many job timers " + NJ);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014166 }
14167 for (int ij = 0; ij < NJ; ij++) {
14168 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014169 u.readJobSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014170 }
14171
Dianne Hackborn94326cb2017-06-28 16:17:20 -070014172 u.readJobCompletionsFromParcelLocked(in);
14173
Amith Yamasani977e11f2018-02-16 11:29:54 -080014174 u.mJobsDeferredEventCount.readSummaryFromParcelLocked(in);
14175 u.mJobsDeferredCount.readSummaryFromParcelLocked(in);
14176 u.mJobsFreshnessTimeMs.readSummaryFromParcelLocked(in);
14177 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
14178 if (in.readInt() != 0) {
14179 u.mJobsFreshnessBuckets[i] = new Counter(u.mBsi.mOnBatteryTimeBase);
14180 u.mJobsFreshnessBuckets[i].readSummaryFromParcelLocked(in);
14181 }
14182 }
14183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014184 int NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014185 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014186 throw new ParcelFormatException("File corrupt: too many sensors " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014187 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014188 for (int is = 0; is < NP; is++) {
14189 int seNumber = in.readInt();
14190 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -080014191 u.getSensorTimerLocked(seNumber, true).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014192 }
14193 }
14194
14195 NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014196 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014197 throw new ParcelFormatException("File corrupt: too many processes " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014198 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014199 for (int ip = 0; ip < NP; ip++) {
14200 String procName = in.readString();
14201 Uid.Proc p = u.getProcessStatsLocked(procName);
14202 p.mUserTime = p.mLoadedUserTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014203 p.mSystemTime = p.mLoadedSystemTime = in.readLong();
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014204 p.mForegroundTime = p.mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014205 p.mStarts = p.mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014206 p.mNumCrashes = p.mLoadedNumCrashes = in.readInt();
14207 p.mNumAnrs = p.mLoadedNumAnrs = in.readInt();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014208 p.readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014209 }
14210
14211 NP = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014212 if (NP > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014213 throw new ParcelFormatException("File corrupt: too many packages " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014214 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014215 for (int ip = 0; ip < NP; ip++) {
14216 String pkgName = in.readString();
14217 Uid.Pkg p = u.getPackageStatsLocked(pkgName);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014218 final int NWA = in.readInt();
14219 if (NWA > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014220 throw new ParcelFormatException("File corrupt: too many wakeup alarms " + NWA);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014221 }
14222 p.mWakeupAlarms.clear();
14223 for (int iwa=0; iwa<NWA; iwa++) {
14224 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -070014225 Counter c = new Counter(mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014226 c.readSummaryFromParcelLocked(in);
14227 p.mWakeupAlarms.put(tag, c);
14228 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014229 NS = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014230 if (NS > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014231 throw new ParcelFormatException("File corrupt: too many services " + NS);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014232 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014233 for (int is = 0; is < NS; is++) {
14234 String servName = in.readString();
14235 Uid.Pkg.Serv s = u.getServiceStatsLocked(pkgName, servName);
14236 s.mStartTime = s.mLoadedStartTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014237 s.mStarts = s.mLoadedStarts = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014238 s.mLaunches = s.mLoadedLaunches = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014239 }
14240 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014241 }
14242 }
14243
14244 /**
14245 * Writes a summary of the statistics to a Parcel, in a format suitable to be written to
14246 * disk. This format does not allow a lossless round-trip.
14247 *
14248 * @param out the Parcel to be written to.
14249 */
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070014250 public void writeSummaryToParcel(Parcel out, boolean inclHistory) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080014251 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014252
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014253 // Pull the clock time. This may update the time and make a new history entry
14254 // if we had originally pulled a time before the RTC was set.
14255 long startClockTime = getStartClockTime();
14256
Joe Onoratoabded112016-02-08 16:49:39 -080014257 final long NOW_SYS = mClocks.uptimeMillis() * 1000;
14258 final long NOWREAL_SYS = mClocks.elapsedRealtime() * 1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014259
14260 out.writeInt(VERSION);
14261
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070014262 writeHistory(out, inclHistory, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014264 out.writeInt(mStartCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014265 out.writeLong(computeUptime(NOW_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014266 out.writeLong(computeRealtime(NOWREAL_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014267 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014268 out.writeString(mStartPlatformVersion);
14269 out.writeString(mEndPlatformVersion);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014270 mOnBatteryTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
14271 mOnBatteryScreenOffTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014272 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014273 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070014274 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014275 out.writeInt(mCurrentBatteryLevel);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014276 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070014277 out.writeInt(mMinLearnedBatteryCapacity);
14278 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborne4a59512010-12-07 11:08:07 -080014279 out.writeInt(getLowDischargeAmountSinceCharge());
14280 out.writeInt(getHighDischargeAmountSinceCharge());
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014281 out.writeInt(getDischargeAmountScreenOnSinceCharge());
14282 out.writeInt(getDischargeAmountScreenOffSinceCharge());
Mike Mac2f518a2017-09-19 16:06:03 -070014283 out.writeInt(getDischargeAmountScreenDozeSinceCharge());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014284 mDischargeStepTracker.writeToParcel(out);
14285 mChargeStepTracker.writeToParcel(out);
14286 mDailyDischargeStepTracker.writeToParcel(out);
14287 mDailyChargeStepTracker.writeToParcel(out);
Adam Lesinski67c134f2016-06-10 15:15:08 -070014288 mDischargeCounter.writeSummaryFromParcelLocked(out);
14289 mDischargeScreenOffCounter.writeSummaryFromParcelLocked(out);
Mike Mac2f518a2017-09-19 16:06:03 -070014290 mDischargeScreenDozeCounter.writeSummaryFromParcelLocked(out);
Mike Ma15313c92017-11-15 17:58:21 -080014291 mDischargeLightDozeCounter.writeSummaryFromParcelLocked(out);
14292 mDischargeDeepDozeCounter.writeSummaryFromParcelLocked(out);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014293 if (mDailyPackageChanges != null) {
14294 final int NPKG = mDailyPackageChanges.size();
14295 out.writeInt(NPKG);
14296 for (int i=0; i<NPKG; i++) {
14297 PackageChange pc = mDailyPackageChanges.get(i);
14298 out.writeString(pc.mPackageName);
14299 out.writeInt(pc.mUpdate ? 1 : 0);
Dianne Hackborn3accca02013-09-20 09:32:11 -070014300 out.writeLong(pc.mVersionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014301 }
14302 } else {
14303 out.writeInt(0);
14304 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014305 out.writeLong(mDailyStartTime);
14306 out.writeLong(mNextMinDailyDeadline);
14307 out.writeLong(mNextMaxDailyDeadline);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014308
14309 mScreenOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Mike Mac2f518a2017-09-19 16:06:03 -070014310 mScreenDozeTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070014311 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014312 mScreenBrightnessTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070014313 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070014314 mInteractiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070014315 mPowerSaveModeEnabledTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014316 out.writeLong(mLongestLightIdleTime);
14317 out.writeLong(mLongestFullIdleTime);
14318 mDeviceIdleModeLightTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14319 mDeviceIdleModeFullTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14320 mDeviceLightIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014321 mDeviceIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014322 mPhoneOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Wink Saville52840902011-02-18 12:40:47 -080014323 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014324 mPhoneSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070014325 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014326 mPhoneSignalScanningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070014327 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014328 mPhoneDataConnectionsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070014329 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014330 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014331 mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
14332 mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014333 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014334 mMobileRadioActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14335 mMobileRadioActivePerAppTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014336 mMobileRadioActiveAdjustedTime.writeSummaryFromParcelLocked(out);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080014337 mMobileRadioActiveUnknownTime.writeSummaryFromParcelLocked(out);
14338 mMobileRadioActiveUnknownCount.writeSummaryFromParcelLocked(out);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014339 mWifiMulticastWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014340 mWifiOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14341 mGlobalWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080014342 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014343 mWifiStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080014344 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014345 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
14346 mWifiSupplStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14347 }
14348 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
14349 mWifiSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14350 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014351 mWifiActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14352 mWifiActivity.writeSummaryToParcel(out);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014353 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14354 mGpsSignalQualityTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14355 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014356 mBluetoothActivity.writeSummaryToParcel(out);
14357 mModemActivity.writeSummaryToParcel(out);
14358 out.writeInt(mHasWifiReporting ? 1 : 0);
14359 out.writeInt(mHasBluetoothReporting ? 1 : 0);
14360 out.writeInt(mHasModemReporting ? 1 : 0);
14361
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014362 out.writeInt(mNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070014363 mFlashlightOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014364 mCameraOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014365 mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014366
Bookatz50df7112017-08-04 14:53:26 -070014367 out.writeInt(mRpmStats.size());
14368 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
14369 Timer rpmt = ent.getValue();
14370 if (rpmt != null) {
14371 out.writeInt(1);
14372 out.writeString(ent.getKey());
14373 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14374 } else {
14375 out.writeInt(0);
14376 }
14377 }
14378 out.writeInt(mScreenOffRpmStats.size());
14379 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
14380 Timer rpmt = ent.getValue();
14381 if (rpmt != null) {
14382 out.writeInt(1);
14383 out.writeString(ent.getKey());
14384 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14385 } else {
14386 out.writeInt(0);
14387 }
14388 }
14389
Evan Millarc64edde2009-04-18 12:26:32 -070014390 out.writeInt(mKernelWakelockStats.size());
14391 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
14392 Timer kwlt = ent.getValue();
14393 if (kwlt != null) {
14394 out.writeInt(1);
14395 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014396 kwlt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14397 } else {
14398 out.writeInt(0);
14399 }
14400 }
14401
14402 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014403 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
14404 SamplingTimer timer = ent.getValue();
14405 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014406 out.writeInt(1);
14407 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014408 timer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Evan Millarc64edde2009-04-18 12:26:32 -070014409 } else {
14410 out.writeInt(0);
14411 }
14412 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014413
James Carr3a226052016-07-01 14:49:52 -070014414 out.writeInt(mKernelMemoryStats.size());
14415 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
14416 Timer kmt = mKernelMemoryStats.valueAt(i);
14417 if (kmt != null) {
14418 out.writeInt(1);
14419 out.writeLong(mKernelMemoryStats.keyAt(i));
14420 kmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14421 } else {
14422 out.writeInt(0);
14423 }
14424 }
14425
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014426 final int NU = mUidStats.size();
14427 out.writeInt(NU);
14428 for (int iu = 0; iu < NU; iu++) {
14429 out.writeInt(mUidStats.keyAt(iu));
14430 Uid u = mUidStats.valueAt(iu);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014431
Bookatz867c0d72017-03-07 18:23:42 -080014432 u.mOnBatteryBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatzc8c44962017-05-11 12:12:54 -070014433 u.mOnBatteryScreenOffBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatz867c0d72017-03-07 18:23:42 -080014434
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014435 if (u.mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014436 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014437 u.mWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014438 } else {
14439 out.writeInt(0);
14440 }
14441 if (u.mFullWifiLockTimer != null) {
14442 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014443 u.mFullWifiLockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014444 } else {
14445 out.writeInt(0);
14446 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070014447 if (u.mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014448 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014449 u.mWifiScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014450 } else {
14451 out.writeInt(0);
14452 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070014453 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
14454 if (u.mWifiBatchedScanTimer[i] != null) {
14455 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014456 u.mWifiBatchedScanTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Robert Greenwalta029ea12013-09-25 16:38:12 -070014457 } else {
14458 out.writeInt(0);
14459 }
14460 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014461 if (u.mWifiMulticastTimer != null) {
14462 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014463 u.mWifiMulticastTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014464 } else {
14465 out.writeInt(0);
14466 }
14467 if (u.mAudioTurnedOnTimer != null) {
14468 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014469 u.mAudioTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014470 } else {
14471 out.writeInt(0);
14472 }
14473 if (u.mVideoTurnedOnTimer != null) {
14474 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014475 u.mVideoTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014476 } else {
14477 out.writeInt(0);
14478 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014479 if (u.mFlashlightTurnedOnTimer != null) {
14480 out.writeInt(1);
14481 u.mFlashlightTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14482 } else {
14483 out.writeInt(0);
14484 }
14485 if (u.mCameraTurnedOnTimer != null) {
14486 out.writeInt(1);
14487 u.mCameraTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14488 } else {
14489 out.writeInt(0);
14490 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014491 if (u.mForegroundActivityTimer != null) {
14492 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014493 u.mForegroundActivityTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014494 } else {
14495 out.writeInt(0);
14496 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070014497 if (u.mForegroundServiceTimer != null) {
14498 out.writeInt(1);
14499 u.mForegroundServiceTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14500 } else {
14501 out.writeInt(0);
14502 }
Bookatzc8c44962017-05-11 12:12:54 -070014503 if (u.mAggregatedPartialWakelockTimer != null) {
14504 out.writeInt(1);
14505 u.mAggregatedPartialWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14506 } else {
14507 out.writeInt(0);
14508 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014509 if (u.mBluetoothScanTimer != null) {
14510 out.writeInt(1);
14511 u.mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14512 } else {
14513 out.writeInt(0);
14514 }
Bookatzb1f04f32017-05-19 13:57:32 -070014515 if (u.mBluetoothUnoptimizedScanTimer != null) {
14516 out.writeInt(1);
14517 u.mBluetoothUnoptimizedScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14518 } else {
14519 out.writeInt(0);
14520 }
Bookatz956f36bf2017-04-28 09:48:17 -070014521 if (u.mBluetoothScanResultCounter != null) {
14522 out.writeInt(1);
14523 u.mBluetoothScanResultCounter.writeSummaryFromParcelLocked(out);
14524 } else {
14525 out.writeInt(0);
14526 }
Bookatzb1f04f32017-05-19 13:57:32 -070014527 if (u.mBluetoothScanResultBgCounter != null) {
14528 out.writeInt(1);
14529 u.mBluetoothScanResultBgCounter.writeSummaryFromParcelLocked(out);
14530 } else {
14531 out.writeInt(0);
14532 }
Dianne Hackborn61659e52014-07-09 16:13:01 -070014533 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
14534 if (u.mProcessStateTimer[i] != null) {
14535 out.writeInt(1);
14536 u.mProcessStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14537 } else {
14538 out.writeInt(0);
14539 }
14540 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014541 if (u.mVibratorOnTimer != null) {
14542 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014543 u.mVibratorOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014544 } else {
14545 out.writeInt(0);
14546 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014547
Dianne Hackborn617f8772009-03-31 15:04:46 -070014548 if (u.mUserActivityCounters == null) {
14549 out.writeInt(0);
14550 } else {
14551 out.writeInt(1);
14552 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
14553 u.mUserActivityCounters[i].writeSummaryFromParcelLocked(out);
14554 }
14555 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014556
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014557 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014558 out.writeInt(0);
14559 } else {
14560 out.writeInt(1);
14561 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014562 u.mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
14563 u.mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014564 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080014565 u.mMobileRadioActiveTime.writeSummaryFromParcelLocked(out);
14566 u.mMobileRadioActiveCount.writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014567 }
14568
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014569 u.mUserCpuTime.writeSummaryFromParcelLocked(out);
14570 u.mSystemCpuTime.writeSummaryFromParcelLocked(out);
14571
Sudheer Shankaaf857412017-07-21 00:14:24 -070014572 if (u.mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -070014573 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -070014574 out.writeInt(u.mCpuClusterSpeedTimesUs.length);
14575 for (LongSamplingCounter[] cpuSpeeds : u.mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -070014576 if (cpuSpeeds != null) {
14577 out.writeInt(1);
14578 out.writeInt(cpuSpeeds.length);
14579 for (LongSamplingCounter c : cpuSpeeds) {
14580 if (c != null) {
14581 out.writeInt(1);
14582 c.writeSummaryFromParcelLocked(out);
14583 } else {
14584 out.writeInt(0);
14585 }
14586 }
14587 } else {
14588 out.writeInt(0);
14589 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014590 }
Adam Lesinski6832f392015-09-05 18:05:40 -070014591 } else {
14592 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014593 }
14594
Sudheer Shanka59f5c002017-05-15 10:57:15 -070014595 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mCpuFreqTimeMs);
14596 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mScreenOffCpuFreqTimeMs);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070014597
Mike Ma3d422c32017-10-25 11:08:57 -070014598 u.mCpuActiveTimeMs.writeSummaryFromParcelLocked(out);
14599 u.mCpuClusterTimesMs.writeSummaryToParcelLocked(out);
14600
Sudheer Shankab2f83c12017-11-13 19:25:01 -080014601 if (u.mProcStateTimeMs != null) {
14602 out.writeInt(u.mProcStateTimeMs.length);
14603 for (LongSamplingCounterArray counters : u.mProcStateTimeMs) {
14604 LongSamplingCounterArray.writeSummaryToParcelLocked(out, counters);
14605 }
14606 } else {
14607 out.writeInt(0);
14608 }
14609 if (u.mProcStateScreenOffTimeMs != null) {
14610 out.writeInt(u.mProcStateScreenOffTimeMs.length);
14611 for (LongSamplingCounterArray counters : u.mProcStateScreenOffTimeMs) {
14612 LongSamplingCounterArray.writeSummaryToParcelLocked(out, counters);
14613 }
14614 } else {
14615 out.writeInt(0);
14616 }
14617
Adam Lesinski5f056f62016-07-14 16:56:08 -070014618 if (u.mMobileRadioApWakeupCount != null) {
14619 out.writeInt(1);
14620 u.mMobileRadioApWakeupCount.writeSummaryFromParcelLocked(out);
14621 } else {
14622 out.writeInt(0);
14623 }
14624
14625 if (u.mWifiRadioApWakeupCount != null) {
14626 out.writeInt(1);
14627 u.mWifiRadioApWakeupCount.writeSummaryFromParcelLocked(out);
14628 } else {
14629 out.writeInt(0);
14630 }
14631
Dianne Hackbornd953c532014-08-16 18:17:38 -070014632 final ArrayMap<String, Uid.Wakelock> wakeStats = u.mWakelockStats.getMap();
14633 int NW = wakeStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014634 out.writeInt(NW);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014635 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014636 out.writeString(wakeStats.keyAt(iw));
14637 Uid.Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014638 if (wl.mTimerFull != null) {
14639 out.writeInt(1);
14640 wl.mTimerFull.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14641 } else {
14642 out.writeInt(0);
14643 }
14644 if (wl.mTimerPartial != null) {
14645 out.writeInt(1);
14646 wl.mTimerPartial.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14647 } else {
14648 out.writeInt(0);
14649 }
14650 if (wl.mTimerWindow != null) {
14651 out.writeInt(1);
14652 wl.mTimerWindow.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14653 } else {
14654 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014655 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070014656 if (wl.mTimerDraw != null) {
Adam Lesinski9425fe22015-06-19 12:02:13 -070014657 out.writeInt(1);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070014658 wl.mTimerDraw.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9425fe22015-06-19 12:02:13 -070014659 } else {
14660 out.writeInt(0);
14661 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014662 }
14663
Bookatz2bffb5b2017-04-13 11:59:33 -070014664 final ArrayMap<String, DualTimer> syncStats = u.mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014665 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014666 out.writeInt(NS);
14667 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014668 out.writeString(syncStats.keyAt(is));
14669 syncStats.valueAt(is).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014670 }
14671
Bookatzaa4594a2017-03-24 12:39:56 -070014672 final ArrayMap<String, DualTimer> jobStats = u.mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014673 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014674 out.writeInt(NJ);
14675 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014676 out.writeString(jobStats.keyAt(ij));
14677 jobStats.valueAt(ij).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014678 }
14679
Dianne Hackborn94326cb2017-06-28 16:17:20 -070014680 u.writeJobCompletionsToParcelLocked(out);
14681
Amith Yamasani977e11f2018-02-16 11:29:54 -080014682 u.mJobsDeferredEventCount.writeSummaryFromParcelLocked(out);
14683 u.mJobsDeferredCount.writeSummaryFromParcelLocked(out);
14684 u.mJobsFreshnessTimeMs.writeSummaryFromParcelLocked(out);
14685 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
14686 if (u.mJobsFreshnessBuckets[i] != null) {
Adam Lesinski14082082018-02-23 12:35:55 -080014687 out.writeInt(1);
Amith Yamasani977e11f2018-02-16 11:29:54 -080014688 u.mJobsFreshnessBuckets[i].writeSummaryFromParcelLocked(out);
14689 } else {
14690 out.writeInt(0);
14691 }
14692 }
14693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014694 int NSE = u.mSensorStats.size();
14695 out.writeInt(NSE);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014696 for (int ise=0; ise<NSE; ise++) {
14697 out.writeInt(u.mSensorStats.keyAt(ise));
14698 Uid.Sensor se = u.mSensorStats.valueAt(ise);
14699 if (se.mTimer != null) {
14700 out.writeInt(1);
14701 se.mTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14702 } else {
14703 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014704 }
14705 }
14706
14707 int NP = u.mProcessStats.size();
14708 out.writeInt(NP);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014709 for (int ip=0; ip<NP; ip++) {
14710 out.writeString(u.mProcessStats.keyAt(ip));
14711 Uid.Proc ps = u.mProcessStats.valueAt(ip);
14712 out.writeLong(ps.mUserTime);
14713 out.writeLong(ps.mSystemTime);
14714 out.writeLong(ps.mForegroundTime);
14715 out.writeInt(ps.mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014716 out.writeInt(ps.mNumCrashes);
14717 out.writeInt(ps.mNumAnrs);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014718 ps.writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014719 }
14720
14721 NP = u.mPackageStats.size();
14722 out.writeInt(NP);
14723 if (NP > 0) {
14724 for (Map.Entry<String, BatteryStatsImpl.Uid.Pkg> ent
14725 : u.mPackageStats.entrySet()) {
14726 out.writeString(ent.getKey());
14727 Uid.Pkg ps = ent.getValue();
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014728 final int NWA = ps.mWakeupAlarms.size();
14729 out.writeInt(NWA);
14730 for (int iwa=0; iwa<NWA; iwa++) {
14731 out.writeString(ps.mWakeupAlarms.keyAt(iwa));
14732 ps.mWakeupAlarms.valueAt(iwa).writeSummaryFromParcelLocked(out);
14733 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014734 NS = ps.mServiceStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014735 out.writeInt(NS);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014736 for (int is=0; is<NS; is++) {
14737 out.writeString(ps.mServiceStats.keyAt(is));
14738 BatteryStatsImpl.Uid.Pkg.Serv ss = ps.mServiceStats.valueAt(is);
14739 long time = ss.getStartTimeToNowLocked(
14740 mOnBatteryTimeBase.getUptime(NOW_SYS));
14741 out.writeLong(time);
14742 out.writeInt(ss.mStarts);
14743 out.writeInt(ss.mLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014744 }
14745 }
14746 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014747 }
14748 }
14749
14750 public void readFromParcel(Parcel in) {
14751 readFromParcelLocked(in);
14752 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014754 void readFromParcelLocked(Parcel in) {
14755 int magic = in.readInt();
14756 if (magic != MAGIC) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014757 throw new ParcelFormatException("Bad magic number: #" + Integer.toHexString(magic));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014758 }
14759
Dianne Hackbornae384452011-06-28 12:33:48 -070014760 readHistory(in, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014762 mStartCount = in.readInt();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080014763 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014764 mStartPlatformVersion = in.readString();
14765 mEndPlatformVersion = in.readString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014766 mUptime = in.readLong();
14767 mUptimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014768 mRealtime = in.readLong();
14769 mRealtimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014770 mOnBattery = in.readInt() != 0;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014771 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070014772 mMinLearnedBatteryCapacity = in.readInt();
14773 mMaxLearnedBatteryCapacity = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014774 mOnBatteryInternal = false; // we are no longer really running.
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014775 mOnBatteryTimeBase.readFromParcel(in);
14776 mOnBatteryScreenOffTimeBase.readFromParcel(in);
14777
Jeff Browne95c3cd2014-05-02 16:59:26 -070014778 mScreenState = Display.STATE_UNKNOWN;
Joe Onoratoabded112016-02-08 16:49:39 -080014779 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070014780 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014781 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014782 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
14783 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014784 }
Dianne Hackborn29325132014-05-21 15:01:03 -070014785 mInteractive = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014786 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014787 mPhoneOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014788 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
14789 mOnBatteryTimeBase, in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014790 mLongestLightIdleTime = in.readLong();
14791 mLongestFullIdleTime = in.readLong();
Joe Onoratoabded112016-02-08 16:49:39 -080014792 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -14, null,
14793 mOnBatteryTimeBase, in);
14794 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -11, null,
14795 mOnBatteryTimeBase, in);
14796 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null,
14797 mOnBatteryTimeBase, in);
14798 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase, in);
14799 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014800 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014801 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014802 null, mOnBatteryTimeBase, in);
14803 }
Joe Onoratoabded112016-02-08 16:49:39 -080014804 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
14805 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014806 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014807 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014808 null, mOnBatteryTimeBase, in);
14809 }
14810 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
14811 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
14812 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
14813 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014814 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Joe Onoratoabded112016-02-08 16:49:39 -080014815 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null,
14816 mOnBatteryTimeBase, in);
Kweku Adams87b19ec2017-10-09 12:40:03 -070014817 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
Joe Onoratoabded112016-02-08 16:49:39 -080014818 mOnBatteryTimeBase, in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014819 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014820 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
14821 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase, in);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014822 mWifiMulticastWakelockTimer = new StopwatchTimer(mClocks, null, -4, null,
14823 mOnBatteryTimeBase, in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070014824 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014825 mWifiOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014826 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014827 mGlobalWifiRunning = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014828 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null,
14829 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014830 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014831 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014832 null, mOnBatteryTimeBase, in);
14833 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014834 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014835 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070014836 null, mOnBatteryTimeBase, in);
14837 }
14838 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014839 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070014840 null, mOnBatteryTimeBase, in);
14841 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014842 mWifiActiveTimer = new StopwatchTimer(mClocks, null, -900, null,
14843 mOnBatteryTimeBase, in);
14844 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14845 NUM_WIFI_TX_LEVELS, in);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014846 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14847 mGpsSignalQualityTimer[i] = new StopwatchTimer(mClocks, null, -1000-i,
14848 null, mOnBatteryTimeBase, in);
14849 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014850 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14851 NUM_BT_TX_LEVELS, in);
14852 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14853 ModemActivityInfo.TX_POWER_LEVELS, in);
14854 mHasWifiReporting = in.readInt() != 0;
14855 mHasBluetoothReporting = in.readInt() != 0;
14856 mHasModemReporting = in.readInt() != 0;
14857
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014858 mNumConnectivityChange = in.readInt();
14859 mLoadedNumConnectivityChange = in.readInt();
14860 mUnpluggedNumConnectivityChange = in.readInt();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014861 mAudioOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014862 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014863 mVideoOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014864 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014865 mFlashlightOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014866 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014867 mCameraOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014868 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014869 mBluetoothScanNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014870 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase, in);
Siddharth Rayf5e796a2018-01-22 18:18:17 -080014871 mIsCellularTxPowerHigh = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014872 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014873 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070014874 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014875 mCurrentBatteryLevel = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014876 mLowDischargeAmountSinceCharge = in.readInt();
14877 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014878 mDischargeAmountScreenOn = in.readInt();
14879 mDischargeAmountScreenOnSinceCharge = in.readInt();
14880 mDischargeAmountScreenOff = in.readInt();
14881 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070014882 mDischargeAmountScreenDoze = in.readInt();
14883 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014884 mDischargeStepTracker.readFromParcel(in);
14885 mChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070014886 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070014887 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase, in);
14888 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Ma15313c92017-11-15 17:58:21 -080014889 mDischargeLightDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
14890 mDischargeDeepDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014891 mLastWriteTime = in.readLong();
14892
Bookatz50df7112017-08-04 14:53:26 -070014893 mRpmStats.clear();
14894 int NRPMS = in.readInt();
14895 for (int irpm = 0; irpm < NRPMS; irpm++) {
14896 if (in.readInt() != 0) {
14897 String rpmName = in.readString();
14898 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
14899 mRpmStats.put(rpmName, rpmt);
14900 }
14901 }
14902 mScreenOffRpmStats.clear();
14903 int NSORPMS = in.readInt();
14904 for (int irpm = 0; irpm < NSORPMS; irpm++) {
14905 if (in.readInt() != 0) {
14906 String rpmName = in.readString();
14907 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
14908 mScreenOffRpmStats.put(rpmName, rpmt);
14909 }
14910 }
14911
Evan Millarc64edde2009-04-18 12:26:32 -070014912 mKernelWakelockStats.clear();
14913 int NKW = in.readInt();
14914 for (int ikw = 0; ikw < NKW; ikw++) {
14915 if (in.readInt() != 0) {
14916 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080014917 SamplingTimer kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -070014918 mKernelWakelockStats.put(wakelockName, kwlt);
14919 }
14920 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014921
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014922 mWakeupReasonStats.clear();
14923 int NWR = in.readInt();
14924 for (int iwr = 0; iwr < NWR; iwr++) {
14925 if (in.readInt() != 0) {
14926 String reasonName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080014927 SamplingTimer timer = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014928 mWakeupReasonStats.put(reasonName, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014929 }
14930 }
14931
James Carr3a226052016-07-01 14:49:52 -070014932 mKernelMemoryStats.clear();
14933 int nmt = in.readInt();
14934 for (int imt = 0; imt < nmt; imt++) {
14935 if (in.readInt() != 0) {
14936 Long bucket = in.readLong();
14937 SamplingTimer kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
14938 mKernelMemoryStats.put(bucket, kmt);
14939 }
14940 }
14941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014942 mPartialTimers.clear();
14943 mFullTimers.clear();
14944 mWindowTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014945 mWifiRunningTimers.clear();
14946 mFullWifiLockTimers.clear();
Nick Pelly6ccaa542012-06-15 15:22:47 -070014947 mWifiScanTimers.clear();
Robert Greenwalta029ea12013-09-25 16:38:12 -070014948 mWifiBatchedScanTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014949 mWifiMulticastTimers.clear();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014950 mAudioTurnedOnTimers.clear();
14951 mVideoTurnedOnTimers.clear();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014952 mFlashlightTurnedOnTimers.clear();
14953 mCameraTurnedOnTimers.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014954
14955 int numUids = in.readInt();
14956 mUidStats.clear();
14957 for (int i = 0; i < numUids; i++) {
14958 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080014959 Uid u = new Uid(this, uid);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014960 u.readFromParcelLocked(mOnBatteryTimeBase, mOnBatteryScreenOffTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014961 mUidStats.append(uid, u);
14962 }
14963 }
14964
14965 public void writeToParcel(Parcel out, int flags) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014966 writeToParcelLocked(out, true, flags);
14967 }
14968
14969 public void writeToParcelWithoutUids(Parcel out, int flags) {
14970 writeToParcelLocked(out, false, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014971 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014972
14973 @SuppressWarnings("unused")
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014974 void writeToParcelLocked(Parcel out, boolean inclUids, int flags) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014975 // Need to update with current kernel wake lock counts.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080014976 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014977
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014978 // Pull the clock time. This may update the time and make a new history entry
14979 // if we had originally pulled a time before the RTC was set.
14980 long startClockTime = getStartClockTime();
14981
Joe Onoratoabded112016-02-08 16:49:39 -080014982 final long uSecUptime = mClocks.uptimeMillis() * 1000;
14983 final long uSecRealtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014984 final long batteryRealtime = mOnBatteryTimeBase.getRealtime(uSecRealtime);
14985 final long batteryScreenOffRealtime = mOnBatteryScreenOffTimeBase.getRealtime(uSecRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014986
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014987 out.writeInt(MAGIC);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014988
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070014989 writeHistory(out, true, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014990
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014991 out.writeInt(mStartCount);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014992 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014993 out.writeString(mStartPlatformVersion);
14994 out.writeString(mEndPlatformVersion);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014995 out.writeLong(mUptime);
14996 out.writeLong(mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014997 out.writeLong(mRealtime);
14998 out.writeLong(mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014999 out.writeInt(mOnBattery ? 1 : 0);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070015000 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070015001 out.writeInt(mMinLearnedBatteryCapacity);
15002 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080015003 mOnBatteryTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
15004 mOnBatteryScreenOffTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
15005
15006 mScreenOnTimer.writeToParcel(out, uSecRealtime);
Mike Mac2f518a2017-09-19 16:06:03 -070015007 mScreenDozeTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080015008 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
15009 mScreenBrightnessTimer[i].writeToParcel(out, uSecRealtime);
15010 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070015011 mInteractiveTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070015012 mPowerSaveModeEnabledTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070015013 out.writeLong(mLongestLightIdleTime);
15014 out.writeLong(mLongestFullIdleTime);
15015 mDeviceIdleModeLightTimer.writeToParcel(out, uSecRealtime);
15016 mDeviceIdleModeFullTimer.writeToParcel(out, uSecRealtime);
15017 mDeviceLightIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070015018 mDeviceIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080015019 mPhoneOnTimer.writeToParcel(out, uSecRealtime);
15020 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
15021 mPhoneSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
15022 }
15023 mPhoneSignalScanningTimer.writeToParcel(out, uSecRealtime);
15024 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
15025 mPhoneDataConnectionsTimer[i].writeToParcel(out, uSecRealtime);
15026 }
15027 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
15028 mNetworkByteActivityCounters[i].writeToParcel(out);
15029 mNetworkPacketActivityCounters[i].writeToParcel(out);
15030 }
15031 mMobileRadioActiveTimer.writeToParcel(out, uSecRealtime);
15032 mMobileRadioActivePerAppTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070015033 mMobileRadioActiveAdjustedTime.writeToParcel(out);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080015034 mMobileRadioActiveUnknownTime.writeToParcel(out);
15035 mMobileRadioActiveUnknownCount.writeToParcel(out);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080015036 mWifiMulticastWakelockTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080015037 mWifiOnTimer.writeToParcel(out, uSecRealtime);
15038 mGlobalWifiRunningTimer.writeToParcel(out, uSecRealtime);
15039 for (int i=0; i<NUM_WIFI_STATES; i++) {
15040 mWifiStateTimer[i].writeToParcel(out, uSecRealtime);
15041 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070015042 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
15043 mWifiSupplStateTimer[i].writeToParcel(out, uSecRealtime);
15044 }
15045 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
15046 mWifiSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
15047 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080015048 mWifiActiveTimer.writeToParcel(out, uSecRealtime);
15049 mWifiActivity.writeToParcel(out, 0);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080015050 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
15051 mGpsSignalQualityTimer[i].writeToParcel(out, uSecRealtime);
15052 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080015053 mBluetoothActivity.writeToParcel(out, 0);
15054 mModemActivity.writeToParcel(out, 0);
15055 out.writeInt(mHasWifiReporting ? 1 : 0);
15056 out.writeInt(mHasBluetoothReporting ? 1 : 0);
15057 out.writeInt(mHasModemReporting ? 1 : 0);
15058
Dianne Hackborn1e01d162014-12-04 17:46:42 -080015059 out.writeInt(mNumConnectivityChange);
15060 out.writeInt(mLoadedNumConnectivityChange);
15061 out.writeInt(mUnpluggedNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070015062 mFlashlightOnTimer.writeToParcel(out, uSecRealtime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070015063 mCameraOnTimer.writeToParcel(out, uSecRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080015064 mBluetoothScanTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070015065 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070015066 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070015067 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070015068 out.writeInt(mCurrentBatteryLevel);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015069 out.writeInt(mLowDischargeAmountSinceCharge);
15070 out.writeInt(mHighDischargeAmountSinceCharge);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080015071 out.writeInt(mDischargeAmountScreenOn);
15072 out.writeInt(mDischargeAmountScreenOnSinceCharge);
15073 out.writeInt(mDischargeAmountScreenOff);
15074 out.writeInt(mDischargeAmountScreenOffSinceCharge);
Mike Mac2f518a2017-09-19 16:06:03 -070015075 out.writeInt(mDischargeAmountScreenDoze);
15076 out.writeInt(mDischargeAmountScreenDozeSinceCharge);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080015077 mDischargeStepTracker.writeToParcel(out);
15078 mChargeStepTracker.writeToParcel(out);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070015079 mDischargeCounter.writeToParcel(out);
15080 mDischargeScreenOffCounter.writeToParcel(out);
Mike Mac2f518a2017-09-19 16:06:03 -070015081 mDischargeScreenDozeCounter.writeToParcel(out);
Mike Ma15313c92017-11-15 17:58:21 -080015082 mDischargeLightDozeCounter.writeToParcel(out);
15083 mDischargeDeepDozeCounter.writeToParcel(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015084 out.writeLong(mLastWriteTime);
15085
Bookatz50df7112017-08-04 14:53:26 -070015086 out.writeInt(mRpmStats.size());
15087 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
15088 SamplingTimer rpmt = ent.getValue();
15089 if (rpmt != null) {
15090 out.writeInt(1);
15091 out.writeString(ent.getKey());
15092 rpmt.writeToParcel(out, uSecRealtime);
15093 } else {
15094 out.writeInt(0);
15095 }
15096 }
15097 out.writeInt(mScreenOffRpmStats.size());
15098 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
15099 SamplingTimer rpmt = ent.getValue();
15100 if (rpmt != null) {
15101 out.writeInt(1);
15102 out.writeString(ent.getKey());
15103 rpmt.writeToParcel(out, uSecRealtime);
15104 } else {
15105 out.writeInt(0);
15106 }
15107 }
15108
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015109 if (inclUids) {
15110 out.writeInt(mKernelWakelockStats.size());
15111 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
15112 SamplingTimer kwlt = ent.getValue();
15113 if (kwlt != null) {
15114 out.writeInt(1);
15115 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070015116 kwlt.writeToParcel(out, uSecRealtime);
15117 } else {
15118 out.writeInt(0);
15119 }
15120 }
15121 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070015122 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
15123 SamplingTimer timer = ent.getValue();
15124 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070015125 out.writeInt(1);
15126 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070015127 timer.writeToParcel(out, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015128 } else {
15129 out.writeInt(0);
15130 }
Evan Millarc64edde2009-04-18 12:26:32 -070015131 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015132 } else {
Bookatzba78b2b2017-10-10 11:06:33 -070015133 out.writeInt(0);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015134 out.writeInt(0);
Evan Millarc64edde2009-04-18 12:26:32 -070015135 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070015136
James Carr3a226052016-07-01 14:49:52 -070015137 out.writeInt(mKernelMemoryStats.size());
15138 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
15139 SamplingTimer kmt = mKernelMemoryStats.valueAt(i);
15140 if (kmt != null) {
15141 out.writeInt(1);
15142 out.writeLong(mKernelMemoryStats.keyAt(i));
15143 kmt.writeToParcel(out, uSecRealtime);
15144 } else {
15145 out.writeInt(0);
15146 }
15147 }
15148
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015149 if (inclUids) {
15150 int size = mUidStats.size();
15151 out.writeInt(size);
15152 for (int i = 0; i < size; i++) {
15153 out.writeInt(mUidStats.keyAt(i));
15154 Uid uid = mUidStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015155
Bookatz867c0d72017-03-07 18:23:42 -080015156 uid.writeToParcelLocked(out, uSecUptime, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015157 }
15158 } else {
15159 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015160 }
15161 }
15162
Mathew Inwoodc185f082018-08-20 14:28:54 +010015163 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015164 public static final Parcelable.Creator<BatteryStatsImpl> CREATOR =
15165 new Parcelable.Creator<BatteryStatsImpl>() {
15166 public BatteryStatsImpl createFromParcel(Parcel in) {
15167 return new BatteryStatsImpl(in);
15168 }
15169
15170 public BatteryStatsImpl[] newArray(int size) {
15171 return new BatteryStatsImpl[size];
15172 }
15173 };
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070015174
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070015175 public void prepareForDumpLocked() {
15176 // Need to retrieve current kernel wake lock stats before printing.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080015177 pullPendingStateUpdatesLocked();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070015178
15179 // Pull the clock time. This may update the time and make a new history entry
15180 // if we had originally pulled a time before the RTC was set.
15181 getStartClockTime();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070015182 }
15183
Dianne Hackbornc51cf032014-03-02 19:08:15 -080015184 public void dumpLocked(Context context, PrintWriter pw, int flags, int reqUid, long histStart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015185 if (DEBUG) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080015186 pw.println("mOnBatteryTimeBase:");
15187 mOnBatteryTimeBase.dump(pw, " ");
15188 pw.println("mOnBatteryScreenOffTimeBase:");
15189 mOnBatteryScreenOffTimeBase.dump(pw, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015190 Printer pr = new PrintWriterPrinter(pw);
Mike Mac2f518a2017-09-19 16:06:03 -070015191 pr.println("*** Screen on timer:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015192 mScreenOnTimer.logState(pr, " ");
Mike Mac2f518a2017-09-19 16:06:03 -070015193 pr.println("*** Screen doze timer:");
15194 mScreenDozeTimer.logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070015195 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015196 pr.println("*** Screen brightness #" + i + ":");
15197 mScreenBrightnessTimer[i].logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070015198 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070015199 pr.println("*** Interactive timer:");
15200 mInteractiveTimer.logState(pr, " ");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070015201 pr.println("*** Power save mode timer:");
15202 mPowerSaveModeEnabledTimer.logState(pr, " ");
Dianne Hackborn08c47a52015-10-15 12:38:14 -070015203 pr.println("*** Device idle mode light timer:");
15204 mDeviceIdleModeLightTimer.logState(pr, " ");
15205 pr.println("*** Device idle mode full timer:");
15206 mDeviceIdleModeFullTimer.logState(pr, " ");
15207 pr.println("*** Device light idling timer:");
15208 mDeviceLightIdlingTimer.logState(pr, " ");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070015209 pr.println("*** Device idling timer:");
15210 mDeviceIdlingTimer.logState(pr, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015211 pr.println("*** Phone timer:");
15212 mPhoneOnTimer.logState(pr, " ");
Wink Saville52840902011-02-18 12:40:47 -080015213 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3251b902014-06-20 14:40:53 -070015214 pr.println("*** Phone signal strength #" + i + ":");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015215 mPhoneSignalStrengthsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070015216 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070015217 pr.println("*** Signal scanning :");
15218 mPhoneSignalScanningTimer.logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070015219 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015220 pr.println("*** Data connection type #" + i + ":");
15221 mPhoneDataConnectionsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070015222 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070015223 pr.println("*** mMobileRadioPowerState=" + mMobileRadioPowerState);
Dianne Hackborne13c4c02014-02-11 17:18:35 -080015224 pr.println("*** Mobile network active timer:");
15225 mMobileRadioActiveTimer.logState(pr, " ");
Dianne Hackborna1bd7922014-03-21 11:07:11 -070015226 pr.println("*** Mobile network active adjusted timer:");
15227 mMobileRadioActiveAdjustedTime.logState(pr, " ");
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080015228 pr.println("*** Wifi Multicast WakeLock Timer:");
15229 mWifiMulticastWakelockTimer.logState(pr, " ");
Dianne Hackborn0c820db2015-04-14 17:47:34 -070015230 pr.println("*** mWifiRadioPowerState=" + mWifiRadioPowerState);
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015231 pr.println("*** Wifi timer:");
15232 mWifiOnTimer.logState(pr, " ");
15233 pr.println("*** WifiRunning timer:");
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070015234 mGlobalWifiRunningTimer.logState(pr, " ");
Dianne Hackbornca1bf212014-02-14 14:18:36 -080015235 for (int i=0; i<NUM_WIFI_STATES; i++) {
15236 pr.println("*** Wifi state #" + i + ":");
15237 mWifiStateTimer[i].logState(pr, " ");
15238 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070015239 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
15240 pr.println("*** Wifi suppl state #" + i + ":");
15241 mWifiSupplStateTimer[i].logState(pr, " ");
15242 }
15243 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
15244 pr.println("*** Wifi signal strength #" + i + ":");
15245 mWifiSignalStrengthsTimer[i].logState(pr, " ");
15246 }
Siddharth Ray78ccaf52017-12-23 16:16:21 -080015247 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
15248 pr.println("*** GPS signal quality #" + i + ":");
15249 mGpsSignalQualityTimer[i].logState(pr, " ");
15250 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -070015251 pr.println("*** Flashlight timer:");
15252 mFlashlightOnTimer.logState(pr, " ");
Ruben Brunk6d2c3632015-05-26 17:32:16 -070015253 pr.println("*** Camera timer:");
15254 mCameraOnTimer.logState(pr, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015255 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -080015256 super.dumpLocked(context, pw, flags, reqUid, histStart);
Sudheer Shankac20379e2018-02-15 00:06:21 -080015257 pw.print("Total cpu time reads: ");
Mike Ma234d1822018-03-13 18:53:21 -070015258 pw.println(mNumSingleUidCpuTimeReads);
Sudheer Shankac20379e2018-02-15 00:06:21 -080015259 pw.print("Batched cpu time reads: ");
Mike Ma234d1822018-03-13 18:53:21 -070015260 pw.println(mNumBatchedSingleUidCpuTimeReads);
Sudheer Shankac20379e2018-02-15 00:06:21 -080015261 pw.print("Batching Duration (min): ");
15262 pw.println((mClocks.uptimeMillis() - mCpuTimeReadsTrackingStartTime) / (60 * 1000));
Mike Ma234d1822018-03-13 18:53:21 -070015263 pw.print("All UID cpu time reads since the later of device start or stats reset: ");
15264 pw.println(mNumAllUidCpuTimeReads);
15265 pw.print("UIDs removed since the later of device start or stats reset: ");
15266 pw.println(mNumUidsRemoved);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015267 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015268}