blob: b9dc677af44c27601e6970b6908099595c591aef [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006-2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.internal.os;
18
Sudheer Shanka9b735c52017-05-09 18:26:18 -070019import android.annotation.NonNull;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070020import android.annotation.Nullable;
Dianne Hackborn61659e52014-07-09 16:13:01 -070021import android.app.ActivityManager;
Adam Lesinski33dac552015-03-09 15:24:48 -070022import android.bluetooth.BluetoothActivityEnergyInfo;
Adam Lesinski50e47602015-12-04 17:04:54 -080023import android.bluetooth.UidTraffic;
Mike Mafbc01fc2018-04-02 10:28:28 -070024import android.content.BroadcastReceiver;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080025import android.content.ContentResolver;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080026import android.content.Context;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070027import android.content.Intent;
Mike Mafbc01fc2018-04-02 10:28:28 -070028import android.content.IntentFilter;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080029import android.database.ContentObserver;
Mike Mafbc01fc2018-04-02 10:28:28 -070030import android.hardware.usb.UsbManager;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070031import android.net.ConnectivityManager;
32import android.net.NetworkStats;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080033import android.net.Uri;
Adam Lesinski33dac552015-03-09 15:24:48 -070034import android.net.wifi.WifiActivityEnergyInfo;
Dianne Hackborn3251b902014-06-20 14:40:53 -070035import android.net.wifi.WifiManager;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070036import android.os.BatteryManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.os.BatteryStats;
Dianne Hackborncd0e3352014-08-07 17:08:09 -070038import android.os.Build;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070039import android.os.FileUtils;
Dianne Hackborn0d903a82010-09-07 23:51:03 -070040import android.os.Handler;
Adam Lesinskie1f480d2017-02-15 18:51:23 -080041import android.os.IBatteryPropertiesRegistrar;
Jeff Brown6f357d32014-01-15 20:40:55 -080042import android.os.Looper;
Dianne Hackborn0d903a82010-09-07 23:51:03 -070043import android.os.Message;
Bookatz1a1b0462018-01-12 11:47:03 -080044import android.os.OsProtoEnums;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.os.Parcel;
46import android.os.ParcelFormatException;
47import android.os.Parcelable;
Bookatz1a1b0462018-01-12 11:47:03 -080048import android.os.PowerManager;
Evan Millarc64edde2009-04-18 12:26:32 -070049import android.os.Process;
Adam Lesinskie1f480d2017-02-15 18:51:23 -080050import android.os.RemoteException;
51import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.os.SystemClock;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070053import android.os.UserHandle;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070054import android.os.WorkSource;
Narayan Kamath81822022017-12-08 11:56:01 +000055import android.os.WorkSource.WorkChain;
Mike Ma234d1822018-03-13 18:53:21 -070056import android.os.connectivity.CellularBatteryStats;
57import android.os.connectivity.GpsBatteryStats;
58import android.os.connectivity.WifiBatteryStats;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080059import android.provider.Settings;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070060import android.telephony.DataConnectionRealTimeInfo;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080061import android.telephony.ModemActivityInfo;
Amith Yamasanif37447b2009-10-08 18:28:01 -070062import android.telephony.ServiceState;
Wink Savillee9b06d72009-05-18 21:47:50 -070063import android.telephony.SignalStrength;
Dianne Hackborn627bba72009-03-24 22:32:56 -070064import android.telephony.TelephonyManager;
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -070065import android.text.TextUtils;
Dianne Hackborn61659e52014-07-09 16:13:01 -070066import android.util.ArrayMap;
Sudheer Shankab2f83c12017-11-13 19:25:01 -080067import android.util.IntArray;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080068import android.util.KeyValueListParser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.util.Log;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070070import android.util.LogWriter;
James Carr3a226052016-07-01 14:49:52 -070071import android.util.LongSparseArray;
72import android.util.LongSparseLongArray;
Dianne Hackbornd953c532014-08-16 18:17:38 -070073import android.util.MutableInt;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070074import android.util.Pools;
Dianne Hackborn1d442e02009-04-20 18:14:05 -070075import android.util.PrintWriterPrinter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.util.Printer;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070077import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078import android.util.SparseArray;
Dianne Hackborn099bc622014-01-22 13:39:16 -080079import android.util.SparseIntArray;
Adam Lesinskie08af192015-03-25 16:42:59 -070080import android.util.SparseLongArray;
Bookatzc1a050a2017-10-10 15:49:28 -070081import android.util.StatsLog;
Dianne Hackbornae384452011-06-28 12:33:48 -070082import android.util.TimeUtils;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080083import android.util.Xml;
Jeff Browne95c3cd2014-05-02 16:59:26 -070084import android.view.Display;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085
Adam Lesinski14ae39a2017-05-26 11:50:40 -070086import com.android.internal.annotations.GuardedBy;
Adam Lesinski98f0d462016-04-19 16:46:20 -070087import com.android.internal.annotations.VisibleForTesting;
Siddharth Ray78ccaf52017-12-23 16:16:21 -080088import com.android.internal.location.gnssmetrics.GnssMetrics;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070089import com.android.internal.net.NetworkStatsFactory;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080090import com.android.internal.util.ArrayUtils;
Dianne Hackborn8c841092013-06-24 13:46:13 -070091import com.android.internal.util.FastPrintWriter;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080092import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070093import com.android.internal.util.JournaledFile;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080094import com.android.internal.util.XmlUtils;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070095
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070096import libcore.util.EmptyArray;
Mike Ma234d1822018-03-13 18:53:21 -070097
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080098import org.xmlpull.v1.XmlPullParser;
99import org.xmlpull.v1.XmlPullParserException;
100import org.xmlpull.v1.XmlSerializer;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700101
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800102import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103import java.io.File;
104import java.io.FileInputStream;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800105import java.io.FileNotFoundException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import java.io.FileOutputStream;
107import java.io.IOException;
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700108import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100109import java.nio.charset.StandardCharsets;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import java.util.ArrayList;
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700111import java.util.Arrays;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800112import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113import java.util.HashMap;
Evan Millarc64edde2009-04-18 12:26:32 -0700114import java.util.Iterator;
Mike Ma234d1822018-03-13 18:53:21 -0700115import java.util.LinkedList;
116import java.util.List;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117import java.util.Map;
Mike Ma234d1822018-03-13 18:53:21 -0700118import java.util.Queue;
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700119import java.util.concurrent.Future;
Christopher Tate4cee7252010-03-19 14:50:40 -0700120import java.util.concurrent.atomic.AtomicInteger;
Dianne Hackbornce2ef762010-09-20 11:39:14 -0700121import java.util.concurrent.locks.ReentrantLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122
123/**
124 * All information we are collecting about things that can happen that impact
125 * battery life. All times are represented in microseconds except where indicated
126 * otherwise.
127 */
Joe Onoratoabded112016-02-08 16:49:39 -0800128public class BatteryStatsImpl extends BatteryStats {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129 private static final String TAG = "BatteryStatsImpl";
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800130 private static final boolean DEBUG = false;
Adam Lesinskia7c90c82015-06-18 14:52:24 -0700131 public static final boolean DEBUG_ENERGY = false;
Adam Lesinski50e47602015-12-04 17:04:54 -0800132 private static final boolean DEBUG_ENERGY_CPU = DEBUG_ENERGY;
James Carr3a226052016-07-01 14:49:52 -0700133 private static final boolean DEBUG_MEMORY = false;
Dianne Hackborn32907cf2010-06-10 17:50:20 -0700134 private static final boolean DEBUG_HISTORY = false;
Dianne Hackborne8c88e62011-08-17 19:09:09 -0700135 private static final boolean USE_OLD_HISTORY = false; // for debugging.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700136
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700137 // TODO: remove "tcp" from network methods, since we measure total stats.
138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139 // In-memory Parcel magic number, used to detect attempts to unmarshall bad data
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700140 private static final int MAGIC = 0xBA757475; // 'BATSTATS'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141
142 // Current on-disk Parcel version
Mike Ma561a8d92018-03-20 18:24:05 -0700143 private static final int VERSION = 177 + (USE_OLD_HISTORY ? 1000 : 0);
Amith Yamasanie43530a2009-08-21 13:11:37 -0700144
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700145 // Maximum number of items we will record in the history.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100146 private static final int MAX_HISTORY_ITEMS;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700147
Dianne Hackbornf47d8f22010-10-08 10:46:55 -0700148 // No, really, THIS is the maximum number of items we will record in the history.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100149 private static final int MAX_MAX_HISTORY_ITEMS;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -0700150
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800151 // The maximum number of names wakelocks we will keep track of
152 // per uid; once the limit is reached, we batch the remaining wakelocks
153 // in to one common name.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100154 private static final int MAX_WAKELOCKS_PER_UID;
155
156 static final int MAX_HISTORY_BUFFER; // 256KB
157 static final int MAX_MAX_HISTORY_BUFFER; // 320KB
158
159 static {
160 if (ActivityManager.isLowRamDeviceStatic()) {
161 MAX_HISTORY_ITEMS = 800;
162 MAX_MAX_HISTORY_ITEMS = 1200;
163 MAX_WAKELOCKS_PER_UID = 40;
164 MAX_HISTORY_BUFFER = 96*1024; // 96KB
165 MAX_MAX_HISTORY_BUFFER = 128*1024; // 128KB
166 } else {
Makoto Onuki44d64602018-01-18 08:44:28 -0800167 MAX_HISTORY_ITEMS = 4000;
168 MAX_MAX_HISTORY_ITEMS = 6000;
169 MAX_WAKELOCKS_PER_UID = 200;
170 MAX_HISTORY_BUFFER = 512*1024; // 512KB
171 MAX_MAX_HISTORY_BUFFER = 640*1024; // 640KB
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100172 }
173 }
Dianne Hackbornc24ab862011-10-18 15:55:03 -0700174
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800175 // Number of transmit power states the Wifi controller can be in.
176 private static final int NUM_WIFI_TX_LEVELS = 1;
177
178 // Number of transmit power states the Bluetooth controller can be in.
179 private static final int NUM_BT_TX_LEVELS = 1;
180
Sudheer Shanka38383232017-07-25 09:55:03 -0700181 /**
182 * Holding a wakelock costs more than just using the cpu.
183 * Currently, we assign only half the cpu time to an app that is running but
184 * not holding a wakelock. The apps holding wakelocks get the rest of the blame.
185 * If no app is holding a wakelock, then the distribution is normal.
186 */
187 @VisibleForTesting
188 public static final int WAKE_LOCK_WEIGHT = 50;
189
Joe Onoratoabded112016-02-08 16:49:39 -0800190 protected Clocks mClocks;
191
Dianne Hackborn1afd1c92010-03-18 22:47:17 -0700192 private final JournaledFile mFile;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700193 public final AtomicFile mCheckinFile;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800194 public final AtomicFile mDailyFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195
Sudheer Shankac57729a2018-02-09 15:44:42 -0800196 static final int MSG_REPORT_CPU_UPDATE_NEEDED = 1;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700197 static final int MSG_REPORT_POWER_CHANGE = 2;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700198 static final int MSG_REPORT_CHARGING = 3;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700199 static final long DELAY_UPDATE_WAKELOCKS = 5*1000;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700200
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700201 private final KernelWakelockReader mKernelWakelockReader = new KernelWakelockReader();
202 private final KernelWakelockStats mTmpWakelockStats = new KernelWakelockStats();
203
Sudheer Shanka38383232017-07-25 09:55:03 -0700204 @VisibleForTesting
205 protected KernelUidCpuTimeReader mKernelUidCpuTimeReader = new KernelUidCpuTimeReader();
206 @VisibleForTesting
207 protected KernelCpuSpeedReader[] mKernelCpuSpeedReaders;
208 @VisibleForTesting
209 protected KernelUidCpuFreqTimeReader mKernelUidCpuFreqTimeReader =
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700210 new KernelUidCpuFreqTimeReader();
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800211 @VisibleForTesting
Mike Ma3d422c32017-10-25 11:08:57 -0700212 protected KernelUidCpuActiveTimeReader mKernelUidCpuActiveTimeReader =
213 new KernelUidCpuActiveTimeReader();
214 @VisibleForTesting
215 protected KernelUidCpuClusterTimeReader mKernelUidCpuClusterTimeReader =
216 new KernelUidCpuClusterTimeReader();
217 @VisibleForTesting
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800218 protected KernelSingleUidTimeReader mKernelSingleUidTimeReader;
Adam Lesinski06af1fa2015-05-05 17:35:35 -0700219
James Carr3a226052016-07-01 14:49:52 -0700220 private final KernelMemoryBandwidthStats mKernelMemoryBandwidthStats
221 = new KernelMemoryBandwidthStats();
222 private final LongSparseArray<SamplingTimer> mKernelMemoryStats = new LongSparseArray<>();
223 public LongSparseArray<SamplingTimer> getKernelMemoryStats() {
224 return mKernelMemoryStats;
225 }
226
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800227 @GuardedBy("this")
228 public boolean mPerProcStateCpuTimesAvailable = true;
229
230 /**
231 * Uids for which per-procstate cpu times need to be updated.
232 *
233 * Contains uid -> procState mappings.
234 */
235 @GuardedBy("this")
236 @VisibleForTesting
237 protected final SparseIntArray mPendingUids = new SparseIntArray();
238
Sudheer Shankac20379e2018-02-15 00:06:21 -0800239 @GuardedBy("this")
Mike Ma234d1822018-03-13 18:53:21 -0700240 private long mNumSingleUidCpuTimeReads;
Sudheer Shankac20379e2018-02-15 00:06:21 -0800241 @GuardedBy("this")
Mike Ma234d1822018-03-13 18:53:21 -0700242 private long mNumBatchedSingleUidCpuTimeReads;
Sudheer Shankac20379e2018-02-15 00:06:21 -0800243 @GuardedBy("this")
244 private long mCpuTimeReadsTrackingStartTime = SystemClock.uptimeMillis();
Mike Ma234d1822018-03-13 18:53:21 -0700245 @GuardedBy("this")
246 private int mNumUidsRemoved;
247 @GuardedBy("this")
248 private int mNumAllUidCpuTimeReads;
Sudheer Shankac20379e2018-02-15 00:06:21 -0800249
Bookatz0b8a0502017-09-13 11:51:52 -0700250 /** Container for Resource Power Manager stats. Updated by updateRpmStatsLocked. */
Bookatz50df7112017-08-04 14:53:26 -0700251 private final RpmStats mTmpRpmStats = new RpmStats();
Bookatz0b8a0502017-09-13 11:51:52 -0700252 /** The soonest the RPM stats can be updated after it was last updated. */
253 private static final long RPM_STATS_UPDATE_FREQ_MS = 1000;
254 /** Last time that RPM stats were updated by updateRpmStatsLocked. */
255 private long mLastRpmStatsUpdateTimeMs = -RPM_STATS_UPDATE_FREQ_MS;
Mike Ma234d1822018-03-13 18:53:21 -0700256 /**
257 * Use a queue to delay removing UIDs from {@link KernelUidCpuTimeReader},
258 * {@link KernelUidCpuActiveTimeReader}, {@link KernelUidCpuClusterTimeReader},
259 * {@link KernelUidCpuFreqTimeReader} and from the Kernel.
260 *
261 * Isolated and invalid UID info must be removed to conserve memory. However, STATSD and
262 * Batterystats both need to access UID cpu time. To resolve this race condition, only
263 * Batterystats shall remove UIDs, and a delay {@link Constants#UID_REMOVE_DELAY_MS} is
264 * implemented so that STATSD can capture those UID times before they are deleted.
265 */
266 @GuardedBy("this")
267 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
268 protected Queue<UidToRemove> mPendingRemovedUids = new LinkedList<>();
269
270 @VisibleForTesting
271 public final class UidToRemove {
272 int startUid;
273 int endUid;
274 long timeAddedInQueue;
275
276 /** Remove just one UID */
277 public UidToRemove(int uid, long timestamp) {
278 this(uid, uid, timestamp);
279 }
280
281 /** Remove a range of UIDs, startUid must be smaller than endUid. */
282 public UidToRemove(int startUid, int endUid, long timestamp) {
283 this.startUid = startUid;
284 this.endUid = endUid;
285 timeAddedInQueue = timestamp;
286 }
287
288 void remove() {
289 if (startUid == endUid) {
290 mKernelUidCpuTimeReader.removeUid(startUid);
291 mKernelUidCpuFreqTimeReader.removeUid(startUid);
292 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
293 mKernelUidCpuActiveTimeReader.removeUid(startUid);
294 mKernelUidCpuClusterTimeReader.removeUid(startUid);
295 }
296 if (mKernelSingleUidTimeReader != null) {
297 mKernelSingleUidTimeReader.removeUid(startUid);
298 }
299 mNumUidsRemoved++;
300 } else if (startUid < endUid) {
301 mKernelUidCpuFreqTimeReader.removeUidsInRange(startUid, endUid);
302 mKernelUidCpuTimeReader.removeUidsInRange(startUid, endUid);
303 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
304 mKernelUidCpuActiveTimeReader.removeUidsInRange(startUid, endUid);
305 mKernelUidCpuClusterTimeReader.removeUidsInRange(startUid, endUid);
306 }
307 if (mKernelSingleUidTimeReader != null) {
308 mKernelSingleUidTimeReader.removeUidsInRange(startUid, endUid);
309 }
310 // Treat as one. We don't know how many uids there are in between.
311 mNumUidsRemoved++;
312 } else {
313 Slog.w(TAG, "End UID " + endUid + " is smaller than start UID " + startUid);
314 }
315 }
316 }
Bookatz50df7112017-08-04 14:53:26 -0700317
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700318 public interface BatteryCallback {
319 public void batteryNeedsCpuUpdate();
320 public void batteryPowerChanged(boolean onBattery);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700321 public void batterySendBroadcast(Intent intent);
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700322 }
323
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700324 public interface PlatformIdleStateCallback {
Bookatz50df7112017-08-04 14:53:26 -0700325 public void fillLowPowerStats(RpmStats rpmStats);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700326 public String getPlatformLowPowerStats();
Ahmed ElArabawyd8b44112017-05-23 21:25:02 +0000327 public String getSubsystemLowPowerStats();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700328 }
329
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700330 public static abstract class UserInfoProvider {
331 private int[] userIds;
332 protected abstract @Nullable int[] getUserIds();
Sudheer Shanka38383232017-07-25 09:55:03 -0700333 @VisibleForTesting
334 public final void refreshUserIds() {
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700335 userIds = getUserIds();
336 }
Sudheer Shanka38383232017-07-25 09:55:03 -0700337 @VisibleForTesting
338 public boolean exists(int userId) {
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700339 return userIds != null ? ArrayUtils.contains(userIds, userId) : true;
340 }
341 }
342
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700343 private final PlatformIdleStateCallback mPlatformIdleStateCallback;
344
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700345 final class MyHandler extends Handler {
Jeff Brown6f357d32014-01-15 20:40:55 -0800346 public MyHandler(Looper looper) {
347 super(looper, null, true);
348 }
349
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700350 @Override
351 public void handleMessage(Message msg) {
352 BatteryCallback cb = mCallback;
353 switch (msg.what) {
Sudheer Shankac57729a2018-02-09 15:44:42 -0800354 case MSG_REPORT_CPU_UPDATE_NEEDED:
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700355 if (cb != null) {
356 cb.batteryNeedsCpuUpdate();
357 }
358 break;
359 case MSG_REPORT_POWER_CHANGE:
360 if (cb != null) {
361 cb.batteryPowerChanged(msg.arg1 != 0);
362 }
363 break;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700364 case MSG_REPORT_CHARGING:
365 if (cb != null) {
366 final String action;
367 synchronized (BatteryStatsImpl.this) {
368 action = mCharging ? BatteryManager.ACTION_CHARGING
369 : BatteryManager.ACTION_DISCHARGING;
370 }
371 Intent intent = new Intent(action);
372 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
373 cb.batterySendBroadcast(intent);
374 }
375 break;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700376 }
377 }
378 }
379
Sudheer Shankac57729a2018-02-09 15:44:42 -0800380 public void postBatteryNeedsCpuUpdateMsg() {
381 mHandler.sendEmptyMessage(MSG_REPORT_CPU_UPDATE_NEEDED);
382 }
383
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800384 /**
385 * Update per-freq cpu times for all the uids in {@link #mPendingUids}.
386 */
Sudheer Shankae544d162017-12-28 17:06:20 -0800387 public void updateProcStateCpuTimes(boolean onBattery, boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800388 final SparseIntArray uidStates;
389 synchronized (BatteryStatsImpl.this) {
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800390 if (!mConstants.TRACK_CPU_TIMES_BY_PROC_STATE) {
391 return;
392 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800393 if(!initKernelSingleUidTimeReaderLocked()) {
394 return;
395 }
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800396 // If the KernelSingleUidTimeReader has stale cpu times, then we shouldn't try to
397 // compute deltas since it might result in mis-attributing cpu times to wrong states.
398 if (mKernelSingleUidTimeReader.hasStaleData()) {
399 mPendingUids.clear();
400 return;
401 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800402
403 if (mPendingUids.size() == 0) {
404 return;
405 }
406 uidStates = mPendingUids.clone();
407 mPendingUids.clear();
408 }
409 for (int i = uidStates.size() - 1; i >= 0; --i) {
410 final int uid = uidStates.keyAt(i);
411 final int procState = uidStates.valueAt(i);
412 final int[] isolatedUids;
413 final Uid u;
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800414 synchronized (BatteryStatsImpl.this) {
415 // It's possible that uid no longer exists and any internal references have
416 // already been deleted, so using {@link #getAvailableUidStatsLocked} to avoid
417 // creating an UidStats object if it doesn't already exist.
418 u = getAvailableUidStatsLocked(uid);
419 if (u == null) {
420 continue;
421 }
422 if (u.mChildUids == null) {
423 isolatedUids = null;
424 } else {
425 isolatedUids = u.mChildUids.toArray();
426 for (int j = isolatedUids.length - 1; j >= 0; --j) {
427 isolatedUids[j] = u.mChildUids.get(j);
428 }
429 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800430 }
431 long[] cpuTimesMs = mKernelSingleUidTimeReader.readDeltaMs(uid);
432 if (isolatedUids != null) {
433 for (int j = isolatedUids.length - 1; j >= 0; --j) {
434 cpuTimesMs = addCpuTimes(cpuTimesMs,
435 mKernelSingleUidTimeReader.readDeltaMs(isolatedUids[j]));
436 }
437 }
438 if (onBattery && cpuTimesMs != null) {
439 synchronized (BatteryStatsImpl.this) {
Sudheer Shankae544d162017-12-28 17:06:20 -0800440 u.addProcStateTimesMs(procState, cpuTimesMs, onBattery);
441 u.addProcStateScreenOffTimesMs(procState, cpuTimesMs, onBatteryScreenOff);
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800442 }
443 }
444 }
445 }
446
Mike Ma234d1822018-03-13 18:53:21 -0700447 public void clearPendingRemovedUids() {
448 long cutOffTime = mClocks.elapsedRealtime() - mConstants.UID_REMOVE_DELAY_MS;
449 while (!mPendingRemovedUids.isEmpty()
450 && mPendingRemovedUids.peek().timeAddedInQueue < cutOffTime) {
451 mPendingRemovedUids.poll().remove();
452 }
453 }
454
Sudheer Shankae544d162017-12-28 17:06:20 -0800455 public void copyFromAllUidsCpuTimes() {
456 synchronized (BatteryStatsImpl.this) {
457 copyFromAllUidsCpuTimes(
458 mOnBatteryTimeBase.isRunning(), mOnBatteryScreenOffTimeBase.isRunning());
459 }
460 }
461
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800462 /**
463 * When the battery/screen state changes, we don't attribute the cpu times to any process
464 * but we still need to snapshots of all uids to get correct deltas later on. Since we
465 * already read this data for updating per-freq cpu times, we can use the same data for
466 * per-procstate cpu times.
467 */
Sudheer Shankae544d162017-12-28 17:06:20 -0800468 public void copyFromAllUidsCpuTimes(boolean onBattery, boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800469 synchronized (BatteryStatsImpl.this) {
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800470 if (!mConstants.TRACK_CPU_TIMES_BY_PROC_STATE) {
471 return;
472 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800473 if(!initKernelSingleUidTimeReaderLocked()) {
474 return;
475 }
476
477 final SparseArray<long[]> allUidCpuFreqTimesMs =
478 mKernelUidCpuFreqTimeReader.getAllUidCpuFreqTimeMs();
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800479 // If the KernelSingleUidTimeReader has stale cpu times, then we shouldn't try to
480 // compute deltas since it might result in mis-attributing cpu times to wrong states.
481 if (mKernelSingleUidTimeReader.hasStaleData()) {
482 mKernelSingleUidTimeReader.setAllUidsCpuTimesMs(allUidCpuFreqTimesMs);
483 mKernelSingleUidTimeReader.markDataAsStale(false);
484 mPendingUids.clear();
485 return;
486 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800487 for (int i = allUidCpuFreqTimesMs.size() - 1; i >= 0; --i) {
488 final int uid = allUidCpuFreqTimesMs.keyAt(i);
489 final Uid u = getAvailableUidStatsLocked(mapUid(uid));
490 if (u == null) {
491 continue;
492 }
493 final long[] cpuTimesMs = allUidCpuFreqTimesMs.valueAt(i);
494 if (cpuTimesMs == null) {
495 continue;
496 }
497 final long[] deltaTimesMs = mKernelSingleUidTimeReader.computeDelta(
498 uid, cpuTimesMs.clone());
Sudheer Shankae544d162017-12-28 17:06:20 -0800499 if (onBattery && deltaTimesMs != null) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800500 final int procState;
501 final int idx = mPendingUids.indexOfKey(uid);
502 if (idx >= 0) {
503 procState = mPendingUids.valueAt(idx);
504 mPendingUids.removeAt(idx);
505 } else {
506 procState = u.mProcessState;
507 }
508 if (procState >= 0 && procState < Uid.NUM_PROCESS_STATE) {
Sudheer Shankae544d162017-12-28 17:06:20 -0800509 u.addProcStateTimesMs(procState, deltaTimesMs, onBattery);
510 u.addProcStateScreenOffTimesMs(procState, deltaTimesMs, onBatteryScreenOff);
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800511 }
512 }
513 }
514 }
515 }
516
517 @VisibleForTesting
518 public long[] addCpuTimes(long[] timesA, long[] timesB) {
519 if (timesA != null && timesB != null) {
520 for (int i = timesA.length - 1; i >= 0; --i) {
521 timesA[i] += timesB[i];
522 }
523 return timesA;
524 }
525 return timesA == null ? (timesB == null ? null : timesB) : timesA;
526 }
527
528 @GuardedBy("this")
529 private boolean initKernelSingleUidTimeReaderLocked() {
530 if (mKernelSingleUidTimeReader == null) {
531 if (mPowerProfile == null) {
532 return false;
533 }
534 if (mCpuFreqs == null) {
535 mCpuFreqs = mKernelUidCpuFreqTimeReader.readFreqs(mPowerProfile);
536 }
537 if (mCpuFreqs != null) {
538 mKernelSingleUidTimeReader = new KernelSingleUidTimeReader(mCpuFreqs.length);
539 } else {
540 mPerProcStateCpuTimesAvailable = mKernelUidCpuFreqTimeReader.allUidTimesAvailable();
541 return false;
542 }
543 }
544 mPerProcStateCpuTimesAvailable = mKernelUidCpuFreqTimeReader.allUidTimesAvailable()
545 && mKernelSingleUidTimeReader.singleUidCpuTimesAvailable();
546 return true;
547 }
548
Joe Onoratoabded112016-02-08 16:49:39 -0800549 public interface Clocks {
550 public long elapsedRealtime();
551 public long uptimeMillis();
552 }
553
554 public static class SystemClocks implements Clocks {
555 public long elapsedRealtime() {
556 return SystemClock.elapsedRealtime();
557 }
558
559 public long uptimeMillis() {
560 return SystemClock.uptimeMillis();
561 }
562 }
563
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700564 public interface ExternalStatsSync {
Adam Lesinski14ae39a2017-05-26 11:50:40 -0700565 int UPDATE_CPU = 0x01;
566 int UPDATE_WIFI = 0x02;
567 int UPDATE_RADIO = 0x04;
568 int UPDATE_BT = 0x08;
Bookatz50df7112017-08-04 14:53:26 -0700569 int UPDATE_RPM = 0x10; // 16
570 int UPDATE_ALL = UPDATE_CPU | UPDATE_WIFI | UPDATE_RADIO | UPDATE_BT | UPDATE_RPM;
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800571
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700572 Future<?> scheduleSync(String reason, int flags);
573 Future<?> scheduleCpuSyncDueToRemovedUid(int uid);
Sudheer Shankac20379e2018-02-15 00:06:21 -0800574 Future<?> scheduleReadProcStateCpuTimes(boolean onBattery, boolean onBatteryScreenOff,
575 long delayMillis);
Sudheer Shankae544d162017-12-28 17:06:20 -0800576 Future<?> scheduleCopyFromAllUidsCpuTimes(boolean onBattery, boolean onBatteryScreenOff);
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800577 Future<?> scheduleCpuSyncDueToSettingChange();
Sudheer Shankac57729a2018-02-09 15:44:42 -0800578 Future<?> scheduleCpuSyncDueToScreenStateChange(boolean onBattery,
579 boolean onBatteryScreenOff);
580 Future<?> scheduleCpuSyncDueToWakelockChange(long delayMillis);
581 void cancelCpuSyncDueToWakelockChange();
Sudheer Shanka0719c6a2018-04-24 11:12:11 -0700582 Future<?> scheduleSyncDueToBatteryLevelChange(long delayMillis);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700583 }
584
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800585 public Handler mHandler;
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700586 private ExternalStatsSync mExternalSync = null;
Sudheer Shanka38383232017-07-25 09:55:03 -0700587 @VisibleForTesting
588 protected UserInfoProvider mUserInfoProvider = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700589
590 private BatteryCallback mCallback;
591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800592 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -0800593 * Mapping isolated uids to the actual owning app uid.
594 */
595 final SparseIntArray mIsolatedUids = new SparseIntArray();
596
597 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800598 * The statistics we have collected organized by uids.
599 */
Adam Lesinski50e47602015-12-04 17:04:54 -0800600 final SparseArray<BatteryStatsImpl.Uid> mUidStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800601
602 // A set of pools of currently active timers. When a timer is queried, we will divide the
603 // elapsed time by the number of active timers to arrive at that timer's share of the time.
604 // In order to do this, we must refresh each timer whenever the number of active timers
605 // changes.
Sudheer Shanka38383232017-07-25 09:55:03 -0700606 @VisibleForTesting
607 protected ArrayList<StopwatchTimer> mPartialTimers = new ArrayList<>();
Adam Lesinskie08af192015-03-25 16:42:59 -0700608 final ArrayList<StopwatchTimer> mFullTimers = new ArrayList<>();
609 final ArrayList<StopwatchTimer> mWindowTimers = new ArrayList<>();
Jeff Brown6a8bd7b2015-06-19 15:07:51 -0700610 final ArrayList<StopwatchTimer> mDrawTimers = new ArrayList<>();
Adam Lesinskie08af192015-03-25 16:42:59 -0700611 final SparseArray<ArrayList<StopwatchTimer>> mSensorTimers = new SparseArray<>();
612 final ArrayList<StopwatchTimer> mWifiRunningTimers = new ArrayList<>();
613 final ArrayList<StopwatchTimer> mFullWifiLockTimers = new ArrayList<>();
614 final ArrayList<StopwatchTimer> mWifiMulticastTimers = new ArrayList<>();
615 final ArrayList<StopwatchTimer> mWifiScanTimers = new ArrayList<>();
616 final SparseArray<ArrayList<StopwatchTimer>> mWifiBatchedScanTimers = new SparseArray<>();
617 final ArrayList<StopwatchTimer> mAudioTurnedOnTimers = new ArrayList<>();
618 final ArrayList<StopwatchTimer> mVideoTurnedOnTimers = new ArrayList<>();
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700619 final ArrayList<StopwatchTimer> mFlashlightTurnedOnTimers = new ArrayList<>();
620 final ArrayList<StopwatchTimer> mCameraTurnedOnTimers = new ArrayList<>();
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800621 final ArrayList<StopwatchTimer> mBluetoothScanOnTimers = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800622
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700623 // Last partial timers we use for distributing CPU usage.
Sudheer Shanka38383232017-07-25 09:55:03 -0700624 @VisibleForTesting
625 protected ArrayList<StopwatchTimer> mLastPartialTimers = new ArrayList<>();
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 // These are the objects that will want to do something when the device
628 // is unplugged from power.
Joe Onoratoabded112016-02-08 16:49:39 -0800629 protected final TimeBase mOnBatteryTimeBase = new TimeBase();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800630
631 // These are the objects that will want to do something when the device
Mike Mac2f518a2017-09-19 16:06:03 -0700632 // is unplugged from power *and* the screen is off or doze.
633 protected final TimeBase mOnBatteryScreenOffTimeBase = new TimeBase();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800634
635 // Set to true when we want to distribute CPU across wakelocks for the next
636 // CPU update, even if we aren't currently running wake locks.
637 boolean mDistributeWakelockCpu;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700638
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700639 boolean mShuttingDown;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700640
Dianne Hackborn37de0982014-05-09 09:32:18 -0700641 final HistoryEventTracker mActiveEvents = new HistoryEventTracker();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800642
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700643 long mHistoryBaseTime;
Narayan Kamath695cf722017-12-21 18:32:47 +0000644 protected boolean mHaveBatteryLevel = false;
645 protected boolean mRecordingHistory = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700646 int mNumHistoryItems;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700647
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700648 final Parcel mHistoryBuffer = Parcel.obtain();
649 final HistoryItem mHistoryLastWritten = new HistoryItem();
650 final HistoryItem mHistoryLastLastWritten = new HistoryItem();
Dianne Hackborn1fadab52011-04-14 17:57:33 -0700651 final HistoryItem mHistoryReadTmp = new HistoryItem();
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700652 final HistoryItem mHistoryAddTmp = new HistoryItem();
Adam Lesinskie08af192015-03-25 16:42:59 -0700653 final HashMap<HistoryTag, Integer> mHistoryTagPool = new HashMap<>();
Dianne Hackborn099bc622014-01-22 13:39:16 -0800654 String[] mReadHistoryStrings;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -0800655 int[] mReadHistoryUids;
656 int mReadHistoryChars;
657 int mNextHistoryTagIdx = 0;
658 int mNumHistoryTagChars = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700659 int mHistoryBufferLastPos = -1;
660 boolean mHistoryOverflow = false;
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700661 int mActiveHistoryStates = 0xffffffff;
662 int mActiveHistoryStates2 = 0xffffffff;
Dianne Hackborn40c87252014-03-19 16:55:40 -0700663 long mLastHistoryElapsedRealtime = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700664 long mTrackRunningHistoryElapsedRealtime = 0;
665 long mTrackRunningHistoryUptime = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700666
667 final HistoryItem mHistoryCur = new HistoryItem();
668
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700669 HistoryItem mHistory;
670 HistoryItem mHistoryEnd;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700671 HistoryItem mHistoryLastEnd;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700672 HistoryItem mHistoryCache;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700673
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800674 // Used by computeHistoryStepDetails
675 HistoryStepDetails mLastHistoryStepDetails = null;
676 byte mLastHistoryStepLevel = 0;
677 final HistoryStepDetails mCurHistoryStepDetails = new HistoryStepDetails();
678 final HistoryStepDetails mReadHistoryStepDetails = new HistoryStepDetails();
679 final HistoryStepDetails mTmpHistoryStepDetails = new HistoryStepDetails();
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700680
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800681 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700682 * Total time (in milliseconds) spent executing in user code.
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800683 */
684 long mLastStepCpuUserTime;
685 long mCurStepCpuUserTime;
686 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700687 * Total time (in milliseconds) spent executing in kernel code.
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800688 */
689 long mLastStepCpuSystemTime;
690 long mCurStepCpuSystemTime;
691 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700692 * Times from /proc/stat (but measured in milliseconds).
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800693 */
694 long mLastStepStatUserTime;
695 long mLastStepStatSystemTime;
696 long mLastStepStatIOWaitTime;
697 long mLastStepStatIrqTime;
698 long mLastStepStatSoftIrqTime;
699 long mLastStepStatIdleTime;
700 long mCurStepStatUserTime;
701 long mCurStepStatSystemTime;
702 long mCurStepStatIOWaitTime;
703 long mCurStepStatIrqTime;
704 long mCurStepStatSoftIrqTime;
705 long mCurStepStatIdleTime;
706
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700707 private HistoryItem mHistoryIterator;
708 private boolean mReadOverflow;
709 private boolean mIteratingHistory;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 int mStartCount;
712
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -0800713 long mStartClockTime;
Dianne Hackborncd0e3352014-08-07 17:08:09 -0700714 String mStartPlatformVersion;
715 String mEndPlatformVersion;
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -0800716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800717 long mUptime;
718 long mUptimeStart;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 long mRealtime;
720 long mRealtimeStart;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700721
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800722 int mWakeLockNesting;
723 boolean mWakeLockImportant;
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700724 public boolean mRecordAllHistory;
Dianne Hackborn9a755432014-05-15 17:05:22 -0700725 boolean mNoAutoReset;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800726
Mike Mac2f518a2017-09-19 16:06:03 -0700727 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
728 protected int mScreenState = Display.STATE_UNKNOWN;
729 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
730 protected StopwatchTimer mScreenOnTimer;
731 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
732 protected StopwatchTimer mScreenDozeTimer;
Amith Yamasani3718aaa2009-06-09 06:32:35 -0700733
Dianne Hackborn617f8772009-03-31 15:04:46 -0700734 int mScreenBrightnessBin = -1;
Evan Millarc64edde2009-04-18 12:26:32 -0700735 final StopwatchTimer[] mScreenBrightnessTimer = new StopwatchTimer[NUM_SCREEN_BRIGHTNESS_BINS];
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700736
Amith Yamasani674c9bb2017-02-01 09:45:17 -0800737 boolean mPretendScreenOff;
738
Jeff Browne95c3cd2014-05-02 16:59:26 -0700739 boolean mInteractive;
740 StopwatchTimer mInteractiveTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700741
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700742 boolean mPowerSaveModeEnabled;
743 StopwatchTimer mPowerSaveModeEnabledTimer;
744
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700745 boolean mDeviceIdling;
746 StopwatchTimer mDeviceIdlingTimer;
747
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700748 boolean mDeviceLightIdling;
749 StopwatchTimer mDeviceLightIdlingTimer;
750
751 int mDeviceIdleMode;
752 long mLastIdleTimeStart;
753 long mLongestLightIdleTime;
754 long mLongestFullIdleTime;
755 StopwatchTimer mDeviceIdleModeLightTimer;
756 StopwatchTimer mDeviceIdleModeFullTimer;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 boolean mPhoneOn;
Evan Millarc64edde2009-04-18 12:26:32 -0700759 StopwatchTimer mPhoneOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700760
Dianne Hackborn10eaa852014-07-22 22:54:55 -0700761 int mAudioOnNesting;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700762 StopwatchTimer mAudioOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700763
Dianne Hackborn10eaa852014-07-22 22:54:55 -0700764 int mVideoOnNesting;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700765 StopwatchTimer mVideoOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700766
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700767 int mFlashlightOnNesting;
Dianne Hackbornabc7c492014-06-30 16:57:46 -0700768 StopwatchTimer mFlashlightOnTimer;
769
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700770 int mCameraOnNesting;
771 StopwatchTimer mCameraOnTimer;
772
Mike Mafbc01fc2018-04-02 10:28:28 -0700773 private static final int USB_DATA_UNKNOWN = 0;
774 private static final int USB_DATA_DISCONNECTED = 1;
775 private static final int USB_DATA_CONNECTED = 2;
776 int mUsbDataState = USB_DATA_UNKNOWN;
Mike Ma926a97c2018-03-25 02:32:35 -0700777
Siddharth Ray78ccaf52017-12-23 16:16:21 -0800778 int mGpsSignalQualityBin = -1;
Narayan Kamathefa0fe62018-02-05 16:04:43 +0000779 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
780 protected final StopwatchTimer[] mGpsSignalQualityTimer =
Siddharth Ray78ccaf52017-12-23 16:16:21 -0800781 new StopwatchTimer[GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS];
782
Dianne Hackborn627bba72009-03-24 22:32:56 -0700783 int mPhoneSignalStrengthBin = -1;
Dianne Hackborne4a59512010-12-07 11:08:07 -0800784 int mPhoneSignalStrengthBinRaw = -1;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700785 final StopwatchTimer[] mPhoneSignalStrengthsTimer =
Wink Saville52840902011-02-18 12:40:47 -0800786 new StopwatchTimer[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
Amith Yamasanif37447b2009-10-08 18:28:01 -0700787
788 StopwatchTimer mPhoneSignalScanningTimer;
789
Dianne Hackborn627bba72009-03-24 22:32:56 -0700790 int mPhoneDataConnectionType = -1;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700791 final StopwatchTimer[] mPhoneDataConnectionsTimer =
Evan Millarc64edde2009-04-18 12:26:32 -0700792 new StopwatchTimer[NUM_DATA_CONNECTION_TYPES];
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700793
Dianne Hackborn57ed6a62013-12-09 18:15:56 -0800794 final LongSamplingCounter[] mNetworkByteActivityCounters =
795 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
796 final LongSamplingCounter[] mNetworkPacketActivityCounters =
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700797 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
798
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800799 /**
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -0800800 * The WiFi Overall wakelock timer
801 * This timer tracks the actual aggregate time for which MC wakelocks are enabled
802 * since addition of per UID timers would not result in an accurate value due to overlapp of
803 * per uid wakelock timers
804 */
805 StopwatchTimer mWifiMulticastWakelockTimer;
806
807 /**
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800808 * The WiFi controller activity (time in tx, rx, idle, and power consumed) for the device.
809 */
810 ControllerActivityCounterImpl mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -0700811
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800812 /**
813 * The Bluetooth controller activity (time in tx, rx, idle, and power consumed) for the device.
814 */
815 ControllerActivityCounterImpl mBluetoothActivity;
816
817 /**
818 * The Modem controller activity (time in tx, rx, idle, and power consumed) for the device.
819 */
820 ControllerActivityCounterImpl mModemActivity;
821
822 /**
823 * Whether the device supports WiFi controller energy reporting. This is set to true on
824 * the first WiFi energy report. See {@link #mWifiActivity}.
825 */
826 boolean mHasWifiReporting = false;
827
828 /**
829 * Whether the device supports Bluetooth controller energy reporting. This is set to true on
830 * the first Bluetooth energy report. See {@link #mBluetoothActivity}.
831 */
832 boolean mHasBluetoothReporting = false;
833
834 /**
835 * Whether the device supports Modem controller energy reporting. This is set to true on
836 * the first Modem energy report. See {@link #mModemActivity}.
837 */
838 boolean mHasModemReporting = false;
Adam Lesinski33dac552015-03-09 15:24:48 -0700839
The Android Open Source Project10592532009-03-18 17:39:46 -0700840 boolean mWifiOn;
Evan Millarc64edde2009-04-18 12:26:32 -0700841 StopwatchTimer mWifiOnTimer;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -0700842
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700843 boolean mGlobalWifiRunning;
844 StopwatchTimer mGlobalWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700845
Dianne Hackbornca1bf212014-02-14 14:18:36 -0800846 int mWifiState = -1;
847 final StopwatchTimer[] mWifiStateTimer = new StopwatchTimer[NUM_WIFI_STATES];
848
Dianne Hackborn3251b902014-06-20 14:40:53 -0700849 int mWifiSupplState = -1;
850 final StopwatchTimer[] mWifiSupplStateTimer = new StopwatchTimer[NUM_WIFI_SUPPL_STATES];
851
852 int mWifiSignalStrengthBin = -1;
853 final StopwatchTimer[] mWifiSignalStrengthsTimer =
854 new StopwatchTimer[NUM_WIFI_SIGNAL_STRENGTH_BINS];
855
Siddharth Rayb50a6842017-12-14 15:15:28 -0800856 StopwatchTimer mWifiActiveTimer;
857
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800858 int mBluetoothScanNesting;
Bookatz867c0d72017-03-07 18:23:42 -0800859 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
860 protected StopwatchTimer mBluetoothScanTimer;
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800861
Siddharth Rayf5e796a2018-01-22 18:18:17 -0800862 boolean mIsCellularTxPowerHigh = false;
863
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700864 int mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackbornf7097a52014-05-13 09:56:14 -0700865 long mMobileRadioActiveStartTime;
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800866 StopwatchTimer mMobileRadioActiveTimer;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800867 StopwatchTimer mMobileRadioActivePerAppTimer;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700868 LongSamplingCounter mMobileRadioActiveAdjustedTime;
Dianne Hackbornd45665b2014-02-26 12:35:32 -0800869 LongSamplingCounter mMobileRadioActiveUnknownTime;
870 LongSamplingCounter mMobileRadioActiveUnknownCount;
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800871
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700872 int mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
873
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800874 /**
875 * These provide time bases that discount the time the device is plugged
876 * in to power.
877 */
878 boolean mOnBattery;
Sudheer Shanka38383232017-07-25 09:55:03 -0700879 @VisibleForTesting
880 protected boolean mOnBatteryInternal;
Amith Yamasani3718aaa2009-06-09 06:32:35 -0700881
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700882 /**
883 * External reporting of whether the device is actually charging.
884 */
885 boolean mCharging = true;
886 int mLastChargingStateLevel;
887
The Android Open Source Project10592532009-03-18 17:39:46 -0700888 /*
889 * These keep track of battery levels (1-100) at the last plug event and the last unplug event.
890 */
Evan Millar633a1742009-04-02 16:36:33 -0700891 int mDischargeStartLevel;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700892 int mDischargeUnplugLevel;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700893 int mDischargePlugLevel;
Evan Millar633a1742009-04-02 16:36:33 -0700894 int mDischargeCurrentLevel;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700895 int mCurrentBatteryLevel;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -0700896 int mLowDischargeAmountSinceCharge;
897 int mHighDischargeAmountSinceCharge;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -0800898 int mDischargeScreenOnUnplugLevel;
899 int mDischargeScreenOffUnplugLevel;
Mike Mac2f518a2017-09-19 16:06:03 -0700900 int mDischargeScreenDozeUnplugLevel;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -0800901 int mDischargeAmountScreenOn;
902 int mDischargeAmountScreenOnSinceCharge;
903 int mDischargeAmountScreenOff;
904 int mDischargeAmountScreenOffSinceCharge;
Mike Mac2f518a2017-09-19 16:06:03 -0700905 int mDischargeAmountScreenDoze;
906 int mDischargeAmountScreenDozeSinceCharge;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700907
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700908 private LongSamplingCounter mDischargeScreenOffCounter;
Mike Mac2f518a2017-09-19 16:06:03 -0700909 private LongSamplingCounter mDischargeScreenDozeCounter;
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700910 private LongSamplingCounter mDischargeCounter;
Mike Ma15313c92017-11-15 17:58:21 -0800911 private LongSamplingCounter mDischargeLightDozeCounter;
912 private LongSamplingCounter mDischargeDeepDozeCounter;
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700913
Dianne Hackborncd0e3352014-08-07 17:08:09 -0700914 static final int MAX_LEVEL_STEPS = 200;
Dianne Hackborn260c5022014-04-29 11:23:16 -0700915
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700916 int mInitStepMode = 0;
917 int mCurStepMode = 0;
918 int mModStepMode = 0;
919
Dianne Hackborn260c5022014-04-29 11:23:16 -0700920 int mLastDischargeStepLevel;
Dianne Hackborn29325132014-05-21 15:01:03 -0700921 int mMinDischargeStepLevel;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800922 final LevelStepTracker mDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS);
923 final LevelStepTracker mDailyDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700924 ArrayList<PackageChange> mDailyPackageChanges;
Dianne Hackborn260c5022014-04-29 11:23:16 -0700925
926 int mLastChargeStepLevel;
Dianne Hackborn29325132014-05-21 15:01:03 -0700927 int mMaxChargeStepLevel;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800928 final LevelStepTracker mChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS);
929 final LevelStepTracker mDailyChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2);
930
931 static final int MAX_DAILY_ITEMS = 10;
932
933 long mDailyStartTime = 0;
934 long mNextMinDailyDeadline = 0;
935 long mNextMaxDailyDeadline = 0;
936
937 final ArrayList<DailyItem> mDailyItems = new ArrayList<>();
Dianne Hackborn260c5022014-04-29 11:23:16 -0700938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800939 long mLastWriteTime = 0; // Milliseconds
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700940
Amith Yamasanif37447b2009-10-08 18:28:01 -0700941 private int mPhoneServiceState = -1;
Dianne Hackborne4a59512010-12-07 11:08:07 -0800942 private int mPhoneServiceStateRaw = -1;
943 private int mPhoneSimStateRaw = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -0700944
Dianne Hackborn1e01d162014-12-04 17:46:42 -0800945 private int mNumConnectivityChange;
946 private int mLoadedNumConnectivityChange;
947 private int mUnpluggedNumConnectivityChange;
948
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700949 private int mEstimatedBatteryCapacity = -1;
950
Jocelyn Dangc627d102017-04-14 13:15:14 -0700951 private int mMinLearnedBatteryCapacity = -1;
952 private int mMaxLearnedBatteryCapacity = -1;
Adam Lesinski041d9172016-12-12 12:03:56 -0800953
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700954 private long[] mCpuFreqs;
955
Sudheer Shanka38383232017-07-25 09:55:03 -0700956 @VisibleForTesting
957 protected PowerProfile mPowerProfile;
Adam Lesinskie08af192015-03-25 16:42:59 -0700958
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800959 @GuardedBy("this")
960 private final Constants mConstants;
961
Evan Millarc64edde2009-04-18 12:26:32 -0700962 /*
Bookatz50df7112017-08-04 14:53:26 -0700963 * Holds a SamplingTimer associated with each Resource Power Manager state and voter,
964 * recording their times when on-battery (regardless of screen state).
965 */
966 private final HashMap<String, SamplingTimer> mRpmStats = new HashMap<>();
967 /** Times for each Resource Power Manager state and voter when screen-off and on-battery. */
968 private final HashMap<String, SamplingTimer> mScreenOffRpmStats = new HashMap<>();
969
970 @Override
971 public Map<String, ? extends Timer> getRpmStats() {
972 return mRpmStats;
973 }
974
Bookatz82b341172017-09-07 19:06:08 -0700975 // TODO: Note: screenOffRpmStats has been disabled via SCREEN_OFF_RPM_STATS_ENABLED.
Bookatz50df7112017-08-04 14:53:26 -0700976 @Override
977 public Map<String, ? extends Timer> getScreenOffRpmStats() {
978 return mScreenOffRpmStats;
979 }
980
981 /*
Evan Millarc64edde2009-04-18 12:26:32 -0700982 * Holds a SamplingTimer associated with each kernel wakelock name being tracked.
983 */
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700984 private final HashMap<String, SamplingTimer> mKernelWakelockStats = new HashMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700985
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700986 public Map<String, ? extends Timer> getKernelWakelockStats() {
Evan Millarc64edde2009-04-18 12:26:32 -0700987 return mKernelWakelockStats;
988 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700989
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700990 String mLastWakeupReason = null;
991 long mLastWakeupUptimeMs = 0;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -0700992 private final HashMap<String, SamplingTimer> mWakeupReasonStats = new HashMap<>();
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700993
Dianne Hackbornc3940bc2014-09-05 15:50:25 -0700994 public Map<String, ? extends Timer> getWakeupReasonStats() {
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700995 return mWakeupReasonStats;
996 }
997
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700998 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -0700999 public long getUahDischarge(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -07001000 return mDischargeCounter.getCountLocked(which);
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001001 }
1002
1003 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -07001004 public long getUahDischargeScreenOff(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -07001005 return mDischargeScreenOffCounter.getCountLocked(which);
1006 }
1007
1008 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -07001009 public long getUahDischargeScreenDoze(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -07001010 return mDischargeScreenDozeCounter.getCountLocked(which);
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001011 }
1012
Adam Lesinskif9b20a92016-06-17 17:30:01 -07001013 @Override
Mike Ma15313c92017-11-15 17:58:21 -08001014 public long getUahDischargeLightDoze(int which) {
1015 return mDischargeLightDozeCounter.getCountLocked(which);
1016 }
1017
1018 @Override
1019 public long getUahDischargeDeepDoze(int which) {
1020 return mDischargeDeepDozeCounter.getCountLocked(which);
1021 }
1022
1023 @Override
Adam Lesinskif9b20a92016-06-17 17:30:01 -07001024 public int getEstimatedBatteryCapacity() {
1025 return mEstimatedBatteryCapacity;
1026 }
1027
Jocelyn Dangc627d102017-04-14 13:15:14 -07001028 @Override
1029 public int getMinLearnedBatteryCapacity() {
1030 return mMinLearnedBatteryCapacity;
1031 }
1032
1033 @Override
1034 public int getMaxLearnedBatteryCapacity() {
1035 return mMaxLearnedBatteryCapacity;
1036 }
1037
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 public BatteryStatsImpl() {
Joe Onoratoabded112016-02-08 16:49:39 -08001039 this(new SystemClocks());
1040 }
1041
1042 public BatteryStatsImpl(Clocks clocks) {
1043 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07001044 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07001045 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08001046 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001047 mHandler = null;
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07001048 mPlatformIdleStateCallback = null;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -07001049 mUserInfoProvider = null;
Sudheer Shanka5c19b892018-01-05 17:25:46 -08001050 mConstants = new Constants(mHandler);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07001051 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 }
1053
Joe Onoratoabded112016-02-08 16:49:39 -08001054 private void init(Clocks clocks) {
1055 mClocks = clocks;
Joe Onoratoabded112016-02-08 16:49:39 -08001056 }
1057
Adam Lesinski14ae39a2017-05-26 11:50:40 -07001058 public interface TimeBaseObs {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001059 void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime);
1060 void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime);
1061 }
1062
Joe Onoratoabded112016-02-08 16:49:39 -08001063 // methods are protected not private to be VisibleForTesting
1064 public static class TimeBase {
1065 protected final ArrayList<TimeBaseObs> mObservers = new ArrayList<>();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001066
Joe Onoratoabded112016-02-08 16:49:39 -08001067 protected long mUptime;
1068 protected long mRealtime;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001069
Joe Onoratoabded112016-02-08 16:49:39 -08001070 protected boolean mRunning;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001071
Joe Onoratoabded112016-02-08 16:49:39 -08001072 protected long mPastUptime;
1073 protected long mUptimeStart;
1074 protected long mPastRealtime;
1075 protected long mRealtimeStart;
1076 protected long mUnpluggedUptime;
1077 protected long mUnpluggedRealtime;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001078
1079 public void dump(PrintWriter pw, String prefix) {
1080 StringBuilder sb = new StringBuilder(128);
1081 pw.print(prefix); pw.print("mRunning="); pw.println(mRunning);
1082 sb.setLength(0);
1083 sb.append(prefix);
1084 sb.append("mUptime=");
Dianne Hackborn4590e522014-03-24 13:36:46 -07001085 formatTimeMs(sb, mUptime / 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001086 pw.println(sb.toString());
1087 sb.setLength(0);
1088 sb.append(prefix);
1089 sb.append("mRealtime=");
Dianne Hackborn4590e522014-03-24 13:36:46 -07001090 formatTimeMs(sb, mRealtime / 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001091 pw.println(sb.toString());
1092 sb.setLength(0);
1093 sb.append(prefix);
1094 sb.append("mPastUptime=");
1095 formatTimeMs(sb, mPastUptime / 1000); sb.append("mUptimeStart=");
1096 formatTimeMs(sb, mUptimeStart / 1000);
1097 sb.append("mUnpluggedUptime="); formatTimeMs(sb, mUnpluggedUptime / 1000);
1098 pw.println(sb.toString());
1099 sb.setLength(0);
1100 sb.append(prefix);
1101 sb.append("mPastRealtime=");
1102 formatTimeMs(sb, mPastRealtime / 1000); sb.append("mRealtimeStart=");
1103 formatTimeMs(sb, mRealtimeStart / 1000);
1104 sb.append("mUnpluggedRealtime="); formatTimeMs(sb, mUnpluggedRealtime / 1000);
1105 pw.println(sb.toString());
1106 }
1107
1108 public void add(TimeBaseObs observer) {
1109 mObservers.add(observer);
1110 }
1111
1112 public void remove(TimeBaseObs observer) {
1113 if (!mObservers.remove(observer)) {
1114 Slog.wtf(TAG, "Removed unknown observer: " + observer);
1115 }
1116 }
1117
Joe Onoratoabded112016-02-08 16:49:39 -08001118 public boolean hasObserver(TimeBaseObs observer) {
1119 return mObservers.contains(observer);
1120 }
1121
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001122 public void init(long uptime, long realtime) {
1123 mRealtime = 0;
1124 mUptime = 0;
1125 mPastUptime = 0;
1126 mPastRealtime = 0;
1127 mUptimeStart = uptime;
1128 mRealtimeStart = realtime;
1129 mUnpluggedUptime = getUptime(mUptimeStart);
1130 mUnpluggedRealtime = getRealtime(mRealtimeStart);
1131 }
1132
1133 public void reset(long uptime, long realtime) {
1134 if (!mRunning) {
1135 mPastUptime = 0;
1136 mPastRealtime = 0;
1137 } else {
1138 mUptimeStart = uptime;
1139 mRealtimeStart = realtime;
Joe Onoratoabded112016-02-08 16:49:39 -08001140 // TODO: Since mUptimeStart was just reset and we are running, getUptime will
1141 // just return mPastUptime. Also, are we sure we don't want to reset that?
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001142 mUnpluggedUptime = getUptime(uptime);
Joe Onoratoabded112016-02-08 16:49:39 -08001143 // TODO: likewise.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001144 mUnpluggedRealtime = getRealtime(realtime);
1145 }
1146 }
1147
1148 public long computeUptime(long curTime, int which) {
1149 switch (which) {
1150 case STATS_SINCE_CHARGED:
1151 return mUptime + getUptime(curTime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001152 case STATS_CURRENT:
1153 return getUptime(curTime);
1154 case STATS_SINCE_UNPLUGGED:
1155 return getUptime(curTime) - mUnpluggedUptime;
1156 }
1157 return 0;
1158 }
1159
1160 public long computeRealtime(long curTime, int which) {
1161 switch (which) {
1162 case STATS_SINCE_CHARGED:
1163 return mRealtime + getRealtime(curTime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001164 case STATS_CURRENT:
1165 return getRealtime(curTime);
1166 case STATS_SINCE_UNPLUGGED:
1167 return getRealtime(curTime) - mUnpluggedRealtime;
1168 }
1169 return 0;
1170 }
1171
1172 public long getUptime(long curTime) {
1173 long time = mPastUptime;
1174 if (mRunning) {
1175 time += curTime - mUptimeStart;
1176 }
1177 return time;
1178 }
1179
1180 public long getRealtime(long curTime) {
1181 long time = mPastRealtime;
1182 if (mRunning) {
1183 time += curTime - mRealtimeStart;
1184 }
1185 return time;
1186 }
1187
1188 public long getUptimeStart() {
1189 return mUptimeStart;
1190 }
1191
1192 public long getRealtimeStart() {
1193 return mRealtimeStart;
1194 }
1195
1196 public boolean isRunning() {
1197 return mRunning;
1198 }
1199
1200 public boolean setRunning(boolean running, long uptime, long realtime) {
1201 if (mRunning != running) {
1202 mRunning = running;
1203 if (running) {
1204 mUptimeStart = uptime;
1205 mRealtimeStart = realtime;
1206 long batteryUptime = mUnpluggedUptime = getUptime(uptime);
1207 long batteryRealtime = mUnpluggedRealtime = getRealtime(realtime);
1208
1209 for (int i = mObservers.size() - 1; i >= 0; i--) {
1210 mObservers.get(i).onTimeStarted(realtime, batteryUptime, batteryRealtime);
1211 }
1212 } else {
1213 mPastUptime += uptime - mUptimeStart;
1214 mPastRealtime += realtime - mRealtimeStart;
1215
1216 long batteryUptime = getUptime(uptime);
1217 long batteryRealtime = getRealtime(realtime);
1218
1219 for (int i = mObservers.size() - 1; i >= 0; i--) {
1220 mObservers.get(i).onTimeStopped(realtime, batteryUptime, batteryRealtime);
1221 }
1222 }
1223 return true;
1224 }
1225 return false;
1226 }
1227
1228 public void readSummaryFromParcel(Parcel in) {
1229 mUptime = in.readLong();
1230 mRealtime = in.readLong();
1231 }
1232
1233 public void writeSummaryToParcel(Parcel out, long uptime, long realtime) {
1234 out.writeLong(computeUptime(uptime, STATS_SINCE_CHARGED));
1235 out.writeLong(computeRealtime(realtime, STATS_SINCE_CHARGED));
1236 }
1237
1238 public void readFromParcel(Parcel in) {
1239 mRunning = false;
1240 mUptime = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001241 mPastUptime = in.readLong();
1242 mUptimeStart = in.readLong();
Dianne Hackbornef640cd2014-03-25 14:41:05 -07001243 mRealtime = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001244 mPastRealtime = in.readLong();
1245 mRealtimeStart = in.readLong();
1246 mUnpluggedUptime = in.readLong();
1247 mUnpluggedRealtime = in.readLong();
1248 }
1249
1250 public void writeToParcel(Parcel out, long uptime, long realtime) {
1251 final long runningUptime = getUptime(uptime);
1252 final long runningRealtime = getRealtime(realtime);
1253 out.writeLong(mUptime);
1254 out.writeLong(runningUptime);
1255 out.writeLong(mUptimeStart);
Dianne Hackbornef640cd2014-03-25 14:41:05 -07001256 out.writeLong(mRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001257 out.writeLong(runningRealtime);
1258 out.writeLong(mRealtimeStart);
1259 out.writeLong(mUnpluggedUptime);
1260 out.writeLong(mUnpluggedRealtime);
1261 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 /**
Dianne Hackborn617f8772009-03-31 15:04:46 -07001265 * State for keeping track of counting information.
1266 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001267 public static class Counter extends BatteryStats.Counter implements TimeBaseObs {
Christopher Tate4cee7252010-03-19 14:50:40 -07001268 final AtomicInteger mCount = new AtomicInteger();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001269 final TimeBase mTimeBase;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001270 int mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001271 int mUnpluggedCount;
1272 int mPluggedCount;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001273
Bookatz8c6f3c52017-05-24 12:00:17 -07001274 public Counter(TimeBase timeBase, Parcel in) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001275 mTimeBase = timeBase;
Christopher Tate4cee7252010-03-19 14:50:40 -07001276 mPluggedCount = in.readInt();
1277 mCount.set(mPluggedCount);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001278 mLoadedCount = in.readInt();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001279 mUnpluggedCount = in.readInt();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001280 timeBase.add(this);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001281 }
1282
Bookatz8c6f3c52017-05-24 12:00:17 -07001283 public Counter(TimeBase timeBase) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001284 mTimeBase = timeBase;
1285 timeBase.add(this);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001286 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001287
Dianne Hackborn617f8772009-03-31 15:04:46 -07001288 public void writeToParcel(Parcel out) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001289 out.writeInt(mCount.get());
Dianne Hackborn617f8772009-03-31 15:04:46 -07001290 out.writeInt(mLoadedCount);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001291 out.writeInt(mUnpluggedCount);
1292 }
1293
Bookatz8c6f3c52017-05-24 12:00:17 -07001294 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001295 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001296 mUnpluggedCount = mPluggedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001297 }
1298
Bookatz8c6f3c52017-05-24 12:00:17 -07001299 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001300 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001301 mPluggedCount = mCount.get();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001302 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001303
Dianne Hackborn617f8772009-03-31 15:04:46 -07001304 /**
1305 * Writes a possibly null Counter to a Parcel.
1306 *
1307 * @param out the Parcel to be written to.
1308 * @param counter a Counter, or null.
1309 */
Amith Yamasani977e11f2018-02-16 11:29:54 -08001310 public static void writeCounterToParcel(Parcel out, @Nullable Counter counter) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07001311 if (counter == null) {
1312 out.writeInt(0); // indicates null
1313 return;
1314 }
1315 out.writeInt(1); // indicates non-null
1316
1317 counter.writeToParcel(out);
1318 }
1319
Amith Yamasani977e11f2018-02-16 11:29:54 -08001320 /**
1321 * Reads a Counter that was written using {@link #writeCounterToParcel(Parcel, Counter)}.
1322 * @param timeBase the timebase to assign to the Counter
1323 * @param in the parcel to read from
1324 * @return the Counter or null.
1325 */
1326 public static @Nullable Counter readCounterFromParcel(TimeBase timeBase, Parcel in) {
1327 if (in.readInt() == 0) {
1328 return null;
1329 }
1330 return new Counter(timeBase, in);
1331 }
1332
Dianne Hackborn617f8772009-03-31 15:04:46 -07001333 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001334 public int getCountLocked(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001335 int val = mCount.get();
1336 if (which == STATS_SINCE_UNPLUGGED) {
1337 val -= mUnpluggedCount;
1338 } else if (which != STATS_SINCE_CHARGED) {
1339 val -= mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001340 }
1341
1342 return val;
1343 }
1344
1345 public void logState(Printer pw, String prefix) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001346 pw.println(prefix + "mCount=" + mCount.get()
Bookatz8c6f3c52017-05-24 12:00:17 -07001347 + " mLoadedCount=" + mLoadedCount
Dianne Hackborn617f8772009-03-31 15:04:46 -07001348 + " mUnpluggedCount=" + mUnpluggedCount
1349 + " mPluggedCount=" + mPluggedCount);
1350 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001351
Bookatz8c6f3c52017-05-24 12:00:17 -07001352 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1353 public void stepAtomic() {
1354 if (mTimeBase.isRunning()) {
1355 mCount.incrementAndGet();
1356 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001357 }
1358
Bookatz4ebc0642017-05-11 12:21:19 -07001359 void addAtomic(int delta) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001360 if (mTimeBase.isRunning()) {
1361 mCount.addAndGet(delta);
1362 }
Bookatz4ebc0642017-05-11 12:21:19 -07001363 }
1364
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001365 /**
1366 * Clear state of this counter.
1367 */
1368 void reset(boolean detachIfReset) {
1369 mCount.set(0);
Bookatz8c6f3c52017-05-24 12:00:17 -07001370 mLoadedCount = mPluggedCount = mUnpluggedCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001371 if (detachIfReset) {
1372 detach();
1373 }
1374 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001375
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001376 void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001377 mTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001378 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001379
Bookatz8c6f3c52017-05-24 12:00:17 -07001380 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1381 public void writeSummaryFromParcelLocked(Parcel out) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001382 int count = mCount.get();
1383 out.writeInt(count);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001384 }
1385
Bookatz8c6f3c52017-05-24 12:00:17 -07001386 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1387 public void readSummaryFromParcelLocked(Parcel in) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001388 mLoadedCount = in.readInt();
1389 mCount.set(mLoadedCount);
Christopher Tate4cee7252010-03-19 14:50:40 -07001390 mUnpluggedCount = mPluggedCount = mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001391 }
1392 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07001393
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001394 @VisibleForTesting
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001395 public static class LongSamplingCounterArray extends LongCounterArray implements TimeBaseObs {
1396 final TimeBase mTimeBase;
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001397 public long[] mCounts;
1398 public long[] mLoadedCounts;
1399 public long[] mUnpluggedCounts;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001400
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001401 private LongSamplingCounterArray(TimeBase timeBase, Parcel in) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001402 mTimeBase = timeBase;
Sudheer Shankae544d162017-12-28 17:06:20 -08001403 mCounts = in.createLongArray();
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001404 mLoadedCounts = in.createLongArray();
1405 mUnpluggedCounts = in.createLongArray();
1406 timeBase.add(this);
1407 }
1408
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001409 public LongSamplingCounterArray(TimeBase timeBase) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001410 mTimeBase = timeBase;
1411 timeBase.add(this);
1412 }
1413
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001414 private void writeToParcel(Parcel out) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001415 out.writeLongArray(mCounts);
1416 out.writeLongArray(mLoadedCounts);
1417 out.writeLongArray(mUnpluggedCounts);
1418 }
1419
1420 @Override
1421 public void onTimeStarted(long elapsedRealTime, long baseUptime, long baseRealtime) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001422 mUnpluggedCounts = copyArray(mCounts, mUnpluggedCounts);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001423 }
1424
1425 @Override
1426 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001427 }
1428
1429 @Override
1430 public long[] getCountsLocked(int which) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001431 long[] val = copyArray(mCounts, null);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001432 if (which == STATS_SINCE_UNPLUGGED) {
1433 subtract(val, mUnpluggedCounts);
1434 } else if (which != STATS_SINCE_CHARGED) {
1435 subtract(val, mLoadedCounts);
1436 }
1437 return val;
1438 }
1439
1440 @Override
1441 public void logState(Printer pw, String prefix) {
1442 pw.println(prefix + "mCounts=" + Arrays.toString(mCounts)
1443 + " mLoadedCounts=" + Arrays.toString(mLoadedCounts)
Sudheer Shankae544d162017-12-28 17:06:20 -08001444 + " mUnpluggedCounts=" + Arrays.toString(mUnpluggedCounts));
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001445 }
1446
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001447 public void addCountLocked(long[] counts) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001448 addCountLocked(counts, mTimeBase.isRunning());
1449 }
1450
1451 public void addCountLocked(long[] counts, boolean isRunning) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001452 if (counts == null) {
1453 return;
1454 }
Sudheer Shankae544d162017-12-28 17:06:20 -08001455 if (isRunning) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001456 if (mCounts == null) {
1457 mCounts = new long[counts.length];
1458 }
1459 for (int i = 0; i < counts.length; ++i) {
1460 mCounts[i] += counts[i];
1461 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001462 }
1463 }
1464
Sudheer Shankab8ad5942017-08-08 12:16:09 -07001465 public int getSize() {
1466 return mCounts == null ? 0 : mCounts.length;
1467 }
1468
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001469 /**
1470 * Clear state of this counter.
1471 */
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001472 public void reset(boolean detachIfReset) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001473 fillArray(mCounts, 0);
1474 fillArray(mLoadedCounts, 0);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001475 fillArray(mUnpluggedCounts, 0);
1476 if (detachIfReset) {
1477 detach();
1478 }
1479 }
1480
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001481 public void detach() {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001482 mTimeBase.remove(this);
1483 }
1484
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001485 private void writeSummaryToParcelLocked(Parcel out) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001486 out.writeLongArray(mCounts);
1487 }
1488
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001489 private void readSummaryFromParcelLocked(Parcel in) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001490 mCounts = in.createLongArray();
1491 mLoadedCounts = copyArray(mCounts, mLoadedCounts);
1492 mUnpluggedCounts = copyArray(mCounts, mUnpluggedCounts);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001493 }
1494
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001495 public static void writeToParcel(Parcel out, LongSamplingCounterArray counterArray) {
1496 if (counterArray != null) {
1497 out.writeInt(1);
1498 counterArray.writeToParcel(out);
1499 } else {
1500 out.writeInt(0);
1501 }
1502 }
1503
1504 public static LongSamplingCounterArray readFromParcel(Parcel in, TimeBase timeBase) {
1505 if (in.readInt() != 0) {
1506 return new LongSamplingCounterArray(timeBase, in);
1507 } else {
1508 return null;
1509 }
1510 }
1511
1512 public static void writeSummaryToParcelLocked(Parcel out,
1513 LongSamplingCounterArray counterArray) {
1514 if (counterArray != null) {
1515 out.writeInt(1);
1516 counterArray.writeSummaryToParcelLocked(out);
1517 } else {
1518 out.writeInt(0);
1519 }
1520 }
1521
1522 public static LongSamplingCounterArray readSummaryFromParcelLocked(Parcel in,
1523 TimeBase timeBase) {
1524 if (in.readInt() != 0) {
1525 final LongSamplingCounterArray counterArray
1526 = new LongSamplingCounterArray(timeBase);
1527 counterArray.readSummaryFromParcelLocked(in);
1528 return counterArray;
1529 } else {
1530 return null;
1531 }
1532 }
1533
Bookatz8c6f3c52017-05-24 12:00:17 -07001534 private static void fillArray(long[] a, long val) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001535 if (a != null) {
1536 Arrays.fill(a, val);
1537 }
1538 }
1539
Bookatz8c6f3c52017-05-24 12:00:17 -07001540 private static void subtract(@NonNull long[] val, long[] toSubtract) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001541 if (toSubtract == null) {
1542 return;
1543 }
1544 for (int i = 0; i < val.length; i++) {
1545 val[i] -= toSubtract[i];
1546 }
1547 }
1548
Bookatz8c6f3c52017-05-24 12:00:17 -07001549 private static long[] copyArray(long[] src, long[] dest) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001550 if (src == null) {
1551 return null;
1552 } else {
1553 if (dest == null) {
1554 dest = new long[src.length];
1555 }
1556 System.arraycopy(src, 0, dest, 0, src.length);
1557 return dest;
1558 }
1559 }
1560 }
1561
Mike Ma561a8d92018-03-20 18:24:05 -07001562 @VisibleForTesting
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001563 public static class LongSamplingCounter extends LongCounter implements TimeBaseObs {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001564 final TimeBase mTimeBase;
Mike Ma561a8d92018-03-20 18:24:05 -07001565 public long mCount;
1566 public long mCurrentCount;
1567 public long mLoadedCount;
1568 public long mUnpluggedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001569
Mike Ma561a8d92018-03-20 18:24:05 -07001570 public LongSamplingCounter(TimeBase timeBase, Parcel in) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001571 mTimeBase = timeBase;
Sudheer Shankac57729a2018-02-09 15:44:42 -08001572 mCount = in.readLong();
Mike Ma561a8d92018-03-20 18:24:05 -07001573 mCurrentCount = in.readLong();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001574 mLoadedCount = in.readLong();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001575 mUnpluggedCount = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001576 timeBase.add(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001577 }
1578
Mike Ma561a8d92018-03-20 18:24:05 -07001579 public LongSamplingCounter(TimeBase timeBase) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001580 mTimeBase = timeBase;
1581 timeBase.add(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001582 }
1583
1584 public void writeToParcel(Parcel out) {
1585 out.writeLong(mCount);
Mike Ma561a8d92018-03-20 18:24:05 -07001586 out.writeLong(mCurrentCount);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001587 out.writeLong(mLoadedCount);
1588 out.writeLong(mUnpluggedCount);
1589 }
1590
1591 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001592 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Sudheer Shankac57729a2018-02-09 15:44:42 -08001593 mUnpluggedCount = mCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001594 }
1595
1596 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001597 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001598 }
1599
1600 public long getCountLocked(int which) {
Sudheer Shankac57729a2018-02-09 15:44:42 -08001601 long val = mCount;
Dianne Hackborn4590e522014-03-24 13:36:46 -07001602 if (which == STATS_SINCE_UNPLUGGED) {
1603 val -= mUnpluggedCount;
1604 } else if (which != STATS_SINCE_CHARGED) {
1605 val -= mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001606 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001607 return val;
1608 }
1609
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001610 @Override
1611 public void logState(Printer pw, String prefix) {
1612 pw.println(prefix + "mCount=" + mCount
Mike Ma561a8d92018-03-20 18:24:05 -07001613 + " mCurrentCount=" + mCurrentCount
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001614 + " mLoadedCount=" + mLoadedCount
Sudheer Shankac57729a2018-02-09 15:44:42 -08001615 + " mUnpluggedCount=" + mUnpluggedCount);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001616 }
1617
Mike Ma561a8d92018-03-20 18:24:05 -07001618 public void addCountLocked(long count) {
1619 update(mCurrentCount + count, mTimeBase.isRunning());
Sudheer Shankac57729a2018-02-09 15:44:42 -08001620 }
1621
Mike Ma561a8d92018-03-20 18:24:05 -07001622 public void addCountLocked(long count, boolean isRunning) {
1623 update(mCurrentCount + count, isRunning);
1624 }
1625
1626 public void update(long count) {
1627 update(count, mTimeBase.isRunning());
1628 }
1629
1630 public void update(long count, boolean isRunning) {
1631 if (count < mCurrentCount) {
1632 mCurrentCount = 0;
Bookatz8c6f3c52017-05-24 12:00:17 -07001633 }
Mike Ma561a8d92018-03-20 18:24:05 -07001634 if (isRunning) {
1635 mCount += count - mCurrentCount;
1636 }
1637 mCurrentCount = count;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001638 }
1639
1640 /**
1641 * Clear state of this counter.
1642 */
Mike Ma561a8d92018-03-20 18:24:05 -07001643 public void reset(boolean detachIfReset) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001644 mCount = 0;
Sudheer Shankac57729a2018-02-09 15:44:42 -08001645 mLoadedCount = mUnpluggedCount = 0;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001646 if (detachIfReset) {
1647 detach();
1648 }
1649 }
1650
Mike Ma561a8d92018-03-20 18:24:05 -07001651 public void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001652 mTimeBase.remove(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001653 }
1654
Mike Ma561a8d92018-03-20 18:24:05 -07001655 public void writeSummaryFromParcelLocked(Parcel out) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001656 out.writeLong(mCount);
1657 }
1658
Mike Ma561a8d92018-03-20 18:24:05 -07001659 public void readSummaryFromParcelLocked(Parcel in) {
1660 mCount = mUnpluggedCount= mLoadedCount = in.readLong();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001661 }
1662 }
1663
Dianne Hackborn617f8772009-03-31 15:04:46 -07001664 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 * State for keeping track of timing information.
1666 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001667 public static abstract class Timer extends BatteryStats.Timer implements TimeBaseObs {
Joe Onoratoabded112016-02-08 16:49:39 -08001668 protected final Clocks mClocks;
1669 protected final int mType;
1670 protected final TimeBase mTimeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001671
Joe Onoratoabded112016-02-08 16:49:39 -08001672 protected int mCount;
1673 protected int mLoadedCount;
1674 protected int mLastCount;
1675 protected int mUnpluggedCount;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 // Times are in microseconds for better accuracy when dividing by the
1678 // lock count, and are in "battery realtime" units.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001679
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001680 /**
1681 * The total time we have accumulated since the start of the original
1682 * boot, to the last time something interesting happened in the
1683 * current run.
1684 */
Joe Onoratoabded112016-02-08 16:49:39 -08001685 protected long mTotalTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001686
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 /**
1688 * The total time we loaded for the previous runs. Subtract this from
1689 * mTotalTime to find the time for the current run of the system.
1690 */
Joe Onoratoabded112016-02-08 16:49:39 -08001691 protected long mLoadedTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 /**
1694 * The run time of the last run of the system, as loaded from the
1695 * saved data.
1696 */
Joe Onoratoabded112016-02-08 16:49:39 -08001697 protected long mLastTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699 /**
1700 * The value of mTotalTime when unplug() was last called. Subtract
1701 * this from mTotalTime to find the time since the last unplug from
1702 * power.
1703 */
Joe Onoratoabded112016-02-08 16:49:39 -08001704 protected long mUnpluggedTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001705
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001706 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07001707 * The total time this timer has been running until the latest mark has been set.
1708 * Subtract this from mTotalTime to get the time spent running since the mark was set.
1709 */
Joe Onoratoabded112016-02-08 16:49:39 -08001710 protected long mTimeBeforeMark;
Adam Lesinskie08af192015-03-25 16:42:59 -07001711
1712 /**
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001713 * Constructs from a parcel.
1714 * @param type
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001715 * @param timeBase
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001716 * @param in
1717 */
Joe Onoratoabded112016-02-08 16:49:39 -08001718 public Timer(Clocks clocks, int type, TimeBase timeBase, Parcel in) {
1719 mClocks = clocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720 mType = type;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001721 mTimeBase = timeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001723 mCount = in.readInt();
1724 mLoadedCount = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001725 mLastCount = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 mUnpluggedCount = in.readInt();
1727 mTotalTime = in.readLong();
1728 mLoadedTime = in.readLong();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001729 mLastTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001730 mUnpluggedTime = in.readLong();
Adam Lesinskie08af192015-03-25 16:42:59 -07001731 mTimeBeforeMark = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001732 timeBase.add(this);
Dianne Hackborn29325132014-05-21 15:01:03 -07001733 if (DEBUG) Log.i(TAG, "**** READ TIMER #" + mType + ": mTotalTime=" + mTotalTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 }
1735
Joe Onoratoabded112016-02-08 16:49:39 -08001736 public Timer(Clocks clocks, int type, TimeBase timeBase) {
1737 mClocks = clocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 mType = type;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001739 mTimeBase = timeBase;
1740 timeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001741 }
Evan Millarc64edde2009-04-18 12:26:32 -07001742
1743 protected abstract long computeRunTimeLocked(long curBatteryRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001744
Evan Millarc64edde2009-04-18 12:26:32 -07001745 protected abstract int computeCurrentCountLocked();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001746
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001747 /**
1748 * Clear state of this timer. Returns true if the timer is inactive
1749 * so can be completely dropped.
1750 */
Joe Onoratoabded112016-02-08 16:49:39 -08001751 public boolean reset(boolean detachIfReset) {
Adam Lesinskie08af192015-03-25 16:42:59 -07001752 mTotalTime = mLoadedTime = mLastTime = mTimeBeforeMark = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001753 mCount = mLoadedCount = mLastCount = 0;
1754 if (detachIfReset) {
1755 detach();
1756 }
1757 return true;
1758 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001759
Joe Onoratoabded112016-02-08 16:49:39 -08001760 public void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001761 mTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001762 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001763
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001764 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
Dianne Hackborn29325132014-05-21 15:01:03 -07001765 if (DEBUG) Log.i(TAG, "**** WRITING TIMER #" + mType + ": mTotalTime="
1766 + computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)));
Adam Lesinski98f0d462016-04-19 16:46:20 -07001767 out.writeInt(computeCurrentCountLocked());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 out.writeInt(mLoadedCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 out.writeInt(mUnpluggedCount);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001770 out.writeLong(computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001771 out.writeLong(mLoadedTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001772 out.writeLong(mUnpluggedTime);
Adam Lesinskie08af192015-03-25 16:42:59 -07001773 out.writeLong(mTimeBeforeMark);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 }
1775
Adam Lesinskie08af192015-03-25 16:42:59 -07001776 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001777 public void onTimeStarted(long elapsedRealtime, long timeBaseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001778 if (DEBUG && mType < 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001779 Log.v(TAG, "unplug #" + mType + ": realtime=" + baseRealtime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780 + " old mUnpluggedTime=" + mUnpluggedTime
1781 + " old mUnpluggedCount=" + mUnpluggedCount);
1782 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001783 mUnpluggedTime = computeRunTimeLocked(baseRealtime);
Adam Lesinski98f0d462016-04-19 16:46:20 -07001784 mUnpluggedCount = computeCurrentCountLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 if (DEBUG && mType < 0) {
1786 Log.v(TAG, "unplug #" + mType
1787 + ": new mUnpluggedTime=" + mUnpluggedTime
1788 + " new mUnpluggedCount=" + mUnpluggedCount);
1789 }
1790 }
1791
Adam Lesinskie08af192015-03-25 16:42:59 -07001792 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001793 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Evan Millarc64edde2009-04-18 12:26:32 -07001794 if (DEBUG && mType < 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001795 Log.v(TAG, "plug #" + mType + ": realtime=" + baseRealtime
Evan Millarc64edde2009-04-18 12:26:32 -07001796 + " old mTotalTime=" + mTotalTime);
1797 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001798 mTotalTime = computeRunTimeLocked(baseRealtime);
Evan Millarc64edde2009-04-18 12:26:32 -07001799 mCount = computeCurrentCountLocked();
1800 if (DEBUG && mType < 0) {
1801 Log.v(TAG, "plug #" + mType
1802 + ": new mTotalTime=" + mTotalTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 }
1804 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 /**
1807 * Writes a possibly null Timer to a Parcel.
1808 *
1809 * @param out the Parcel to be written to.
1810 * @param timer a Timer, or null.
1811 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001812 public static void writeTimerToParcel(Parcel out, Timer timer, long elapsedRealtimeUs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813 if (timer == null) {
1814 out.writeInt(0); // indicates null
1815 return;
1816 }
1817 out.writeInt(1); // indicates non-null
1818
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001819 timer.writeToParcel(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001820 }
1821
1822 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001823 public long getTotalTimeLocked(long elapsedRealtimeUs, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001824 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1825 if (which == STATS_SINCE_UNPLUGGED) {
1826 val -= mUnpluggedTime;
1827 } else if (which != STATS_SINCE_CHARGED) {
1828 val -= mLoadedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 }
1830
1831 return val;
1832 }
1833
1834 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001835 public int getCountLocked(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001836 int val = computeCurrentCountLocked();
1837 if (which == STATS_SINCE_UNPLUGGED) {
1838 val -= mUnpluggedCount;
1839 } else if (which != STATS_SINCE_CHARGED) {
1840 val -= mLoadedCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001841 }
1842
1843 return val;
1844 }
1845
Adam Lesinskie08af192015-03-25 16:42:59 -07001846 @Override
1847 public long getTimeSinceMarkLocked(long elapsedRealtimeUs) {
1848 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1849 return val - mTimeBeforeMark;
1850 }
1851
1852 @Override
Dianne Hackborn627bba72009-03-24 22:32:56 -07001853 public void logState(Printer pw, String prefix) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07001854 pw.println(prefix + "mCount=" + mCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 + " mLoadedCount=" + mLoadedCount + " mLastCount=" + mLastCount
1856 + " mUnpluggedCount=" + mUnpluggedCount);
Dianne Hackborn627bba72009-03-24 22:32:56 -07001857 pw.println(prefix + "mTotalTime=" + mTotalTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001858 + " mLoadedTime=" + mLoadedTime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07001859 pw.println(prefix + "mLastTime=" + mLastTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 + " mUnpluggedTime=" + mUnpluggedTime);
Evan Millarc64edde2009-04-18 12:26:32 -07001861 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001862
1863
Joe Onoratoabded112016-02-08 16:49:39 -08001864 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001865 long runTime = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1866 out.writeLong(runTime);
Adam Lesinski98f0d462016-04-19 16:46:20 -07001867 out.writeInt(computeCurrentCountLocked());
Evan Millarc64edde2009-04-18 12:26:32 -07001868 }
1869
Joe Onoratoabded112016-02-08 16:49:39 -08001870 public void readSummaryFromParcelLocked(Parcel in) {
Evan Millarc64edde2009-04-18 12:26:32 -07001871 // Multiply by 1000 for backwards compatibility
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001872 mTotalTime = mLoadedTime = in.readLong();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001873 mLastTime = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001874 mUnpluggedTime = mTotalTime;
1875 mCount = mLoadedCount = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001876 mLastCount = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001877 mUnpluggedCount = mCount;
Adam Lesinskie08af192015-03-25 16:42:59 -07001878
1879 // When reading the summary, we set the mark to be the latest information.
1880 mTimeBeforeMark = mTotalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001881 }
1882 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001883
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001884 /**
1885 * A counter meant to accept monotonically increasing values to its {@link #update(long, int)}
1886 * method. The state of the timer according to its {@link TimeBase} will determine how much
1887 * of the value is recorded.
1888 *
1889 * If the value being recorded resets, {@link #endSample()} can be called in order to
1890 * account for the change. If the value passed in to {@link #update(long, int)} decreased
1891 * between calls, the {@link #endSample()} is automatically called and the new value is
1892 * expected to increase monotonically from that point on.
1893 */
Joe Onoratoabded112016-02-08 16:49:39 -08001894 public static class SamplingTimer extends Timer {
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001895
Evan Millarc64edde2009-04-18 12:26:32 -07001896 /**
1897 * The most recent reported count from /proc/wakelocks.
1898 */
1899 int mCurrentReportedCount;
1900
1901 /**
1902 * The reported count from /proc/wakelocks when unplug() was last
1903 * called.
1904 */
1905 int mUnpluggedReportedCount;
1906
1907 /**
1908 * The most recent reported total_time from /proc/wakelocks.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001909 */
Evan Millarc64edde2009-04-18 12:26:32 -07001910 long mCurrentReportedTotalTime;
1911
1912
1913 /**
1914 * The reported total_time from /proc/wakelocks when unplug() was last
1915 * called.
1916 */
1917 long mUnpluggedReportedTotalTime;
1918
1919 /**
1920 * Whether we are currently in a discharge cycle.
1921 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001922 boolean mTimeBaseRunning;
Evan Millarc64edde2009-04-18 12:26:32 -07001923
1924 /**
1925 * Whether we are currently recording reported values.
1926 */
1927 boolean mTrackingReportedValues;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001928
Evan Millarc64edde2009-04-18 12:26:32 -07001929 /*
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001930 * A sequence counter, incremented once for each update of the stats.
Evan Millarc64edde2009-04-18 12:26:32 -07001931 */
1932 int mUpdateVersion;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001933
Adam Lesinski98f0d462016-04-19 16:46:20 -07001934 @VisibleForTesting
1935 public SamplingTimer(Clocks clocks, TimeBase timeBase, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08001936 super(clocks, 0, timeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -07001937 mCurrentReportedCount = in.readInt();
1938 mUnpluggedReportedCount = in.readInt();
1939 mCurrentReportedTotalTime = in.readLong();
1940 mUnpluggedReportedTotalTime = in.readLong();
1941 mTrackingReportedValues = in.readInt() == 1;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001942 mTimeBaseRunning = timeBase.isRunning();
Evan Millarc64edde2009-04-18 12:26:32 -07001943 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001944
Adam Lesinski98f0d462016-04-19 16:46:20 -07001945 @VisibleForTesting
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001946 public SamplingTimer(Clocks clocks, TimeBase timeBase) {
Joe Onoratoabded112016-02-08 16:49:39 -08001947 super(clocks, 0, timeBase);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001948 mTrackingReportedValues = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001949 mTimeBaseRunning = timeBase.isRunning();
Evan Millarc64edde2009-04-18 12:26:32 -07001950 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001951
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001952 /**
1953 * Ends the current sample, allowing subsequent values to {@link #update(long, int)} to
1954 * be less than the values used for a previous invocation.
1955 */
1956 public void endSample() {
1957 mTotalTime = computeRunTimeLocked(0 /* unused by us */);
1958 mCount = computeCurrentCountLocked();
1959 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime = 0;
1960 mUnpluggedReportedCount = mCurrentReportedCount = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001961 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001962
Evan Millarc64edde2009-04-18 12:26:32 -07001963 public void setUpdateVersion(int version) {
1964 mUpdateVersion = version;
1965 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001966
Evan Millarc64edde2009-04-18 12:26:32 -07001967 public int getUpdateVersion() {
1968 return mUpdateVersion;
1969 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001970
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001971 /**
1972 * Updates the current recorded values. These are meant to be monotonically increasing
1973 * and cumulative. If you are dealing with deltas, use {@link #add(long, int)}.
1974 *
1975 * If the values being recorded have been reset, the monotonically increasing requirement
1976 * will be broken. In this case, {@link #endSample()} is automatically called and
1977 * the total value of totalTime and count are recorded, starting a new monotonically
1978 * increasing sample.
1979 *
1980 * @param totalTime total time of sample in microseconds.
1981 * @param count total number of times the event being sampled occurred.
1982 */
1983 public void update(long totalTime, int count) {
1984 if (mTimeBaseRunning && !mTrackingReportedValues) {
Evan Millarc64edde2009-04-18 12:26:32 -07001985 // Updating the reported value for the first time.
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001986 mUnpluggedReportedTotalTime = totalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001987 mUnpluggedReportedCount = count;
Evan Millarc64edde2009-04-18 12:26:32 -07001988 }
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001989
1990 mTrackingReportedValues = true;
1991
1992 if (totalTime < mCurrentReportedTotalTime || count < mCurrentReportedCount) {
1993 endSample();
1994 }
1995
1996 mCurrentReportedTotalTime = totalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001997 mCurrentReportedCount = count;
1998 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001999
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002000 /**
2001 * Adds deltaTime and deltaCount to the current sample.
2002 *
2003 * @param deltaTime additional time recorded since the last sampled event, in microseconds.
2004 * @param deltaCount additional number of times the event being sampled occurred.
2005 */
2006 public void add(long deltaTime, int deltaCount) {
2007 update(mCurrentReportedTotalTime + deltaTime, mCurrentReportedCount + deltaCount);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002008 }
2009
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002010 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002011 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
2012 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime);
Evan Millarc64edde2009-04-18 12:26:32 -07002013 if (mTrackingReportedValues) {
2014 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime;
2015 mUnpluggedReportedCount = mCurrentReportedCount;
2016 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002017 mTimeBaseRunning = true;
Evan Millarc64edde2009-04-18 12:26:32 -07002018 }
2019
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002020 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002021 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
2022 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
2023 mTimeBaseRunning = false;
Evan Millarc64edde2009-04-18 12:26:32 -07002024 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002025
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002026 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07002027 public void logState(Printer pw, String prefix) {
2028 super.logState(pw, prefix);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002029 pw.println(prefix + "mCurrentReportedCount=" + mCurrentReportedCount
Evan Millarc64edde2009-04-18 12:26:32 -07002030 + " mUnpluggedReportedCount=" + mUnpluggedReportedCount
2031 + " mCurrentReportedTotalTime=" + mCurrentReportedTotalTime
2032 + " mUnpluggedReportedTotalTime=" + mUnpluggedReportedTotalTime);
2033 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002034
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002035 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07002036 protected long computeRunTimeLocked(long curBatteryRealtime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002037 return mTotalTime + (mTimeBaseRunning && mTrackingReportedValues
Evan Millarc64edde2009-04-18 12:26:32 -07002038 ? mCurrentReportedTotalTime - mUnpluggedReportedTotalTime : 0);
2039 }
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 protected int computeCurrentCountLocked() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002043 return mCount + (mTimeBaseRunning && mTrackingReportedValues
Evan Millarc64edde2009-04-18 12:26:32 -07002044 ? mCurrentReportedCount - mUnpluggedReportedCount : 0);
2045 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002046
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002047 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002048 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2049 super.writeToParcel(out, elapsedRealtimeUs);
Evan Millarc64edde2009-04-18 12:26:32 -07002050 out.writeInt(mCurrentReportedCount);
2051 out.writeInt(mUnpluggedReportedCount);
2052 out.writeLong(mCurrentReportedTotalTime);
2053 out.writeLong(mUnpluggedReportedTotalTime);
2054 out.writeInt(mTrackingReportedValues ? 1 : 0);
2055 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002056
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002057 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002058 public boolean reset(boolean detachIfReset) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002059 super.reset(detachIfReset);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002060 mTrackingReportedValues = false;
2061 mUnpluggedReportedTotalTime = 0;
2062 mUnpluggedReportedCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002063 return true;
2064 }
Evan Millarc64edde2009-04-18 12:26:32 -07002065 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002066
Evan Millarc64edde2009-04-18 12:26:32 -07002067 /**
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002068 * A timer that increments in batches. It does not run for durations, but just jumps
2069 * for a pre-determined amount.
2070 */
Joe Onoratoabded112016-02-08 16:49:39 -08002071 public static class BatchTimer extends Timer {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002072 final Uid mUid;
2073
2074 /**
2075 * The last time at which we updated the timer. This is in elapsed realtime microseconds.
2076 */
2077 long mLastAddedTime;
2078
2079 /**
2080 * The last duration that we added to the timer. This is in microseconds.
2081 */
2082 long mLastAddedDuration;
2083
2084 /**
2085 * Whether we are currently in a discharge cycle.
2086 */
2087 boolean mInDischarge;
2088
Joe Onoratoabded112016-02-08 16:49:39 -08002089 BatchTimer(Clocks clocks, Uid uid, int type, TimeBase timeBase, Parcel in) {
2090 super(clocks, type, timeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002091 mUid = uid;
2092 mLastAddedTime = in.readLong();
2093 mLastAddedDuration = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002094 mInDischarge = timeBase.isRunning();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002095 }
2096
Joe Onoratoabded112016-02-08 16:49:39 -08002097 BatchTimer(Clocks clocks, Uid uid, int type, TimeBase timeBase) {
2098 super(clocks, type, timeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002099 mUid = uid;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002100 mInDischarge = timeBase.isRunning();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002101 }
2102
2103 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002104 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2105 super.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002106 out.writeLong(mLastAddedTime);
2107 out.writeLong(mLastAddedDuration);
2108 }
2109
2110 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002111 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Joe Onoratoabded112016-02-08 16:49:39 -08002112 recomputeLastDuration(mClocks.elapsedRealtime() * 1000, false);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002113 mInDischarge = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002114 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002115 }
2116
2117 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002118 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002119 recomputeLastDuration(elapsedRealtime, false);
2120 mInDischarge = true;
2121 // If we are still within the last added duration, then re-added whatever remains.
2122 if (mLastAddedTime == elapsedRealtime) {
2123 mTotalTime += mLastAddedDuration;
2124 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002125 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002126 }
2127
2128 @Override
2129 public void logState(Printer pw, String prefix) {
2130 super.logState(pw, prefix);
2131 pw.println(prefix + "mLastAddedTime=" + mLastAddedTime
2132 + " mLastAddedDuration=" + mLastAddedDuration);
2133 }
2134
2135 private long computeOverage(long curTime) {
2136 if (mLastAddedTime > 0) {
2137 return mLastTime + mLastAddedDuration - curTime;
2138 }
2139 return 0;
2140 }
2141
2142 private void recomputeLastDuration(long curTime, boolean abort) {
2143 final long overage = computeOverage(curTime);
2144 if (overage > 0) {
2145 // Aborting before the duration ran out -- roll back the remaining
2146 // duration. Only do this if currently discharging; otherwise we didn't
2147 // actually add the time.
2148 if (mInDischarge) {
2149 mTotalTime -= overage;
2150 }
2151 if (abort) {
2152 mLastAddedTime = 0;
2153 } else {
2154 mLastAddedTime = curTime;
2155 mLastAddedDuration -= overage;
2156 }
2157 }
2158 }
2159
2160 public void addDuration(BatteryStatsImpl stats, long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08002161 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002162 recomputeLastDuration(now, true);
2163 mLastAddedTime = now;
2164 mLastAddedDuration = durationMillis * 1000;
2165 if (mInDischarge) {
2166 mTotalTime += mLastAddedDuration;
2167 mCount++;
2168 }
2169 }
2170
2171 public void abortLastDuration(BatteryStatsImpl stats) {
Joe Onoratoabded112016-02-08 16:49:39 -08002172 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002173 recomputeLastDuration(now, true);
2174 }
2175
2176 @Override
2177 protected int computeCurrentCountLocked() {
2178 return mCount;
2179 }
2180
2181 @Override
2182 protected long computeRunTimeLocked(long curBatteryRealtime) {
Joe Onoratoabded112016-02-08 16:49:39 -08002183 final long overage = computeOverage(mClocks.elapsedRealtime() * 1000);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002184 if (overage > 0) {
2185 return mTotalTime = overage;
2186 }
2187 return mTotalTime;
2188 }
2189
2190 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002191 public boolean reset(boolean detachIfReset) {
2192 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002193 recomputeLastDuration(now, true);
2194 boolean stillActive = mLastAddedTime == now;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002195 super.reset(!stillActive && detachIfReset);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002196 return !stillActive;
2197 }
2198 }
2199
Joe Onorato92fd23f2016-07-25 11:18:42 -07002200
2201 /**
2202 * A StopwatchTimer that also tracks the total and max individual
2203 * time spent active according to the given timebase. Whereas
2204 * StopwatchTimer apportions the time amongst all in the pool,
2205 * the total and max durations are not apportioned.
2206 */
2207 public static class DurationTimer extends StopwatchTimer {
2208 /**
2209 * The time (in ms) that the timer was last acquired or the time base
2210 * last (re-)started. Increasing the nesting depth does not reset this time.
2211 *
2212 * -1 if the timer is currently not running or the time base is not running.
2213 *
2214 * If written to a parcel, the start time is reset, as is mNesting in the base class
2215 * StopwatchTimer.
2216 */
2217 long mStartTimeMs = -1;
2218
2219 /**
Bookatz867c0d72017-03-07 18:23:42 -08002220 * The longest time period (in ms) that the timer has been active. Not pooled.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002221 */
2222 long mMaxDurationMs;
2223
2224 /**
Bookatz867c0d72017-03-07 18:23:42 -08002225 * The time (in ms) that that the timer has been active since most recent
2226 * stopRunningLocked() or reset(). Not pooled.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002227 */
2228 long mCurrentDurationMs;
2229
Bookatz867c0d72017-03-07 18:23:42 -08002230 /**
2231 * The total time (in ms) that that the timer has been active since most recent reset()
2232 * prior to the current startRunningLocked. This is the sum of all past currentDurations
2233 * (but not including the present currentDuration) since reset. Not pooled.
2234 */
2235 long mTotalDurationMs;
2236
Joe Onorato92fd23f2016-07-25 11:18:42 -07002237 public DurationTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2238 TimeBase timeBase, Parcel in) {
2239 super(clocks, uid, type, timerPool, timeBase, in);
2240 mMaxDurationMs = in.readLong();
Bookatz867c0d72017-03-07 18:23:42 -08002241 mTotalDurationMs = in.readLong();
jackqdyulei610a0a02017-08-09 14:02:01 -07002242 mCurrentDurationMs = in.readLong();
Joe Onorato92fd23f2016-07-25 11:18:42 -07002243 }
2244
2245 public DurationTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2246 TimeBase timeBase) {
2247 super(clocks, uid, type, timerPool, timeBase);
2248 }
2249
2250 @Override
2251 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2252 super.writeToParcel(out, elapsedRealtimeUs);
Kweku Adams47db5a82016-12-09 19:04:50 -08002253 out.writeLong(getMaxDurationMsLocked(elapsedRealtimeUs / 1000));
jackqdyulei610a0a02017-08-09 14:02:01 -07002254 out.writeLong(mTotalDurationMs);
2255 out.writeLong(getCurrentDurationMsLocked(elapsedRealtimeUs / 1000));
Joe Onorato92fd23f2016-07-25 11:18:42 -07002256 }
2257
2258 /**
2259 * Write the summary to the parcel.
2260 *
2261 * Since the time base is probably meaningless after we come back, reading
2262 * from this will have the effect of stopping the timer. So here all we write
Bookatz867c0d72017-03-07 18:23:42 -08002263 * is the max and total durations.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002264 */
2265 @Override
2266 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
2267 super.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
Kweku Adams47db5a82016-12-09 19:04:50 -08002268 out.writeLong(getMaxDurationMsLocked(elapsedRealtimeUs / 1000));
Bookatz867c0d72017-03-07 18:23:42 -08002269 out.writeLong(getTotalDurationMsLocked(elapsedRealtimeUs / 1000));
Joe Onorato92fd23f2016-07-25 11:18:42 -07002270 }
2271
2272 /**
2273 * Read the summary parcel.
2274 *
2275 * Has the side effect of stopping the timer.
2276 */
2277 @Override
2278 public void readSummaryFromParcelLocked(Parcel in) {
2279 super.readSummaryFromParcelLocked(in);
2280 mMaxDurationMs = in.readLong();
Bookatz867c0d72017-03-07 18:23:42 -08002281 mTotalDurationMs = in.readLong();
Joe Onorato92fd23f2016-07-25 11:18:42 -07002282 mStartTimeMs = -1;
2283 mCurrentDurationMs = 0;
2284 }
2285
2286 /**
2287 * The TimeBase time started (again).
2288 *
2289 * If the timer is also running, store the start time.
2290 */
2291 public void onTimeStarted(long elapsedRealtimeUs, long baseUptime, long baseRealtime) {
2292 super.onTimeStarted(elapsedRealtimeUs, baseUptime, baseRealtime);
2293 if (mNesting > 0) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002294 mStartTimeMs = baseRealtime / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002295 }
2296 }
2297
2298 /**
2299 * The TimeBase stopped running.
2300 *
2301 * If the timer is running, add the duration into mCurrentDurationMs.
2302 */
2303 @Override
Kweku Adams47db5a82016-12-09 19:04:50 -08002304 public void onTimeStopped(long elapsedRealtimeUs, long baseUptime, long baseRealtimeUs) {
2305 super.onTimeStopped(elapsedRealtimeUs, baseUptime, baseRealtimeUs);
Joe Onorato92fd23f2016-07-25 11:18:42 -07002306 if (mNesting > 0) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002307 // baseRealtimeUs has already been converted to the timebase's realtime.
2308 mCurrentDurationMs += (baseRealtimeUs / 1000) - mStartTimeMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002309 }
2310 mStartTimeMs = -1;
2311 }
2312
2313 @Override
2314 public void logState(Printer pw, String prefix) {
2315 super.logState(pw, prefix);
2316 }
2317
2318 @Override
2319 public void startRunningLocked(long elapsedRealtimeMs) {
2320 super.startRunningLocked(elapsedRealtimeMs);
2321 if (mNesting == 1 && mTimeBase.isRunning()) {
2322 // Just started
Kweku Adams47db5a82016-12-09 19:04:50 -08002323 mStartTimeMs = mTimeBase.getRealtime(elapsedRealtimeMs * 1000) / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002324 }
2325 }
2326
2327 /**
2328 * Decrements the mNesting ref-count on this timer.
2329 *
2330 * If it actually stopped (mNesting went to 0), then possibly update
2331 * mMaxDuration if the current duration was the longest ever.
2332 */
2333 @Override
2334 public void stopRunningLocked(long elapsedRealtimeMs) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002335 if (mNesting == 1) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07002336 final long durationMs = getCurrentDurationMsLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002337 mTotalDurationMs += durationMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002338 if (durationMs > mMaxDurationMs) {
2339 mMaxDurationMs = durationMs;
2340 }
2341 mStartTimeMs = -1;
2342 mCurrentDurationMs = 0;
2343 }
Kweku Adams47db5a82016-12-09 19:04:50 -08002344 // super method decrements mNesting, which getCurrentDurationMsLocked relies on,
2345 // so call super.stopRunningLocked after calling getCurrentDurationMsLocked.
2346 super.stopRunningLocked(elapsedRealtimeMs);
Joe Onorato92fd23f2016-07-25 11:18:42 -07002347 }
2348
2349 @Override
2350 public boolean reset(boolean detachIfReset) {
2351 boolean result = super.reset(detachIfReset);
2352 mMaxDurationMs = 0;
Bookatz867c0d72017-03-07 18:23:42 -08002353 mTotalDurationMs = 0;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002354 mCurrentDurationMs = 0;
2355 if (mNesting > 0) {
2356 mStartTimeMs = mTimeBase.getRealtime(mClocks.elapsedRealtime()*1000) / 1000;
2357 } else {
2358 mStartTimeMs = -1;
2359 }
2360 return result;
2361 }
2362
2363 /**
2364 * Returns the max duration that this timer has ever seen.
2365 *
2366 * Note that this time is NOT split between the timers in the timer group that
2367 * this timer is attached to. It is the TOTAL time.
2368 */
2369 @Override
2370 public long getMaxDurationMsLocked(long elapsedRealtimeMs) {
2371 if (mNesting > 0) {
2372 final long durationMs = getCurrentDurationMsLocked(elapsedRealtimeMs);
2373 if (durationMs > mMaxDurationMs) {
2374 return durationMs;
2375 }
2376 }
2377 return mMaxDurationMs;
2378 }
2379
2380 /**
2381 * Returns the time since the timer was started.
Bookatz867c0d72017-03-07 18:23:42 -08002382 * Returns 0 if the timer is not currently running.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002383 *
2384 * Note that this time is NOT split between the timers in the timer group that
2385 * this timer is attached to. It is the TOTAL time.
jackqdyulei610a0a02017-08-09 14:02:01 -07002386 *
2387 * Note that if running timer is parceled and unparceled, this method will return
2388 * current duration value at the time of parceling even though timer may not be
2389 * currently running.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002390 */
2391 @Override
2392 public long getCurrentDurationMsLocked(long elapsedRealtimeMs) {
2393 long durationMs = mCurrentDurationMs;
Kweku Adams47db5a82016-12-09 19:04:50 -08002394 if (mNesting > 0 && mTimeBase.isRunning()) {
2395 durationMs += (mTimeBase.getRealtime(elapsedRealtimeMs*1000)/1000)
2396 - mStartTimeMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002397 }
2398 return durationMs;
2399 }
Bookatz867c0d72017-03-07 18:23:42 -08002400
2401 /**
2402 * Returns the total cumulative duration that this timer has been on since reset().
2403 * If mTimerPool == null, this should be the same
2404 * as getTotalTimeLocked(elapsedRealtimeMs*1000, STATS_SINCE_CHARGED)/1000.
2405 *
2406 * Note that this time is NOT split between the timers in the timer group that
2407 * this timer is attached to. It is the TOTAL time. For this reason, if mTimerPool != null,
2408 * the result will not be equivalent to getTotalTimeLocked.
2409 */
2410 @Override
2411 public long getTotalDurationMsLocked(long elapsedRealtimeMs) {
2412 return mTotalDurationMs + getCurrentDurationMsLocked(elapsedRealtimeMs);
2413 }
Joe Onorato92fd23f2016-07-25 11:18:42 -07002414 }
2415
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002416 /**
Evan Millarc64edde2009-04-18 12:26:32 -07002417 * State for keeping track of timing information.
2418 */
Joe Onoratoabded112016-02-08 16:49:39 -08002419 public static class StopwatchTimer extends Timer {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002420 final Uid mUid;
Evan Millarc64edde2009-04-18 12:26:32 -07002421 final ArrayList<StopwatchTimer> mTimerPool;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002422
Evan Millarc64edde2009-04-18 12:26:32 -07002423 int mNesting;
2424
Evan Millarc64edde2009-04-18 12:26:32 -07002425 /**
2426 * The last time at which we updated the timer. If mNesting is > 0,
2427 * subtract this from the current battery time to find the amount of
2428 * time we have been running since we last computed an update.
2429 */
2430 long mUpdateTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002431
Evan Millarc64edde2009-04-18 12:26:32 -07002432 /**
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002433 * The total time at which the timer was acquired, to determine if it
Bookatzceebafe2017-04-06 11:59:13 -07002434 * was actually held for an interesting duration. If time base was not running when timer
2435 * was acquired, will be -1.
Evan Millarc64edde2009-04-18 12:26:32 -07002436 */
Bookatzceebafe2017-04-06 11:59:13 -07002437 long mAcquireTime = -1;
Evan Millarc64edde2009-04-18 12:26:32 -07002438
Amith Yamasanif37447b2009-10-08 18:28:01 -07002439 long mTimeout;
2440
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002441 /**
2442 * For partial wake locks, keep track of whether we are in the list
2443 * to consume CPU cycles.
2444 */
Sudheer Shanka38383232017-07-25 09:55:03 -07002445 @VisibleForTesting
2446 public boolean mInList;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002447
Joe Onoratoabded112016-02-08 16:49:39 -08002448 public StopwatchTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002449 TimeBase timeBase, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08002450 super(clocks, type, timeBase, in);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002451 mUid = uid;
Evan Millarc64edde2009-04-18 12:26:32 -07002452 mTimerPool = timerPool;
2453 mUpdateTime = in.readLong();
2454 }
2455
Joe Onoratoabded112016-02-08 16:49:39 -08002456 public StopwatchTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002457 TimeBase timeBase) {
Joe Onoratoabded112016-02-08 16:49:39 -08002458 super(clocks, type, timeBase);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002459 mUid = uid;
Evan Millarc64edde2009-04-18 12:26:32 -07002460 mTimerPool = timerPool;
2461 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002462
Joe Onoratoabded112016-02-08 16:49:39 -08002463 public void setTimeout(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07002464 mTimeout = timeout;
2465 }
2466
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002467 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2468 super.writeToParcel(out, elapsedRealtimeUs);
Evan Millarc64edde2009-04-18 12:26:32 -07002469 out.writeLong(mUpdateTime);
2470 }
2471
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002472 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Evan Millarc64edde2009-04-18 12:26:32 -07002473 if (mNesting > 0) {
2474 if (DEBUG && mType < 0) {
2475 Log.v(TAG, "old mUpdateTime=" + mUpdateTime);
2476 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002477 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
2478 mUpdateTime = baseRealtime;
Evan Millarc64edde2009-04-18 12:26:32 -07002479 if (DEBUG && mType < 0) {
2480 Log.v(TAG, "new mUpdateTime=" + mUpdateTime);
2481 }
2482 }
2483 }
2484
2485 public void logState(Printer pw, String prefix) {
2486 super.logState(pw, prefix);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07002487 pw.println(prefix + "mNesting=" + mNesting + " mUpdateTime=" + mUpdateTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002488 + " mAcquireTime=" + mAcquireTime);
2489 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002490
Joe Onoratoabded112016-02-08 16:49:39 -08002491 public void startRunningLocked(long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002492 if (mNesting++ == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002493 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002494 mUpdateTime = batteryRealtime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 if (mTimerPool != null) {
2496 // Accumulate time to all currently active timers before adding
2497 // this new one to the pool.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002498 refreshTimersLocked(batteryRealtime, mTimerPool, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002499 // Add this timer to the active pool
2500 mTimerPool.add(this);
2501 }
Bookatzceebafe2017-04-06 11:59:13 -07002502 if (mTimeBase.isRunning()) {
2503 // Increment the count
2504 mCount++;
2505 mAcquireTime = mTotalTime;
2506 } else {
2507 mAcquireTime = -1;
2508 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002509 if (DEBUG && mType < 0) {
2510 Log.v(TAG, "start #" + mType + ": mUpdateTime=" + mUpdateTime
2511 + " mTotalTime=" + mTotalTime + " mCount=" + mCount
2512 + " mAcquireTime=" + mAcquireTime);
2513 }
2514 }
2515 }
2516
Joe Onoratoabded112016-02-08 16:49:39 -08002517 public boolean isRunningLocked() {
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002518 return mNesting > 0;
2519 }
2520
Joe Onoratoabded112016-02-08 16:49:39 -08002521 public void stopRunningLocked(long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002522 // Ignore attempt to stop a timer that isn't running
2523 if (mNesting == 0) {
2524 return;
2525 }
2526 if (--mNesting == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002527 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002528 if (mTimerPool != null) {
2529 // Accumulate time to all active counters, scaled by the total
2530 // active in the pool, before taking this one out of the pool.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002531 refreshTimersLocked(batteryRealtime, mTimerPool, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002532 // Remove this timer from the active pool
2533 mTimerPool.remove(this);
2534 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002535 mNesting = 1;
2536 mTotalTime = computeRunTimeLocked(batteryRealtime);
2537 mNesting = 0;
2538 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002540 if (DEBUG && mType < 0) {
2541 Log.v(TAG, "stop #" + mType + ": mUpdateTime=" + mUpdateTime
2542 + " mTotalTime=" + mTotalTime + " mCount=" + mCount
2543 + " mAcquireTime=" + mAcquireTime);
2544 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002545
Bookatzceebafe2017-04-06 11:59:13 -07002546 if (mAcquireTime >= 0 && mTotalTime == mAcquireTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002547 // If there was no change in the time, then discard this
2548 // count. A somewhat cheezy strategy, but hey.
2549 mCount--;
2550 }
2551 }
2552 }
2553
Joe Onoratoabded112016-02-08 16:49:39 -08002554 public void stopAllRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07002555 if (mNesting > 0) {
2556 mNesting = 1;
2557 stopRunningLocked(elapsedRealtimeMs);
2558 }
2559 }
2560
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002561 // Update the total time for all other running Timers with the same type as this Timer
2562 // due to a change in timer count
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002563 private static long refreshTimersLocked(long batteryRealtime,
2564 final ArrayList<StopwatchTimer> pool, StopwatchTimer self) {
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002565 long selfTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566 final int N = pool.size();
2567 for (int i=N-1; i>= 0; i--) {
Evan Millarc64edde2009-04-18 12:26:32 -07002568 final StopwatchTimer t = pool.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002569 long heldTime = batteryRealtime - t.mUpdateTime;
2570 if (heldTime > 0) {
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002571 final long myTime = heldTime / N;
2572 if (t == self) {
2573 selfTime = myTime;
2574 }
2575 t.mTotalTime += myTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576 }
2577 t.mUpdateTime = batteryRealtime;
2578 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002579 return selfTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002580 }
2581
Evan Millarc64edde2009-04-18 12:26:32 -07002582 @Override
2583 protected long computeRunTimeLocked(long curBatteryRealtime) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07002584 if (mTimeout > 0 && curBatteryRealtime > mUpdateTime + mTimeout) {
2585 curBatteryRealtime = mUpdateTime + mTimeout;
2586 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 return mTotalTime + (mNesting > 0
2588 ? (curBatteryRealtime - mUpdateTime)
2589 / (mTimerPool != null ? mTimerPool.size() : 1)
2590 : 0);
2591 }
2592
Evan Millarc64edde2009-04-18 12:26:32 -07002593 @Override
2594 protected int computeCurrentCountLocked() {
2595 return mCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002596 }
2597
Adam Lesinskie08af192015-03-25 16:42:59 -07002598 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002599 public boolean reset(boolean detachIfReset) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002600 boolean canDetach = mNesting <= 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002601 super.reset(canDetach && detachIfReset);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002602 if (mNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08002603 mUpdateTime = mTimeBase.getRealtime(mClocks.elapsedRealtime() * 1000);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002604 }
Bookatzceebafe2017-04-06 11:59:13 -07002605 mAcquireTime = -1; // to ensure mCount isn't decreased to -1 if timer is stopped later.
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002606 return canDetach;
2607 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002608
Adam Lesinskie08af192015-03-25 16:42:59 -07002609 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002610 public void detach() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002611 super.detach();
2612 if (mTimerPool != null) {
2613 mTimerPool.remove(this);
2614 }
2615 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002616
Adam Lesinskie08af192015-03-25 16:42:59 -07002617 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002618 public void readSummaryFromParcelLocked(Parcel in) {
Evan Millarc64edde2009-04-18 12:26:32 -07002619 super.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002620 mNesting = 0;
2621 }
Adam Lesinskie08af192015-03-25 16:42:59 -07002622
2623 /**
2624 * Set the mark so that we can query later for the total time the timer has
2625 * accumulated since this point. The timer can be running or not.
2626 *
2627 * @param elapsedRealtimeMs the current elapsed realtime in milliseconds.
2628 */
2629 public void setMark(long elapsedRealtimeMs) {
2630 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
2631 if (mNesting > 0) {
2632 // We are running.
2633 if (mTimerPool != null) {
2634 refreshTimersLocked(batteryRealtime, mTimerPool, this);
2635 } else {
2636 mTotalTime += batteryRealtime - mUpdateTime;
2637 mUpdateTime = batteryRealtime;
2638 }
2639 }
2640 mTimeBeforeMark = mTotalTime;
2641 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002642 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002643
Bookatz867c0d72017-03-07 18:23:42 -08002644 /**
2645 * State for keeping track of two DurationTimers with different TimeBases, presumably where one
2646 * TimeBase is effectively a subset of the other.
2647 */
Bookatzaa4594a2017-03-24 12:39:56 -07002648 public static class DualTimer extends DurationTimer {
2649 // This class both is a DurationTimer and also holds a second DurationTimer.
2650 // The main timer (this) typically tracks the total time. It may be pooled (but since it's a
2651 // durationTimer, it also has the unpooled getTotalDurationMsLocked() for
2652 // STATS_SINCE_CHARGED).
Bookatz867c0d72017-03-07 18:23:42 -08002653 // mSubTimer typically tracks only part of the total time, such as background time, as
2654 // determined by a subTimeBase. It is NOT pooled.
2655 private final DurationTimer mSubTimer;
2656
2657 /**
Bookatzaa4594a2017-03-24 12:39:56 -07002658 * Creates a DualTimer to hold a main timer (this) and a mSubTimer.
2659 * The main timer (this) is based on the given timeBase and timerPool.
Bookatz867c0d72017-03-07 18:23:42 -08002660 * The mSubTimer is based on the given subTimeBase. The mSubTimer is not pooled, even if
Bookatzaa4594a2017-03-24 12:39:56 -07002661 * the main timer is.
Bookatz867c0d72017-03-07 18:23:42 -08002662 */
2663 public DualTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2664 TimeBase timeBase, TimeBase subTimeBase, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07002665 super(clocks, uid, type, timerPool, timeBase, in);
Bookatz867c0d72017-03-07 18:23:42 -08002666 mSubTimer = new DurationTimer(clocks, uid, type, null, subTimeBase, in);
2667 }
2668
2669 /**
Bookatzaa4594a2017-03-24 12:39:56 -07002670 * Creates a DualTimer to hold a main timer (this) and a mSubTimer.
2671 * The main timer (this) is based on the given timeBase and timerPool.
Bookatz867c0d72017-03-07 18:23:42 -08002672 * The mSubTimer is based on the given subTimeBase. The mSubTimer is not pooled, even if
Bookatzaa4594a2017-03-24 12:39:56 -07002673 * the main timer is.
Bookatz867c0d72017-03-07 18:23:42 -08002674 */
2675 public DualTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2676 TimeBase timeBase, TimeBase subTimeBase) {
Bookatzaa4594a2017-03-24 12:39:56 -07002677 super(clocks, uid, type, timerPool, timeBase);
Bookatz867c0d72017-03-07 18:23:42 -08002678 mSubTimer = new DurationTimer(clocks, uid, type, null, subTimeBase);
2679 }
2680
Bookatz867c0d72017-03-07 18:23:42 -08002681 /** Get the secondary timer. */
Bookatzaa4594a2017-03-24 12:39:56 -07002682 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002683 public DurationTimer getSubTimer() {
2684 return mSubTimer;
2685 }
2686
Bookatzaa4594a2017-03-24 12:39:56 -07002687 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002688 public void startRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002689 super.startRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002690 mSubTimer.startRunningLocked(elapsedRealtimeMs);
2691 }
2692
Bookatzaa4594a2017-03-24 12:39:56 -07002693 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002694 public void stopRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002695 super.stopRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002696 mSubTimer.stopRunningLocked(elapsedRealtimeMs);
2697 }
2698
Bookatzaa4594a2017-03-24 12:39:56 -07002699 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002700 public void stopAllRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002701 super.stopAllRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002702 mSubTimer.stopAllRunningLocked(elapsedRealtimeMs);
2703 }
2704
Bookatzaa4594a2017-03-24 12:39:56 -07002705 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002706 public boolean reset(boolean detachIfReset) {
2707 boolean active = false;
Bookatz4a3eda92017-04-10 13:10:46 -07002708 // Do not detach the subTimer explicitly since that'll be done by DualTimer.detach().
2709 active |= !mSubTimer.reset(false);
Bookatzaa4594a2017-03-24 12:39:56 -07002710 active |= !super.reset(detachIfReset);
Bookatz867c0d72017-03-07 18:23:42 -08002711 return !active;
2712 }
2713
Bookatzaa4594a2017-03-24 12:39:56 -07002714 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002715 public void detach() {
Bookatz867c0d72017-03-07 18:23:42 -08002716 mSubTimer.detach();
Bookatz4a3eda92017-04-10 13:10:46 -07002717 super.detach();
Bookatz867c0d72017-03-07 18:23:42 -08002718 }
2719
Bookatzaa4594a2017-03-24 12:39:56 -07002720 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002721 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002722 super.writeToParcel(out, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08002723 mSubTimer.writeToParcel(out, elapsedRealtimeUs);
2724 }
2725
Bookatzaa4594a2017-03-24 12:39:56 -07002726 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002727 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002728 super.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08002729 mSubTimer.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
2730 }
2731
Bookatzaa4594a2017-03-24 12:39:56 -07002732 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002733 public void readSummaryFromParcelLocked(Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07002734 super.readSummaryFromParcelLocked(in);
Bookatz867c0d72017-03-07 18:23:42 -08002735 mSubTimer.readSummaryFromParcelLocked(in);
2736 }
2737 }
2738
2739
Dianne Hackbornd953c532014-08-16 18:17:38 -07002740 public abstract class OverflowArrayMap<T> {
2741 private static final String OVERFLOW_NAME = "*overflow*";
2742
Dianne Hackborn657153b2016-07-29 14:54:14 -07002743 final int mUid;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002744 final ArrayMap<String, T> mMap = new ArrayMap<>();
2745 T mCurOverflow;
2746 ArrayMap<String, MutableInt> mActiveOverflow;
Dianne Hackborn657153b2016-07-29 14:54:14 -07002747 long mLastOverflowTime;
2748 long mLastOverflowFinishTime;
2749 long mLastClearTime;
2750 long mLastCleanupTime;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002751
Dianne Hackborn657153b2016-07-29 14:54:14 -07002752 public OverflowArrayMap(int uid) {
2753 mUid = uid;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002754 }
2755
2756 public ArrayMap<String, T> getMap() {
2757 return mMap;
2758 }
2759
2760 public void clear() {
Dianne Hackborn657153b2016-07-29 14:54:14 -07002761 mLastClearTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002762 mMap.clear();
2763 mCurOverflow = null;
2764 mActiveOverflow = null;
2765 }
2766
2767 public void add(String name, T obj) {
Joe Onorato388fc332016-04-12 17:06:47 -07002768 if (name == null) {
2769 name = "";
2770 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002771 mMap.put(name, obj);
2772 if (OVERFLOW_NAME.equals(name)) {
2773 mCurOverflow = obj;
2774 }
2775 }
2776
2777 public void cleanup() {
Dianne Hackborn657153b2016-07-29 14:54:14 -07002778 mLastCleanupTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002779 if (mActiveOverflow != null) {
2780 if (mActiveOverflow.size() == 0) {
2781 mActiveOverflow = null;
2782 }
2783 }
2784 if (mActiveOverflow == null) {
2785 // There is no currently active overflow, so we should no longer have
2786 // an overflow entry.
2787 if (mMap.containsKey(OVERFLOW_NAME)) {
2788 Slog.wtf(TAG, "Cleaning up with no active overflow, but have overflow entry "
2789 + mMap.get(OVERFLOW_NAME));
2790 mMap.remove(OVERFLOW_NAME);
2791 }
2792 mCurOverflow = null;
2793 } else {
2794 // There is currently active overflow, so we should still have an overflow entry.
2795 if (mCurOverflow == null || !mMap.containsKey(OVERFLOW_NAME)) {
2796 Slog.wtf(TAG, "Cleaning up with active overflow, but no overflow entry: cur="
2797 + mCurOverflow + " map=" + mMap.get(OVERFLOW_NAME));
2798 }
2799 }
2800 }
2801
2802 public T startObject(String name) {
Joe Onorato388fc332016-04-12 17:06:47 -07002803 if (name == null) {
2804 name = "";
2805 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002806 T obj = mMap.get(name);
2807 if (obj != null) {
2808 return obj;
2809 }
2810
2811 // No object exists for the given name, but do we currently have it
2812 // running as part of the overflow?
2813 if (mActiveOverflow != null) {
2814 MutableInt over = mActiveOverflow.get(name);
2815 if (over != null) {
2816 // We are already actively counting this name in the overflow object.
2817 obj = mCurOverflow;
2818 if (obj == null) {
2819 // Shouldn't be here, but we'll try to recover.
2820 Slog.wtf(TAG, "Have active overflow " + name + " but null overflow");
2821 obj = mCurOverflow = instantiateObject();
2822 mMap.put(OVERFLOW_NAME, obj);
2823 }
2824 over.value++;
2825 return obj;
2826 }
2827 }
2828
2829 // No object exists for given name nor in the overflow; we need to make
2830 // a new one.
2831 final int N = mMap.size();
2832 if (N >= MAX_WAKELOCKS_PER_UID) {
2833 // Went over the limit on number of objects to track; this one goes
2834 // in to the overflow.
2835 obj = mCurOverflow;
2836 if (obj == null) {
2837 // Need to start overflow now...
2838 obj = mCurOverflow = instantiateObject();
2839 mMap.put(OVERFLOW_NAME, obj);
2840 }
2841 if (mActiveOverflow == null) {
2842 mActiveOverflow = new ArrayMap<>();
2843 }
2844 mActiveOverflow.put(name, new MutableInt(1));
Dianne Hackborn657153b2016-07-29 14:54:14 -07002845 mLastOverflowTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002846 return obj;
2847 }
2848
2849 // Normal case where we just need to make a new object.
2850 obj = instantiateObject();
2851 mMap.put(name, obj);
2852 return obj;
2853 }
2854
2855 public T stopObject(String name) {
Joe Onorato388fc332016-04-12 17:06:47 -07002856 if (name == null) {
2857 name = "";
2858 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002859 T obj = mMap.get(name);
2860 if (obj != null) {
2861 return obj;
2862 }
2863
2864 // No object exists for the given name, but do we currently have it
2865 // running as part of the overflow?
2866 if (mActiveOverflow != null) {
2867 MutableInt over = mActiveOverflow.get(name);
2868 if (over != null) {
2869 // We are already actively counting this name in the overflow object.
2870 obj = mCurOverflow;
2871 if (obj != null) {
2872 over.value--;
2873 if (over.value <= 0) {
2874 mActiveOverflow.remove(name);
Dianne Hackborn657153b2016-07-29 14:54:14 -07002875 mLastOverflowFinishTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002876 }
2877 return obj;
2878 }
2879 }
2880 }
2881
2882 // Huh, they are stopping an active operation but we can't find one!
2883 // That's not good.
Dianne Hackborn657153b2016-07-29 14:54:14 -07002884 StringBuilder sb = new StringBuilder();
2885 sb.append("Unable to find object for ");
2886 sb.append(name);
2887 sb.append(" in uid ");
2888 sb.append(mUid);
2889 sb.append(" mapsize=");
2890 sb.append(mMap.size());
2891 sb.append(" activeoverflow=");
2892 sb.append(mActiveOverflow);
2893 sb.append(" curoverflow=");
2894 sb.append(mCurOverflow);
2895 long now = SystemClock.elapsedRealtime();
2896 if (mLastOverflowTime != 0) {
2897 sb.append(" lastOverflowTime=");
2898 TimeUtils.formatDuration(mLastOverflowTime-now, sb);
2899 }
2900 if (mLastOverflowFinishTime != 0) {
2901 sb.append(" lastOverflowFinishTime=");
2902 TimeUtils.formatDuration(mLastOverflowFinishTime-now, sb);
2903 }
2904 if (mLastClearTime != 0) {
2905 sb.append(" lastClearTime=");
2906 TimeUtils.formatDuration(mLastClearTime-now, sb);
2907 }
2908 if (mLastCleanupTime != 0) {
2909 sb.append(" lastCleanupTime=");
2910 TimeUtils.formatDuration(mLastCleanupTime-now, sb);
2911 }
2912 Slog.wtf(TAG, sb.toString());
Dianne Hackbornd953c532014-08-16 18:17:38 -07002913 return null;
2914 }
2915
2916 public abstract T instantiateObject();
2917 }
2918
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002919 public static class ControllerActivityCounterImpl extends ControllerActivityCounter
2920 implements Parcelable {
2921 private final LongSamplingCounter mIdleTimeMillis;
Siddharth Rayb50a6842017-12-14 15:15:28 -08002922 private final LongSamplingCounter mScanTimeMillis;
Siddharth Rayed754702018-02-15 12:44:37 -08002923 private final LongSamplingCounter mSleepTimeMillis;
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002924 private final LongSamplingCounter mRxTimeMillis;
2925 private final LongSamplingCounter[] mTxTimeMillis;
2926 private final LongSamplingCounter mPowerDrainMaMs;
2927
2928 public ControllerActivityCounterImpl(TimeBase timeBase, int numTxStates) {
2929 mIdleTimeMillis = new LongSamplingCounter(timeBase);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002930 mScanTimeMillis = new LongSamplingCounter(timeBase);
Siddharth Rayed754702018-02-15 12:44:37 -08002931 mSleepTimeMillis = new LongSamplingCounter(timeBase);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002932 mRxTimeMillis = new LongSamplingCounter(timeBase);
2933 mTxTimeMillis = new LongSamplingCounter[numTxStates];
2934 for (int i = 0; i < numTxStates; i++) {
2935 mTxTimeMillis[i] = new LongSamplingCounter(timeBase);
2936 }
2937 mPowerDrainMaMs = new LongSamplingCounter(timeBase);
2938 }
2939
2940 public ControllerActivityCounterImpl(TimeBase timeBase, int numTxStates, Parcel in) {
2941 mIdleTimeMillis = new LongSamplingCounter(timeBase, in);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002942 mScanTimeMillis = new LongSamplingCounter(timeBase, in);
Siddharth Rayed754702018-02-15 12:44:37 -08002943 mSleepTimeMillis = new LongSamplingCounter(timeBase, in);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002944 mRxTimeMillis = new LongSamplingCounter(timeBase, in);
2945 final int recordedTxStates = in.readInt();
2946 if (recordedTxStates != numTxStates) {
2947 throw new ParcelFormatException("inconsistent tx state lengths");
2948 }
2949
2950 mTxTimeMillis = new LongSamplingCounter[numTxStates];
2951 for (int i = 0; i < numTxStates; i++) {
2952 mTxTimeMillis[i] = new LongSamplingCounter(timeBase, in);
2953 }
2954 mPowerDrainMaMs = new LongSamplingCounter(timeBase, in);
2955 }
2956
2957 public void readSummaryFromParcel(Parcel in) {
2958 mIdleTimeMillis.readSummaryFromParcelLocked(in);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002959 mScanTimeMillis.readSummaryFromParcelLocked(in);
Siddharth Rayed754702018-02-15 12:44:37 -08002960 mSleepTimeMillis.readSummaryFromParcelLocked(in);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002961 mRxTimeMillis.readSummaryFromParcelLocked(in);
2962 final int recordedTxStates = in.readInt();
2963 if (recordedTxStates != mTxTimeMillis.length) {
2964 throw new ParcelFormatException("inconsistent tx state lengths");
2965 }
2966 for (LongSamplingCounter counter : mTxTimeMillis) {
2967 counter.readSummaryFromParcelLocked(in);
2968 }
2969 mPowerDrainMaMs.readSummaryFromParcelLocked(in);
2970 }
2971
2972 @Override
2973 public int describeContents() {
2974 return 0;
2975 }
2976
2977 public void writeSummaryToParcel(Parcel dest) {
2978 mIdleTimeMillis.writeSummaryFromParcelLocked(dest);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002979 mScanTimeMillis.writeSummaryFromParcelLocked(dest);
Siddharth Rayed754702018-02-15 12:44:37 -08002980 mSleepTimeMillis.writeSummaryFromParcelLocked(dest);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002981 mRxTimeMillis.writeSummaryFromParcelLocked(dest);
2982 dest.writeInt(mTxTimeMillis.length);
2983 for (LongSamplingCounter counter : mTxTimeMillis) {
2984 counter.writeSummaryFromParcelLocked(dest);
2985 }
2986 mPowerDrainMaMs.writeSummaryFromParcelLocked(dest);
2987 }
2988
2989 @Override
2990 public void writeToParcel(Parcel dest, int flags) {
2991 mIdleTimeMillis.writeToParcel(dest);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002992 mScanTimeMillis.writeToParcel(dest);
Siddharth Rayed754702018-02-15 12:44:37 -08002993 mSleepTimeMillis.writeToParcel(dest);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002994 mRxTimeMillis.writeToParcel(dest);
2995 dest.writeInt(mTxTimeMillis.length);
2996 for (LongSamplingCounter counter : mTxTimeMillis) {
2997 counter.writeToParcel(dest);
2998 }
2999 mPowerDrainMaMs.writeToParcel(dest);
3000 }
3001
3002 public void reset(boolean detachIfReset) {
3003 mIdleTimeMillis.reset(detachIfReset);
Siddharth Rayb50a6842017-12-14 15:15:28 -08003004 mScanTimeMillis.reset(detachIfReset);
Siddharth Rayed754702018-02-15 12:44:37 -08003005 mSleepTimeMillis.reset(detachIfReset);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08003006 mRxTimeMillis.reset(detachIfReset);
3007 for (LongSamplingCounter counter : mTxTimeMillis) {
3008 counter.reset(detachIfReset);
3009 }
3010 mPowerDrainMaMs.reset(detachIfReset);
3011 }
3012
3013 public void detach() {
3014 mIdleTimeMillis.detach();
Siddharth Rayb50a6842017-12-14 15:15:28 -08003015 mScanTimeMillis.detach();
Siddharth Rayed754702018-02-15 12:44:37 -08003016 mSleepTimeMillis.detach();
Adam Lesinski21f76aa2016-01-25 12:27:06 -08003017 mRxTimeMillis.detach();
3018 for (LongSamplingCounter counter : mTxTimeMillis) {
3019 counter.detach();
3020 }
3021 mPowerDrainMaMs.detach();
3022 }
3023
3024 /**
3025 * @return a LongSamplingCounter, measuring time spent in the idle state in
3026 * milliseconds.
3027 */
3028 @Override
3029 public LongSamplingCounter getIdleTimeCounter() {
Roshan Pius81643302016-03-14 16:45:55 -07003030 return mIdleTimeMillis;
Adam Lesinski21f76aa2016-01-25 12:27:06 -08003031 }
3032
3033 /**
Siddharth Rayb50a6842017-12-14 15:15:28 -08003034 * @return a LongSamplingCounter, measuring time spent in the scan state in
3035 * milliseconds.
3036 */
3037 @Override
3038 public LongSamplingCounter getScanTimeCounter() {
3039 return mScanTimeMillis;
3040 }
3041
3042 /**
Siddharth Rayed754702018-02-15 12:44:37 -08003043 * @return a LongSamplingCounter, measuring time spent in the sleep state in
3044 * milliseconds.
3045 */
3046 @Override
3047 public LongSamplingCounter getSleepTimeCounter() {
3048 return mSleepTimeMillis;
3049 }
3050
3051 /**
Adam Lesinski21f76aa2016-01-25 12:27:06 -08003052 * @return a LongSamplingCounter, measuring time spent in the receive state in
3053 * milliseconds.
3054 */
3055 @Override
3056 public LongSamplingCounter getRxTimeCounter() {
3057 return mRxTimeMillis;
3058 }
3059
3060 /**
3061 * @return a LongSamplingCounter[], measuring time spent in various transmit states in
3062 * milliseconds.
3063 */
3064 @Override
3065 public LongSamplingCounter[] getTxTimeCounters() {
3066 return mTxTimeMillis;
3067 }
3068
3069 /**
3070 * @return a LongSamplingCounter, measuring power use in milli-ampere milliseconds (mAmS).
3071 */
3072 @Override
3073 public LongSamplingCounter getPowerCounter() {
3074 return mPowerDrainMaMs;
3075 }
3076 }
3077
Bookatz50df7112017-08-04 14:53:26 -07003078 /** Get Resource Power Manager stats. Create a new one if it doesn't already exist. */
3079 public SamplingTimer getRpmTimerLocked(String name) {
3080 SamplingTimer rpmt = mRpmStats.get(name);
3081 if (rpmt == null) {
3082 rpmt = new SamplingTimer(mClocks, mOnBatteryTimeBase);
3083 mRpmStats.put(name, rpmt);
3084 }
3085 return rpmt;
3086 }
3087
3088 /** Get Screen-off Resource Power Manager stats. Create new one if it doesn't already exist. */
3089 public SamplingTimer getScreenOffRpmTimerLocked(String name) {
3090 SamplingTimer rpmt = mScreenOffRpmStats.get(name);
3091 if (rpmt == null) {
3092 rpmt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
3093 mScreenOffRpmStats.put(name, rpmt);
3094 }
3095 return rpmt;
3096 }
3097
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003098 /*
3099 * Get the wakeup reason counter, and create a new one if one
3100 * doesn't already exist.
3101 */
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07003102 public SamplingTimer getWakeupReasonTimerLocked(String name) {
3103 SamplingTimer timer = mWakeupReasonStats.get(name);
3104 if (timer == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07003105 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07003106 mWakeupReasonStats.put(name, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003107 }
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07003108 return timer;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003109 }
3110
Evan Millarc64edde2009-04-18 12:26:32 -07003111 /*
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003112 * Get the KernelWakelockTimer associated with name, and create a new one if one
Evan Millarc64edde2009-04-18 12:26:32 -07003113 * doesn't already exist.
3114 */
3115 public SamplingTimer getKernelWakelockTimerLocked(String name) {
3116 SamplingTimer kwlt = mKernelWakelockStats.get(name);
3117 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07003118 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Evan Millarc64edde2009-04-18 12:26:32 -07003119 mKernelWakelockStats.put(name, kwlt);
3120 }
3121 return kwlt;
3122 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07003123
James Carr3a226052016-07-01 14:49:52 -07003124 public SamplingTimer getKernelMemoryTimerLocked(long bucket) {
3125 SamplingTimer kmt = mKernelMemoryStats.get(bucket);
3126 if (kmt == null) {
3127 kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase);
3128 mKernelMemoryStats.put(bucket, kmt);
3129 }
3130 return kmt;
3131 }
3132
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003133 private int writeHistoryTag(HistoryTag tag) {
3134 Integer idxObj = mHistoryTagPool.get(tag);
3135 int idx;
3136 if (idxObj != null) {
3137 idx = idxObj;
3138 } else {
3139 idx = mNextHistoryTagIdx;
3140 HistoryTag key = new HistoryTag();
3141 key.setTo(tag);
3142 tag.poolIdx = idx;
3143 mHistoryTagPool.put(key, idx);
3144 mNextHistoryTagIdx++;
3145 mNumHistoryTagChars += key.string.length() + 1;
3146 }
3147 return idx;
3148 }
3149
3150 private void readHistoryTag(int index, HistoryTag tag) {
3151 tag.string = mReadHistoryStrings[index];
3152 tag.uid = mReadHistoryUids[index];
3153 tag.poolIdx = index;
3154 }
3155
Adam Lesinski926969b2016-04-28 17:31:12 -07003156 /*
3157 The history delta format uses flags to denote further data in subsequent ints in the parcel.
3158
3159 There is always the first token, which may contain the delta time, or an indicator of
3160 the length of the time (int or long) following this token.
3161
3162 First token: always present,
3163 31 23 15 7 0
3164 â–ˆ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â–ˆ
3165
3166 T: the delta time if it is <= 0x7fffd. Otherwise 0x7fffe indicates an int immediately
3167 follows containing the time, and 0x7ffff indicates a long immediately follows with the
3168 delta time.
3169 A: battery level changed and an int follows with battery data.
3170 B: state changed and an int follows with state change data.
3171 C: state2 has changed and an int follows with state2 change data.
3172 D: wakelock/wakereason has changed and an wakelock/wakereason struct follows.
3173 E: event data has changed and an event struct follows.
3174 F: battery charge in coulombs has changed and an int with the charge follows.
3175 G: state flag denoting that the mobile radio was active.
3176 H: state flag denoting that the wifi radio was active.
3177 I: state flag denoting that a wifi scan occurred.
3178 J: state flag denoting that a wifi full lock was held.
3179 K: state flag denoting that the gps was on.
3180 L: state flag denoting that a wakelock was held.
3181 M: state flag denoting that the cpu was running.
3182
3183 Time int/long: if T in the first token is 0x7ffff or 0x7fffe, then an int or long follows
3184 with the time delta.
3185
3186 Battery level int: if A in the first token is set,
3187 31 23 15 7 0
3188 â–ˆ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â–ˆ
3189
3190 D: indicates that extra history details follow.
3191 V: the battery voltage.
3192 T: the battery temperature.
3193 L: the battery level (out of 100).
3194
3195 State change int: if B in the first token is set,
3196 31 23 15 7 0
3197 â–ˆS|S|S|H|H|H|P|Pâ–ˆF|E|D|C|B| | |Aâ–ˆ | | | | | | | â–ˆ | | | | | | | â–ˆ
3198
3199 A: wifi multicast was on.
3200 B: battery was plugged in.
3201 C: screen was on.
3202 D: phone was scanning for signal.
3203 E: audio was on.
3204 F: a sensor was active.
3205
3206 State2 change int: if C in the first token is set,
3207 31 23 15 7 0
3208 â–ˆM|L|K|J|I|H|H|Gâ–ˆF|E|D|C| | | | â–ˆ | | | | | | | â–ˆ |B|B|B|A|A|A|Aâ–ˆ
3209
3210 A: 4 bits indicating the wifi supplicant state: {@link BatteryStats#WIFI_SUPPL_STATE_NAMES}.
3211 B: 3 bits indicating the wifi signal strength: 0, 1, 2, 3, 4.
3212 C: a bluetooth scan was active.
3213 D: the camera was active.
3214 E: bluetooth was on.
3215 F: a phone call was active.
3216 G: the device was charging.
3217 H: 2 bits indicating the device-idle (doze) state: off, light, full
3218 I: the flashlight was on.
3219 J: wifi was on.
3220 K: wifi was running.
3221 L: video was playing.
3222 M: power save mode was on.
3223
3224 Wakelock/wakereason struct: if D in the first token is set,
3225 TODO(adamlesinski): describe wakelock/wakereason struct.
3226
3227 Event struct: if E in the first token is set,
3228 TODO(adamlesinski): describe the event struct.
3229
3230 History step details struct: if D in the battery level int is set,
3231 TODO(adamlesinski): describe the history step details struct.
3232
3233 Battery charge int: if F in the first token is set, an int representing the battery charge
3234 in coulombs follows.
3235 */
3236
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003237 // Part of initial delta int that specifies the time delta.
Dianne Hackborne13c4c02014-02-11 17:18:35 -08003238 static final int DELTA_TIME_MASK = 0x7ffff;
3239 static final int DELTA_TIME_LONG = 0x7ffff; // The delta is a following long
3240 static final int DELTA_TIME_INT = 0x7fffe; // The delta is a following int
3241 static final int DELTA_TIME_ABS = 0x7fffd; // Following is an entire abs update.
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003242 // Flag in delta int: a new battery level int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003243 static final int DELTA_BATTERY_LEVEL_FLAG = 0x00080000;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003244 // Flag in delta int: a new full state and battery status int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003245 static final int DELTA_STATE_FLAG = 0x00100000;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08003246 // Flag in delta int: a new full state2 int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003247 static final int DELTA_STATE2_FLAG = 0x00200000;
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003248 // Flag in delta int: contains a wakelock or wakeReason tag.
Adam Lesinski926969b2016-04-28 17:31:12 -07003249 static final int DELTA_WAKELOCK_FLAG = 0x00400000;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003250 // Flag in delta int: contains an event description.
Adam Lesinski926969b2016-04-28 17:31:12 -07003251 static final int DELTA_EVENT_FLAG = 0x00800000;
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003252 // Flag in delta int: contains the battery charge count in uAh.
3253 static final int DELTA_BATTERY_CHARGE_FLAG = 0x01000000;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003254 // These upper bits are the frequently changing state bits.
Adam Lesinski926969b2016-04-28 17:31:12 -07003255 static final int DELTA_STATE_MASK = 0xfe000000;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003256
3257 // These are the pieces of battery state that are packed in to the upper bits of
3258 // the state int that have been packed in to the first delta int. They must fit
Adam Lesinski926969b2016-04-28 17:31:12 -07003259 // in STATE_BATTERY_MASK.
3260 static final int STATE_BATTERY_MASK = 0xff000000;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003261 static final int STATE_BATTERY_STATUS_MASK = 0x00000007;
3262 static final int STATE_BATTERY_STATUS_SHIFT = 29;
3263 static final int STATE_BATTERY_HEALTH_MASK = 0x00000007;
3264 static final int STATE_BATTERY_HEALTH_SHIFT = 26;
3265 static final int STATE_BATTERY_PLUG_MASK = 0x00000003;
3266 static final int STATE_BATTERY_PLUG_SHIFT = 24;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003267
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003268 // We use the low bit of the battery state int to indicate that we have full details
3269 // from a battery level change.
3270 static final int BATTERY_DELTA_LEVEL_FLAG = 0x00000001;
3271
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003272 public void writeHistoryDelta(Parcel dest, HistoryItem cur, HistoryItem last) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003273 if (last == null || cur.cmd != HistoryItem.CMD_UPDATE) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003274 dest.writeInt(DELTA_TIME_ABS);
3275 cur.writeToParcel(dest, 0);
3276 return;
3277 }
3278
3279 final long deltaTime = cur.time - last.time;
3280 final int lastBatteryLevelInt = buildBatteryLevelInt(last);
3281 final int lastStateInt = buildStateInt(last);
3282
3283 int deltaTimeToken;
3284 if (deltaTime < 0 || deltaTime > Integer.MAX_VALUE) {
3285 deltaTimeToken = DELTA_TIME_LONG;
3286 } else if (deltaTime >= DELTA_TIME_ABS) {
3287 deltaTimeToken = DELTA_TIME_INT;
3288 } else {
3289 deltaTimeToken = (int)deltaTime;
3290 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003291 int firstToken = deltaTimeToken | (cur.states&DELTA_STATE_MASK);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003292 final int includeStepDetails = mLastHistoryStepLevel > cur.batteryLevel
3293 ? BATTERY_DELTA_LEVEL_FLAG : 0;
3294 final boolean computeStepDetails = includeStepDetails != 0
3295 || mLastHistoryStepDetails == null;
3296 final int batteryLevelInt = buildBatteryLevelInt(cur) | includeStepDetails;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003297 final boolean batteryLevelIntChanged = batteryLevelInt != lastBatteryLevelInt;
3298 if (batteryLevelIntChanged) {
3299 firstToken |= DELTA_BATTERY_LEVEL_FLAG;
3300 }
3301 final int stateInt = buildStateInt(cur);
3302 final boolean stateIntChanged = stateInt != lastStateInt;
3303 if (stateIntChanged) {
3304 firstToken |= DELTA_STATE_FLAG;
3305 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003306 final boolean state2IntChanged = cur.states2 != last.states2;
3307 if (state2IntChanged) {
3308 firstToken |= DELTA_STATE2_FLAG;
3309 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003310 if (cur.wakelockTag != null || cur.wakeReasonTag != null) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003311 firstToken |= DELTA_WAKELOCK_FLAG;
3312 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003313 if (cur.eventCode != HistoryItem.EVENT_NONE) {
3314 firstToken |= DELTA_EVENT_FLAG;
3315 }
Adam Lesinski926969b2016-04-28 17:31:12 -07003316
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003317 final boolean batteryChargeChanged = cur.batteryChargeUAh != last.batteryChargeUAh;
3318 if (batteryChargeChanged) {
3319 firstToken |= DELTA_BATTERY_CHARGE_FLAG;
Adam Lesinski926969b2016-04-28 17:31:12 -07003320 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003321 dest.writeInt(firstToken);
3322 if (DEBUG) Slog.i(TAG, "WRITE DELTA: firstToken=0x" + Integer.toHexString(firstToken)
3323 + " deltaTime=" + deltaTime);
3324
3325 if (deltaTimeToken >= DELTA_TIME_INT) {
3326 if (deltaTimeToken == DELTA_TIME_INT) {
3327 if (DEBUG) Slog.i(TAG, "WRITE DELTA: int deltaTime=" + (int)deltaTime);
3328 dest.writeInt((int)deltaTime);
3329 } else {
3330 if (DEBUG) Slog.i(TAG, "WRITE DELTA: long deltaTime=" + deltaTime);
3331 dest.writeLong(deltaTime);
3332 }
3333 }
3334 if (batteryLevelIntChanged) {
3335 dest.writeInt(batteryLevelInt);
3336 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryToken=0x"
3337 + Integer.toHexString(batteryLevelInt)
3338 + " batteryLevel=" + cur.batteryLevel
3339 + " batteryTemp=" + cur.batteryTemperature
3340 + " batteryVolt=" + (int)cur.batteryVoltage);
3341 }
3342 if (stateIntChanged) {
3343 dest.writeInt(stateInt);
3344 if (DEBUG) Slog.i(TAG, "WRITE DELTA: stateToken=0x"
3345 + Integer.toHexString(stateInt)
3346 + " batteryStatus=" + cur.batteryStatus
3347 + " batteryHealth=" + cur.batteryHealth
3348 + " batteryPlugType=" + cur.batteryPlugType
3349 + " states=0x" + Integer.toHexString(cur.states));
3350 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003351 if (state2IntChanged) {
3352 dest.writeInt(cur.states2);
3353 if (DEBUG) Slog.i(TAG, "WRITE DELTA: states2=0x"
3354 + Integer.toHexString(cur.states2));
3355 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003356 if (cur.wakelockTag != null || cur.wakeReasonTag != null) {
3357 int wakeLockIndex;
3358 int wakeReasonIndex;
3359 if (cur.wakelockTag != null) {
3360 wakeLockIndex = writeHistoryTag(cur.wakelockTag);
3361 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx
3362 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string);
3363 } else {
3364 wakeLockIndex = 0xffff;
3365 }
3366 if (cur.wakeReasonTag != null) {
3367 wakeReasonIndex = writeHistoryTag(cur.wakeReasonTag);
3368 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx
3369 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string);
3370 } else {
3371 wakeReasonIndex = 0xffff;
3372 }
3373 dest.writeInt((wakeReasonIndex<<16) | wakeLockIndex);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003374 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003375 if (cur.eventCode != HistoryItem.EVENT_NONE) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003376 int index = writeHistoryTag(cur.eventTag);
3377 int codeAndIndex = (cur.eventCode&0xffff) | (index<<16);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003378 dest.writeInt(codeAndIndex);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003379 if (DEBUG) Slog.i(TAG, "WRITE DELTA: event=" + cur.eventCode + " tag=#"
3380 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":"
3381 + cur.eventTag.string);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003382 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003383 if (computeStepDetails) {
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07003384 if (mPlatformIdleStateCallback != null) {
3385 mCurHistoryStepDetails.statPlatformIdleState =
3386 mPlatformIdleStateCallback.getPlatformLowPowerStats();
3387 if (DEBUG) Slog.i(TAG, "WRITE PlatformIdleState:" +
3388 mCurHistoryStepDetails.statPlatformIdleState);
Ahmed ElArabawyd8b44112017-05-23 21:25:02 +00003389
3390 mCurHistoryStepDetails.statSubsystemPowerState =
3391 mPlatformIdleStateCallback.getSubsystemLowPowerStats();
3392 if (DEBUG) Slog.i(TAG, "WRITE SubsystemPowerState:" +
3393 mCurHistoryStepDetails.statSubsystemPowerState);
3394
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07003395 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003396 computeHistoryStepDetails(mCurHistoryStepDetails, mLastHistoryStepDetails);
3397 if (includeStepDetails != 0) {
3398 mCurHistoryStepDetails.writeToParcel(dest);
3399 }
3400 cur.stepDetails = mCurHistoryStepDetails;
3401 mLastHistoryStepDetails = mCurHistoryStepDetails;
3402 } else {
3403 cur.stepDetails = null;
3404 }
3405 if (mLastHistoryStepLevel < cur.batteryLevel) {
3406 mLastHistoryStepDetails = null;
3407 }
3408 mLastHistoryStepLevel = cur.batteryLevel;
Adam Lesinski926969b2016-04-28 17:31:12 -07003409
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003410 if (batteryChargeChanged) {
3411 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryChargeUAh=" + cur.batteryChargeUAh);
3412 dest.writeInt(cur.batteryChargeUAh);
Adam Lesinski926969b2016-04-28 17:31:12 -07003413 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003414 }
3415
3416 private int buildBatteryLevelInt(HistoryItem h) {
3417 return ((((int)h.batteryLevel)<<25)&0xfe000000)
Adam Lesinski3944c812015-11-13 15:54:59 -08003418 | ((((int)h.batteryTemperature)<<15)&0x01ff8000)
3419 | ((((int)h.batteryVoltage)<<1)&0x00007ffe);
3420 }
3421
3422 private void readBatteryLevelInt(int batteryLevelInt, HistoryItem out) {
3423 out.batteryLevel = (byte)((batteryLevelInt & 0xfe000000) >>> 25);
3424 out.batteryTemperature = (short)((batteryLevelInt & 0x01ff8000) >>> 15);
3425 out.batteryVoltage = (char)((batteryLevelInt & 0x00007ffe) >>> 1);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003426 }
3427
3428 private int buildStateInt(HistoryItem h) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003429 int plugType = 0;
3430 if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_AC) != 0) {
3431 plugType = 1;
3432 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_USB) != 0) {
3433 plugType = 2;
3434 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_WIRELESS) != 0) {
3435 plugType = 3;
3436 }
3437 return ((h.batteryStatus&STATE_BATTERY_STATUS_MASK)<<STATE_BATTERY_STATUS_SHIFT)
3438 | ((h.batteryHealth&STATE_BATTERY_HEALTH_MASK)<<STATE_BATTERY_HEALTH_SHIFT)
3439 | ((plugType&STATE_BATTERY_PLUG_MASK)<<STATE_BATTERY_PLUG_SHIFT)
Adam Lesinski926969b2016-04-28 17:31:12 -07003440 | (h.states&(~STATE_BATTERY_MASK));
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003441 }
3442
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003443 private void computeHistoryStepDetails(final HistoryStepDetails out,
3444 final HistoryStepDetails last) {
3445 final HistoryStepDetails tmp = last != null ? mTmpHistoryStepDetails : out;
3446
3447 // Perform a CPU update right after we do this collection, so we have started
3448 // collecting good data for the next step.
3449 requestImmediateCpuUpdate();
3450
3451 if (last == null) {
3452 // We are not generating a delta, so all we need to do is reset the stats
3453 // we will later be doing a delta from.
3454 final int NU = mUidStats.size();
3455 for (int i=0; i<NU; i++) {
3456 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
3457 uid.mLastStepUserTime = uid.mCurStepUserTime;
3458 uid.mLastStepSystemTime = uid.mCurStepSystemTime;
3459 }
3460 mLastStepCpuUserTime = mCurStepCpuUserTime;
3461 mLastStepCpuSystemTime = mCurStepCpuSystemTime;
3462 mLastStepStatUserTime = mCurStepStatUserTime;
3463 mLastStepStatSystemTime = mCurStepStatSystemTime;
3464 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime;
3465 mLastStepStatIrqTime = mCurStepStatIrqTime;
3466 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime;
3467 mLastStepStatIdleTime = mCurStepStatIdleTime;
3468 tmp.clear();
3469 return;
3470 }
3471 if (DEBUG) {
3472 Slog.d(TAG, "Step stats last: user=" + mLastStepCpuUserTime + " sys="
3473 + mLastStepStatSystemTime + " io=" + mLastStepStatIOWaitTime
3474 + " irq=" + mLastStepStatIrqTime + " sirq="
3475 + mLastStepStatSoftIrqTime + " idle=" + mLastStepStatIdleTime);
3476 Slog.d(TAG, "Step stats cur: user=" + mCurStepCpuUserTime + " sys="
3477 + mCurStepStatSystemTime + " io=" + mCurStepStatIOWaitTime
3478 + " irq=" + mCurStepStatIrqTime + " sirq="
3479 + mCurStepStatSoftIrqTime + " idle=" + mCurStepStatIdleTime);
3480 }
3481 out.userTime = (int)(mCurStepCpuUserTime - mLastStepCpuUserTime);
3482 out.systemTime = (int)(mCurStepCpuSystemTime - mLastStepCpuSystemTime);
3483 out.statUserTime = (int)(mCurStepStatUserTime - mLastStepStatUserTime);
3484 out.statSystemTime = (int)(mCurStepStatSystemTime - mLastStepStatSystemTime);
3485 out.statIOWaitTime = (int)(mCurStepStatIOWaitTime - mLastStepStatIOWaitTime);
3486 out.statIrqTime = (int)(mCurStepStatIrqTime - mLastStepStatIrqTime);
3487 out.statSoftIrqTime = (int)(mCurStepStatSoftIrqTime - mLastStepStatSoftIrqTime);
3488 out.statIdlTime = (int)(mCurStepStatIdleTime - mLastStepStatIdleTime);
3489 out.appCpuUid1 = out.appCpuUid2 = out.appCpuUid3 = -1;
3490 out.appCpuUTime1 = out.appCpuUTime2 = out.appCpuUTime3 = 0;
3491 out.appCpuSTime1 = out.appCpuSTime2 = out.appCpuSTime3 = 0;
3492 final int NU = mUidStats.size();
3493 for (int i=0; i<NU; i++) {
3494 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
3495 final int totalUTime = (int)(uid.mCurStepUserTime - uid.mLastStepUserTime);
3496 final int totalSTime = (int)(uid.mCurStepSystemTime - uid.mLastStepSystemTime);
3497 final int totalTime = totalUTime + totalSTime;
3498 uid.mLastStepUserTime = uid.mCurStepUserTime;
3499 uid.mLastStepSystemTime = uid.mCurStepSystemTime;
3500 if (totalTime <= (out.appCpuUTime3+out.appCpuSTime3)) {
3501 continue;
3502 }
3503 if (totalTime <= (out.appCpuUTime2+out.appCpuSTime2)) {
3504 out.appCpuUid3 = uid.mUid;
3505 out.appCpuUTime3 = totalUTime;
3506 out.appCpuSTime3 = totalSTime;
3507 } else {
3508 out.appCpuUid3 = out.appCpuUid2;
3509 out.appCpuUTime3 = out.appCpuUTime2;
3510 out.appCpuSTime3 = out.appCpuSTime2;
3511 if (totalTime <= (out.appCpuUTime1+out.appCpuSTime1)) {
3512 out.appCpuUid2 = uid.mUid;
3513 out.appCpuUTime2 = totalUTime;
3514 out.appCpuSTime2 = totalSTime;
3515 } else {
3516 out.appCpuUid2 = out.appCpuUid1;
3517 out.appCpuUTime2 = out.appCpuUTime1;
3518 out.appCpuSTime2 = out.appCpuSTime1;
3519 out.appCpuUid1 = uid.mUid;
3520 out.appCpuUTime1 = totalUTime;
3521 out.appCpuSTime1 = totalSTime;
3522 }
3523 }
3524 }
3525 mLastStepCpuUserTime = mCurStepCpuUserTime;
3526 mLastStepCpuSystemTime = mCurStepCpuSystemTime;
3527 mLastStepStatUserTime = mCurStepStatUserTime;
3528 mLastStepStatSystemTime = mCurStepStatSystemTime;
3529 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime;
3530 mLastStepStatIrqTime = mCurStepStatIrqTime;
3531 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime;
3532 mLastStepStatIdleTime = mCurStepStatIdleTime;
3533 }
3534
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003535 public void readHistoryDelta(Parcel src, HistoryItem cur) {
3536 int firstToken = src.readInt();
3537 int deltaTimeToken = firstToken&DELTA_TIME_MASK;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003538 cur.cmd = HistoryItem.CMD_UPDATE;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003539 cur.numReadInts = 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003540 if (DEBUG) Slog.i(TAG, "READ DELTA: firstToken=0x" + Integer.toHexString(firstToken)
3541 + " deltaTimeToken=" + deltaTimeToken);
3542
3543 if (deltaTimeToken < DELTA_TIME_ABS) {
3544 cur.time += deltaTimeToken;
3545 } else if (deltaTimeToken == DELTA_TIME_ABS) {
3546 cur.time = src.readLong();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003547 cur.numReadInts += 2;
3548 if (DEBUG) Slog.i(TAG, "READ DELTA: ABS time=" + cur.time);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003549 cur.readFromParcel(src);
3550 return;
3551 } else if (deltaTimeToken == DELTA_TIME_INT) {
3552 int delta = src.readInt();
3553 cur.time += delta;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003554 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003555 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time);
3556 } else {
3557 long delta = src.readLong();
3558 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time);
3559 cur.time += delta;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003560 cur.numReadInts += 2;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003561 }
3562
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003563 final int batteryLevelInt;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003564 if ((firstToken&DELTA_BATTERY_LEVEL_FLAG) != 0) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003565 batteryLevelInt = src.readInt();
Adam Lesinski3944c812015-11-13 15:54:59 -08003566 readBatteryLevelInt(batteryLevelInt, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003567 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003568 if (DEBUG) Slog.i(TAG, "READ DELTA: batteryToken=0x"
3569 + Integer.toHexString(batteryLevelInt)
3570 + " batteryLevel=" + cur.batteryLevel
3571 + " batteryTemp=" + cur.batteryTemperature
3572 + " batteryVolt=" + (int)cur.batteryVoltage);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003573 } else {
3574 batteryLevelInt = 0;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003575 }
3576
3577 if ((firstToken&DELTA_STATE_FLAG) != 0) {
3578 int stateInt = src.readInt();
Adam Lesinski926969b2016-04-28 17:31:12 -07003579 cur.states = (firstToken&DELTA_STATE_MASK) | (stateInt&(~STATE_BATTERY_MASK));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003580 cur.batteryStatus = (byte)((stateInt>>STATE_BATTERY_STATUS_SHIFT)
3581 & STATE_BATTERY_STATUS_MASK);
3582 cur.batteryHealth = (byte)((stateInt>>STATE_BATTERY_HEALTH_SHIFT)
3583 & STATE_BATTERY_HEALTH_MASK);
3584 cur.batteryPlugType = (byte)((stateInt>>STATE_BATTERY_PLUG_SHIFT)
3585 & STATE_BATTERY_PLUG_MASK);
3586 switch (cur.batteryPlugType) {
3587 case 1:
3588 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_AC;
3589 break;
3590 case 2:
3591 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_USB;
3592 break;
3593 case 3:
3594 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_WIRELESS;
3595 break;
3596 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003597 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003598 if (DEBUG) Slog.i(TAG, "READ DELTA: stateToken=0x"
3599 + Integer.toHexString(stateInt)
3600 + " batteryStatus=" + cur.batteryStatus
3601 + " batteryHealth=" + cur.batteryHealth
3602 + " batteryPlugType=" + cur.batteryPlugType
3603 + " states=0x" + Integer.toHexString(cur.states));
3604 } else {
Adam Lesinski926969b2016-04-28 17:31:12 -07003605 cur.states = (firstToken&DELTA_STATE_MASK) | (cur.states&(~STATE_BATTERY_MASK));
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003606 }
3607
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003608 if ((firstToken&DELTA_STATE2_FLAG) != 0) {
3609 cur.states2 = src.readInt();
3610 if (DEBUG) Slog.i(TAG, "READ DELTA: states2=0x"
3611 + Integer.toHexString(cur.states2));
3612 }
3613
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003614 if ((firstToken&DELTA_WAKELOCK_FLAG) != 0) {
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003615 int indexes = src.readInt();
3616 int wakeLockIndex = indexes&0xffff;
3617 int wakeReasonIndex = (indexes>>16)&0xffff;
3618 if (wakeLockIndex != 0xffff) {
3619 cur.wakelockTag = cur.localWakelockTag;
3620 readHistoryTag(wakeLockIndex, cur.wakelockTag);
3621 if (DEBUG) Slog.i(TAG, "READ DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx
3622 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string);
3623 } else {
3624 cur.wakelockTag = null;
3625 }
3626 if (wakeReasonIndex != 0xffff) {
3627 cur.wakeReasonTag = cur.localWakeReasonTag;
3628 readHistoryTag(wakeReasonIndex, cur.wakeReasonTag);
3629 if (DEBUG) Slog.i(TAG, "READ DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx
3630 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string);
3631 } else {
3632 cur.wakeReasonTag = null;
3633 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003634 cur.numReadInts += 1;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003635 } else {
3636 cur.wakelockTag = null;
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003637 cur.wakeReasonTag = null;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003638 }
3639
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003640 if ((firstToken&DELTA_EVENT_FLAG) != 0) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003641 cur.eventTag = cur.localEventTag;
3642 final int codeAndIndex = src.readInt();
Dianne Hackborn099bc622014-01-22 13:39:16 -08003643 cur.eventCode = (codeAndIndex&0xffff);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003644 final int index = ((codeAndIndex>>16)&0xffff);
3645 readHistoryTag(index, cur.eventTag);
3646 cur.numReadInts += 1;
3647 if (DEBUG) Slog.i(TAG, "READ DELTA: event=" + cur.eventCode + " tag=#"
3648 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":"
3649 + cur.eventTag.string);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003650 } else {
3651 cur.eventCode = HistoryItem.EVENT_NONE;
3652 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003653
3654 if ((batteryLevelInt&BATTERY_DELTA_LEVEL_FLAG) != 0) {
3655 cur.stepDetails = mReadHistoryStepDetails;
3656 cur.stepDetails.readFromParcel(src);
3657 } else {
3658 cur.stepDetails = null;
3659 }
Adam Lesinski926969b2016-04-28 17:31:12 -07003660
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003661 if ((firstToken&DELTA_BATTERY_CHARGE_FLAG) != 0) {
3662 cur.batteryChargeUAh = src.readInt();
Adam Lesinski926969b2016-04-28 17:31:12 -07003663 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003664 }
3665
Dianne Hackbornfc064132014-06-02 12:42:12 -07003666 @Override
3667 public void commitCurrentHistoryBatchLocked() {
3668 mHistoryLastWritten.cmd = HistoryItem.CMD_NULL;
3669 }
3670
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003671 void addHistoryBufferLocked(long elapsedRealtimeMs, HistoryItem cur) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003672 if (!mHaveBatteryLevel || !mRecordingHistory) {
3673 return;
3674 }
3675
Dianne Hackborn40c87252014-03-19 16:55:40 -07003676 final long timeDiff = (mHistoryBaseTime+elapsedRealtimeMs) - mHistoryLastWritten.time;
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003677 final int diffStates = mHistoryLastWritten.states^(cur.states&mActiveHistoryStates);
3678 final int diffStates2 = mHistoryLastWritten.states2^(cur.states2&mActiveHistoryStates2);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003679 final int lastDiffStates = mHistoryLastWritten.states^mHistoryLastLastWritten.states;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003680 final int lastDiffStates2 = mHistoryLastWritten.states2^mHistoryLastLastWritten.states2;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003681 if (DEBUG) Slog.i(TAG, "ADD: tdelta=" + timeDiff + " diff="
3682 + Integer.toHexString(diffStates) + " lastDiff="
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003683 + Integer.toHexString(lastDiffStates) + " diff2="
3684 + Integer.toHexString(diffStates2) + " lastDiff2="
3685 + Integer.toHexString(lastDiffStates2));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003686 if (mHistoryBufferLastPos >= 0 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003687 && timeDiff < 1000 && (diffStates&lastDiffStates) == 0
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003688 && (diffStates2&lastDiffStates2) == 0
3689 && (mHistoryLastWritten.wakelockTag == null || cur.wakelockTag == null)
3690 && (mHistoryLastWritten.wakeReasonTag == null || cur.wakeReasonTag == null)
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003691 && mHistoryLastWritten.stepDetails == null
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003692 && (mHistoryLastWritten.eventCode == HistoryItem.EVENT_NONE
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003693 || cur.eventCode == HistoryItem.EVENT_NONE)
3694 && mHistoryLastWritten.batteryLevel == cur.batteryLevel
3695 && mHistoryLastWritten.batteryStatus == cur.batteryStatus
3696 && mHistoryLastWritten.batteryHealth == cur.batteryHealth
3697 && mHistoryLastWritten.batteryPlugType == cur.batteryPlugType
3698 && mHistoryLastWritten.batteryTemperature == cur.batteryTemperature
3699 && mHistoryLastWritten.batteryVoltage == cur.batteryVoltage) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003700 // We can merge this new change in with the last one. Merging is
Dianne Hackborn40c87252014-03-19 16:55:40 -07003701 // allowed as long as only the states have changed, and within those states
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003702 // as long as no bit has changed both between now and the last entry, as
3703 // well as the last entry and the one before it (so we capture any toggles).
3704 if (DEBUG) Slog.i(TAG, "ADD: rewinding back to " + mHistoryBufferLastPos);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003705 mHistoryBuffer.setDataSize(mHistoryBufferLastPos);
3706 mHistoryBuffer.setDataPosition(mHistoryBufferLastPos);
3707 mHistoryBufferLastPos = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003708 elapsedRealtimeMs = mHistoryLastWritten.time - mHistoryBaseTime;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003709 // If the last written history had a wakelock tag, we need to retain it.
3710 // Note that the condition above made sure that we aren't in a case where
3711 // both it and the current history item have a wakelock tag.
3712 if (mHistoryLastWritten.wakelockTag != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003713 cur.wakelockTag = cur.localWakelockTag;
3714 cur.wakelockTag.setTo(mHistoryLastWritten.wakelockTag);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003715 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003716 // If the last written history had a wake reason tag, we need to retain it.
3717 // Note that the condition above made sure that we aren't in a case where
3718 // both it and the current history item have a wakelock tag.
3719 if (mHistoryLastWritten.wakeReasonTag != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003720 cur.wakeReasonTag = cur.localWakeReasonTag;
3721 cur.wakeReasonTag.setTo(mHistoryLastWritten.wakeReasonTag);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003722 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003723 // If the last written history had an event, we need to retain it.
3724 // Note that the condition above made sure that we aren't in a case where
3725 // both it and the current history item have an event.
3726 if (mHistoryLastWritten.eventCode != HistoryItem.EVENT_NONE) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003727 cur.eventCode = mHistoryLastWritten.eventCode;
3728 cur.eventTag = cur.localEventTag;
3729 cur.eventTag.setTo(mHistoryLastWritten.eventTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003730 }
Dianne Hackborn1fadab52011-04-14 17:57:33 -07003731 mHistoryLastWritten.setTo(mHistoryLastLastWritten);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003732 }
3733
Adam Lesinski45489782016-12-15 23:45:17 -08003734 boolean recordResetDueToOverflow = false;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003735 final int dataSize = mHistoryBuffer.dataSize();
Adam Lesinski45489782016-12-15 23:45:17 -08003736 if (dataSize >= MAX_MAX_HISTORY_BUFFER*3) {
3737 // Clients can't deal with history buffers this large. This only
3738 // really happens when the device is on charger and interacted with
3739 // for long periods of time, like in retail mode. Since the device is
3740 // most likely charged, when unplugged, stats would have reset anyways.
3741 // Reset the stats and mark that we overflowed.
3742 // b/32540341
3743 resetAllStatsLocked();
3744
3745 // Mark that we want to set *OVERFLOW* event and the RESET:START
3746 // events.
3747 recordResetDueToOverflow = true;
3748
3749 } else if (dataSize >= MAX_HISTORY_BUFFER) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003750 if (!mHistoryOverflow) {
3751 mHistoryOverflow = true;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003752 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, cur);
3753 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_OVERFLOW, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003754 return;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003755 }
3756
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003757 // After overflow, we allow various bit-wise states to settle to 0.
3758 boolean writeAnyway = false;
3759 final int curStates = cur.states & HistoryItem.SETTLE_TO_ZERO_STATES
3760 & mActiveHistoryStates;
3761 if (mHistoryLastWritten.states != curStates) {
3762 // mActiveHistoryStates keeps track of which bits in .states are now being
3763 // forced to 0.
3764 int old = mActiveHistoryStates;
3765 mActiveHistoryStates &= curStates | ~HistoryItem.SETTLE_TO_ZERO_STATES;
3766 writeAnyway |= old != mActiveHistoryStates;
3767 }
3768 final int curStates2 = cur.states2 & HistoryItem.SETTLE_TO_ZERO_STATES2
3769 & mActiveHistoryStates2;
3770 if (mHistoryLastWritten.states2 != curStates2) {
3771 // mActiveHistoryStates2 keeps track of which bits in .states2 are now being
3772 // forced to 0.
3773 int old = mActiveHistoryStates2;
3774 mActiveHistoryStates2 &= curStates2 | ~HistoryItem.SETTLE_TO_ZERO_STATES2;
3775 writeAnyway |= old != mActiveHistoryStates2;
3776 }
3777
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003778 // Once we've reached the maximum number of items, we only
3779 // record changes to the battery level and the most interesting states.
3780 // Once we've reached the maximum maximum number of items, we only
3781 // record changes to the battery level.
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003782 if (!writeAnyway && mHistoryLastWritten.batteryLevel == cur.batteryLevel &&
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003783 (dataSize >= MAX_MAX_HISTORY_BUFFER
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003784 || ((mHistoryLastWritten.states^cur.states)
Dianne Hackborn3251b902014-06-20 14:40:53 -07003785 & HistoryItem.MOST_INTERESTING_STATES) == 0
3786 || ((mHistoryLastWritten.states2^cur.states2)
3787 & HistoryItem.MOST_INTERESTING_STATES2) == 0)) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003788 return;
3789 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003790
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003791 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003792 return;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003793 }
3794
Adam Lesinski45489782016-12-15 23:45:17 -08003795 if (dataSize == 0 || recordResetDueToOverflow) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003796 // The history is currently empty; we need it to start with a time stamp.
3797 cur.currentTime = System.currentTimeMillis();
Adam Lesinski45489782016-12-15 23:45:17 -08003798 if (recordResetDueToOverflow) {
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003799 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_OVERFLOW, cur);
Adam Lesinski45489782016-12-15 23:45:17 -08003800 }
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003801 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_RESET, cur);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003802 }
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003803 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003804 }
3805
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003806 private void addHistoryBufferLocked(long elapsedRealtimeMs, byte cmd, HistoryItem cur) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003807 if (mIteratingHistory) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003808 throw new IllegalStateException("Can't do this while iterating history!");
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003809 }
3810 mHistoryBufferLastPos = mHistoryBuffer.dataPosition();
3811 mHistoryLastLastWritten.setTo(mHistoryLastWritten);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003812 mHistoryLastWritten.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003813 mHistoryLastWritten.states &= mActiveHistoryStates;
3814 mHistoryLastWritten.states2 &= mActiveHistoryStates2;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003815 writeHistoryDelta(mHistoryBuffer, mHistoryLastWritten, mHistoryLastLastWritten);
Dianne Hackborn40c87252014-03-19 16:55:40 -07003816 mLastHistoryElapsedRealtime = elapsedRealtimeMs;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003817 cur.wakelockTag = null;
3818 cur.wakeReasonTag = null;
3819 cur.eventCode = HistoryItem.EVENT_NONE;
3820 cur.eventTag = null;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003821 if (DEBUG_HISTORY) Slog.i(TAG, "Writing history buffer: was " + mHistoryBufferLastPos
3822 + " now " + mHistoryBuffer.dataPosition()
3823 + " size is now " + mHistoryBuffer.dataSize());
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003824 }
3825
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003826 int mChangedStates = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003827 int mChangedStates2 = 0;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003828
Dianne Hackborn40c87252014-03-19 16:55:40 -07003829 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003830 if (mTrackRunningHistoryElapsedRealtime != 0) {
3831 final long diffElapsed = elapsedRealtimeMs - mTrackRunningHistoryElapsedRealtime;
3832 final long diffUptime = uptimeMs - mTrackRunningHistoryUptime;
3833 if (diffUptime < (diffElapsed-20)) {
3834 final long wakeElapsedTime = elapsedRealtimeMs - (diffElapsed - diffUptime);
3835 mHistoryAddTmp.setTo(mHistoryLastWritten);
3836 mHistoryAddTmp.wakelockTag = null;
3837 mHistoryAddTmp.wakeReasonTag = null;
3838 mHistoryAddTmp.eventCode = HistoryItem.EVENT_NONE;
3839 mHistoryAddTmp.states &= ~HistoryItem.STATE_CPU_RUNNING_FLAG;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003840 addHistoryRecordInnerLocked(wakeElapsedTime, mHistoryAddTmp);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003841 }
3842 }
3843 mHistoryCur.states |= HistoryItem.STATE_CPU_RUNNING_FLAG;
3844 mTrackRunningHistoryElapsedRealtime = elapsedRealtimeMs;
3845 mTrackRunningHistoryUptime = uptimeMs;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003846 addHistoryRecordInnerLocked(elapsedRealtimeMs, mHistoryCur);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003847 }
3848
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003849 void addHistoryRecordInnerLocked(long elapsedRealtimeMs, HistoryItem cur) {
3850 addHistoryBufferLocked(elapsedRealtimeMs, cur);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003851
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003852 if (!USE_OLD_HISTORY) {
3853 return;
3854 }
3855
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003856 if (!mHaveBatteryLevel || !mRecordingHistory) {
3857 return;
3858 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003859
3860 // If the current time is basically the same as the last time,
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003861 // and no states have since the last recorded entry changed and
3862 // are now resetting back to their original value, then just collapse
3863 // into one record.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003864 if (mHistoryEnd != null && mHistoryEnd.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn40c87252014-03-19 16:55:40 -07003865 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+1000)
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003866 && ((mHistoryEnd.states^cur.states)&mChangedStates&mActiveHistoryStates) == 0
3867 && ((mHistoryEnd.states2^cur.states2)&mChangedStates2&mActiveHistoryStates2) == 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003868 // If the current is the same as the one before, then we no
3869 // longer need the entry.
3870 if (mHistoryLastEnd != null && mHistoryLastEnd.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn40c87252014-03-19 16:55:40 -07003871 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+500)
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003872 && mHistoryLastEnd.sameNonEvent(cur)) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003873 mHistoryLastEnd.next = null;
3874 mHistoryEnd.next = mHistoryCache;
3875 mHistoryCache = mHistoryEnd;
3876 mHistoryEnd = mHistoryLastEnd;
3877 mHistoryLastEnd = null;
3878 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003879 mChangedStates |= mHistoryEnd.states^(cur.states&mActiveHistoryStates);
3880 mChangedStates2 |= mHistoryEnd.states^(cur.states2&mActiveHistoryStates2);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003881 mHistoryEnd.setTo(mHistoryEnd.time, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003882 }
3883 return;
3884 }
3885
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003886 mChangedStates = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003887 mChangedStates2 = 0;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003888
3889 if (mNumHistoryItems == MAX_HISTORY_ITEMS
3890 || mNumHistoryItems == MAX_MAX_HISTORY_ITEMS) {
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003891 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_OVERFLOW, cur);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07003892 }
3893
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003894 if (mNumHistoryItems >= MAX_HISTORY_ITEMS) {
3895 // Once we've reached the maximum number of items, we only
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003896 // record changes to the battery level and the most interesting states.
3897 // Once we've reached the maximum maximum number of items, we only
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003898 // record changes to the battery level.
3899 if (mHistoryEnd != null && mHistoryEnd.batteryLevel
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003900 == cur.batteryLevel &&
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003901 (mNumHistoryItems >= MAX_MAX_HISTORY_ITEMS
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003902 || ((mHistoryEnd.states^(cur.states&mActiveHistoryStates))
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003903 & HistoryItem.MOST_INTERESTING_STATES) == 0)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003904 return;
3905 }
3906 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003907
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003908 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003909 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003910
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003911 public void addHistoryEventLocked(long elapsedRealtimeMs, long uptimeMs, int code,
Dianne Hackborn40c87252014-03-19 16:55:40 -07003912 String name, int uid) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003913 mHistoryCur.eventCode = code;
3914 mHistoryCur.eventTag = mHistoryCur.localEventTag;
3915 mHistoryCur.eventTag.string = name;
3916 mHistoryCur.eventTag.uid = uid;
Dianne Hackborn4590e522014-03-24 13:36:46 -07003917 addHistoryRecordLocked(elapsedRealtimeMs, uptimeMs);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003918 }
3919
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003920 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs, byte cmd, HistoryItem cur) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003921 HistoryItem rec = mHistoryCache;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003922 if (rec != null) {
3923 mHistoryCache = rec.next;
3924 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003925 rec = new HistoryItem();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003926 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003927 rec.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003928
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003929 addHistoryRecordLocked(rec);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003930 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003931
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003932 void addHistoryRecordLocked(HistoryItem rec) {
3933 mNumHistoryItems++;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003934 rec.next = null;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003935 mHistoryLastEnd = mHistoryEnd;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003936 if (mHistoryEnd != null) {
3937 mHistoryEnd.next = rec;
3938 mHistoryEnd = rec;
3939 } else {
3940 mHistory = mHistoryEnd = rec;
3941 }
3942 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003943
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003944 void clearHistoryLocked() {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003945 if (DEBUG_HISTORY) Slog.i(TAG, "********** CLEARING HISTORY!");
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003946 if (USE_OLD_HISTORY) {
3947 if (mHistory != null) {
3948 mHistoryEnd.next = mHistoryCache;
3949 mHistoryCache = mHistory;
3950 mHistory = mHistoryLastEnd = mHistoryEnd = null;
3951 }
3952 mNumHistoryItems = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003953 }
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003954
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003955 mHistoryBaseTime = 0;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003956 mLastHistoryElapsedRealtime = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003957 mTrackRunningHistoryElapsedRealtime = 0;
3958 mTrackRunningHistoryUptime = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003959
3960 mHistoryBuffer.setDataSize(0);
3961 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003962 mHistoryBuffer.setDataCapacity(MAX_HISTORY_BUFFER / 2);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003963 mHistoryLastLastWritten.clear();
3964 mHistoryLastWritten.clear();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003965 mHistoryTagPool.clear();
3966 mNextHistoryTagIdx = 0;
3967 mNumHistoryTagChars = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003968 mHistoryBufferLastPos = -1;
3969 mHistoryOverflow = false;
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003970 mActiveHistoryStates = 0xffffffff;
3971 mActiveHistoryStates2 = 0xffffffff;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003972 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003973
Andreas Gampe3f24e692018-02-05 13:24:28 -08003974 @GuardedBy("this")
Mike Mac2f518a2017-09-19 16:06:03 -07003975 public void updateTimeBasesLocked(boolean unplugged, int screenState, long uptime,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003976 long realtime) {
Mike Maa7724752017-10-10 15:29:25 -07003977 final boolean screenOff = !isScreenOn(screenState);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003978 final boolean updateOnBatteryTimeBase = unplugged != mOnBatteryTimeBase.isRunning();
3979 final boolean updateOnBatteryScreenOffTimeBase =
3980 (unplugged && screenOff) != mOnBatteryScreenOffTimeBase.isRunning();
Bookatz867c0d72017-03-07 18:23:42 -08003981
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003982 if (updateOnBatteryScreenOffTimeBase || updateOnBatteryTimeBase) {
3983 if (updateOnBatteryScreenOffTimeBase) {
3984 updateKernelWakelocksLocked();
3985 updateBatteryPropertiesLocked();
Bookatz867c0d72017-03-07 18:23:42 -08003986 }
Bookatz82b341172017-09-07 19:06:08 -07003987 // This if{} is only necessary due to SCREEN_OFF_RPM_STATS_ENABLED, which exists because
3988 // updateRpmStatsLocked is too slow to run each screen change. When the speed is
3989 // improved, remove the surrounding if{}.
3990 if (SCREEN_OFF_RPM_STATS_ENABLED || updateOnBatteryTimeBase) {
3991 updateRpmStatsLocked(); // if either OnBattery or OnBatteryScreenOff timebase changes.
3992 }
Adam Lesinski72478f02015-06-17 15:39:43 -07003993 if (DEBUG_ENERGY_CPU) {
Mike Mac2f518a2017-09-19 16:06:03 -07003994 Slog.d(TAG, "Updating cpu time because screen is now "
3995 + Display.stateToString(screenState)
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003996 + " and battery is " + (unplugged ? "on" : "off"));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003997 }
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003998
3999 mOnBatteryTimeBase.setRunning(unplugged, uptime, realtime);
Mike Mac2f518a2017-09-19 16:06:03 -07004000 if (updateOnBatteryTimeBase) {
4001 for (int i = mUidStats.size() - 1; i >= 0; --i) {
4002 mUidStats.valueAt(i).updateOnBatteryBgTimeBase(uptime, realtime);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07004003 }
Mike Mac2f518a2017-09-19 16:06:03 -07004004 }
4005 if (updateOnBatteryScreenOffTimeBase) {
4006 mOnBatteryScreenOffTimeBase.setRunning(unplugged && screenOff, uptime, realtime);
4007 for (int i = mUidStats.size() - 1; i >= 0; --i) {
4008 mUidStats.valueAt(i).updateOnBatteryScreenOffBgTimeBase(uptime, realtime);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07004009 }
Bookatzc8c44962017-05-11 12:12:54 -07004010 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004011 }
4012 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07004013
Adam Lesinskie1f480d2017-02-15 18:51:23 -08004014 private void updateBatteryPropertiesLocked() {
4015 try {
4016 IBatteryPropertiesRegistrar registrar = IBatteryPropertiesRegistrar.Stub.asInterface(
4017 ServiceManager.getService("batteryproperties"));
4018 registrar.scheduleUpdate();
4019 } catch (RemoteException e) {
4020 // Ignore.
4021 }
4022 }
4023
Dianne Hackborn099bc622014-01-22 13:39:16 -08004024 public void addIsolatedUidLocked(int isolatedUid, int appUid) {
4025 mIsolatedUids.put(isolatedUid, appUid);
Bookatz90867622018-01-31 15:05:57 -08004026 StatsLog.write(StatsLog.ISOLATED_UID_CHANGED, appUid, isolatedUid,
4027 StatsLog.ISOLATED_UID_CHANGED__EVENT__CREATED);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08004028 final Uid u = getUidStatsLocked(appUid);
4029 u.addIsolatedUid(isolatedUid);
Dianne Hackborn099bc622014-01-22 13:39:16 -08004030 }
4031
Adam Lesinski61db88f2015-07-01 15:05:07 -07004032 /**
4033 * Schedules a read of the latest cpu times before removing the isolated UID.
4034 * @see #removeIsolatedUidLocked(int)
4035 */
4036 public void scheduleRemoveIsolatedUidLocked(int isolatedUid, int appUid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004037 int curUid = mIsolatedUids.get(isolatedUid, -1);
4038 if (curUid == appUid) {
Adam Lesinski61db88f2015-07-01 15:05:07 -07004039 if (mExternalSync != null) {
4040 mExternalSync.scheduleCpuSyncDueToRemovedUid(isolatedUid);
4041 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08004042 }
4043 }
4044
Adam Lesinski61db88f2015-07-01 15:05:07 -07004045 /**
4046 * This should only be called after the cpu times have been read.
4047 * @see #scheduleRemoveIsolatedUidLocked(int, int)
4048 */
Andreas Gampe3f24e692018-02-05 13:24:28 -08004049 @GuardedBy("this")
Adam Lesinski61db88f2015-07-01 15:05:07 -07004050 public void removeIsolatedUidLocked(int isolatedUid) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08004051 StatsLog.write(
Bookatz90867622018-01-31 15:05:57 -08004052 StatsLog.ISOLATED_UID_CHANGED, mIsolatedUids.get(isolatedUid, -1),
4053 isolatedUid, StatsLog.ISOLATED_UID_CHANGED__EVENT__REMOVED);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08004054 final int idx = mIsolatedUids.indexOfKey(isolatedUid);
4055 if (idx >= 0) {
4056 final int ownerUid = mIsolatedUids.valueAt(idx);
4057 final Uid u = getUidStatsLocked(ownerUid);
4058 u.removeIsolatedUid(isolatedUid);
4059 mIsolatedUids.removeAt(idx);
4060 }
Mike Ma234d1822018-03-13 18:53:21 -07004061 mPendingRemovedUids.add(new UidToRemove(isolatedUid, mClocks.elapsedRealtime()));
Adam Lesinski61db88f2015-07-01 15:05:07 -07004062 }
4063
Dianne Hackborn099bc622014-01-22 13:39:16 -08004064 public int mapUid(int uid) {
4065 int isolated = mIsolatedUids.get(uid, -1);
4066 return isolated > 0 ? isolated : uid;
4067 }
4068
4069 public void noteEventLocked(int code, String name, int uid) {
4070 uid = mapUid(uid);
Dianne Hackborn37de0982014-05-09 09:32:18 -07004071 if (!mActiveEvents.updateState(code, name, uid, 0)) {
4072 return;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08004073 }
Joe Onoratoabded112016-02-08 16:49:39 -08004074 final long elapsedRealtime = mClocks.elapsedRealtime();
4075 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -07004076 addHistoryEventLocked(elapsedRealtime, uptime, code, name, uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -08004077 }
4078
Dianne Hackbornd48954f2015-07-22 17:20:33 -07004079 boolean ensureStartClockTime(final long currentTime) {
4080 final long ABOUT_ONE_YEAR = 365*24*60*60*1000L;
4081 if (currentTime > ABOUT_ONE_YEAR && mStartClockTime < (currentTime-ABOUT_ONE_YEAR)) {
4082 // If the start clock time has changed by more than a year, then presumably
4083 // the previous time was completely bogus. So we are going to figure out a
4084 // new time based on how much time has elapsed since we started counting.
Joe Onoratoabded112016-02-08 16:49:39 -08004085 mStartClockTime = currentTime - (mClocks.elapsedRealtime()-(mRealtimeStart/1000));
Dianne Hackbornd48954f2015-07-22 17:20:33 -07004086 return true;
4087 }
4088 return false;
4089 }
4090
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07004091 public void noteCurrentTimeChangedLocked() {
4092 final long currentTime = System.currentTimeMillis();
Joe Onoratoabded112016-02-08 16:49:39 -08004093 final long elapsedRealtime = mClocks.elapsedRealtime();
4094 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07004095 recordCurrentTimeChangeLocked(currentTime, elapsedRealtime, uptime);
Dianne Hackbornd48954f2015-07-22 17:20:33 -07004096 ensureStartClockTime(currentTime);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07004097 }
4098
Dianne Hackborn61659e52014-07-09 16:13:01 -07004099 public void noteProcessStartLocked(String name, int uid) {
4100 uid = mapUid(uid);
4101 if (isOnBattery()) {
4102 Uid u = getUidStatsLocked(uid);
4103 u.getProcessStatsLocked(name).incStartsLocked();
4104 }
4105 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_START, name, uid, 0)) {
4106 return;
4107 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004108 if (!mRecordAllHistory) {
4109 return;
4110 }
Joe Onoratoabded112016-02-08 16:49:39 -08004111 final long elapsedRealtime = mClocks.elapsedRealtime();
4112 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn61659e52014-07-09 16:13:01 -07004113 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_START, name, uid);
4114 }
4115
Dianne Hackborn1e01d162014-12-04 17:46:42 -08004116 public void noteProcessCrashLocked(String name, int uid) {
4117 uid = mapUid(uid);
4118 if (isOnBattery()) {
4119 Uid u = getUidStatsLocked(uid);
4120 u.getProcessStatsLocked(name).incNumCrashesLocked();
4121 }
4122 }
4123
4124 public void noteProcessAnrLocked(String name, int uid) {
4125 uid = mapUid(uid);
4126 if (isOnBattery()) {
4127 Uid u = getUidStatsLocked(uid);
4128 u.getProcessStatsLocked(name).incNumAnrsLocked();
4129 }
4130 }
4131
Dianne Hackborna8d10942015-11-19 17:55:19 -08004132 public void noteUidProcessStateLocked(int uid, int state) {
Amith Yamasanifd3caf62017-07-26 11:48:35 -07004133 int parentUid = mapUid(uid);
4134 if (uid != parentUid) {
4135 // Isolated UIDs process state is already rolled up into parent, so no need to track
4136 // Otherwise the parent's process state will get downgraded incorrectly
4137 return;
4138 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08004139 getUidStatsLocked(uid).updateUidProcessStateLocked(state);
Dianne Hackborn61659e52014-07-09 16:13:01 -07004140 }
4141
4142 public void noteProcessFinishLocked(String name, int uid) {
4143 uid = mapUid(uid);
4144 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_FINISH, name, uid, 0)) {
4145 return;
4146 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004147 if (!mRecordAllHistory) {
4148 return;
4149 }
Joe Onoratoabded112016-02-08 16:49:39 -08004150 final long elapsedRealtime = mClocks.elapsedRealtime();
4151 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004152 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_FINISH, name, uid);
Dianne Hackborn61659e52014-07-09 16:13:01 -07004153 }
4154
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004155 public void noteSyncStartLocked(String name, int uid) {
4156 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004157 final long elapsedRealtime = mClocks.elapsedRealtime();
4158 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004159 getUidStatsLocked(uid).noteStartSyncLocked(name, elapsedRealtime);
4160 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_START, name, uid, 0)) {
4161 return;
4162 }
4163 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_START, name, uid);
4164 }
4165
4166 public void noteSyncFinishLocked(String name, int uid) {
4167 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004168 final long elapsedRealtime = mClocks.elapsedRealtime();
4169 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004170 getUidStatsLocked(uid).noteStopSyncLocked(name, elapsedRealtime);
4171 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_FINISH, name, uid, 0)) {
4172 return;
4173 }
4174 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_FINISH, name, uid);
4175 }
4176
4177 public void noteJobStartLocked(String name, int uid) {
4178 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004179 final long elapsedRealtime = mClocks.elapsedRealtime();
4180 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004181 getUidStatsLocked(uid).noteStartJobLocked(name, elapsedRealtime);
4182 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_START, name, uid, 0)) {
4183 return;
4184 }
4185 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_START, name, uid);
4186 }
4187
Dianne Hackborn94326cb2017-06-28 16:17:20 -07004188 public void noteJobFinishLocked(String name, int uid, int stopReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004189 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004190 final long elapsedRealtime = mClocks.elapsedRealtime();
4191 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07004192 getUidStatsLocked(uid).noteStopJobLocked(name, elapsedRealtime, stopReason);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004193 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_FINISH, name, uid, 0)) {
4194 return;
4195 }
4196 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_FINISH, name, uid);
4197 }
4198
Amith Yamasani977e11f2018-02-16 11:29:54 -08004199 public void noteJobsDeferredLocked(int uid, int numDeferred, long sinceLast) {
4200 uid = mapUid(uid);
4201 getUidStatsLocked(uid).noteJobsDeferredLocked(numDeferred, sinceLast);
4202 }
4203
Narayan Kamath695cf722017-12-21 18:32:47 +00004204 public void noteAlarmStartLocked(String name, WorkSource workSource, int uid) {
4205 noteAlarmStartOrFinishLocked(HistoryItem.EVENT_ALARM_START, name, workSource, uid);
Dianne Hackborn1e383822015-04-10 14:02:33 -07004206 }
4207
Narayan Kamath695cf722017-12-21 18:32:47 +00004208 public void noteAlarmFinishLocked(String name, WorkSource workSource, int uid) {
4209 noteAlarmStartOrFinishLocked(HistoryItem.EVENT_ALARM_FINISH, name, workSource, uid);
4210 }
4211
4212 private void noteAlarmStartOrFinishLocked(int historyItem, String name, WorkSource workSource,
4213 int uid) {
Dianne Hackborn1e383822015-04-10 14:02:33 -07004214 if (!mRecordAllHistory) {
4215 return;
4216 }
Narayan Kamath695cf722017-12-21 18:32:47 +00004217
Joe Onoratoabded112016-02-08 16:49:39 -08004218 final long elapsedRealtime = mClocks.elapsedRealtime();
4219 final long uptime = mClocks.uptimeMillis();
Narayan Kamath695cf722017-12-21 18:32:47 +00004220
4221 if (workSource != null) {
4222 for (int i = 0; i < workSource.size(); ++i) {
4223 uid = mapUid(workSource.get(i));
4224 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4225 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4226 }
4227 }
4228
4229 List<WorkChain> workChains = workSource.getWorkChains();
4230 if (workChains != null) {
4231 for (int i = 0; i < workChains.size(); ++i) {
4232 uid = mapUid(workChains.get(i).getAttributionUid());
4233 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4234 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4235 }
4236 }
4237 }
4238 } else {
4239 uid = mapUid(uid);
4240
4241 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4242 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4243 }
4244 }
4245 }
4246
4247 public void noteWakupAlarmLocked(String packageName, int uid, WorkSource workSource,
4248 String tag) {
Narayan Kamath695cf722017-12-21 18:32:47 +00004249 if (workSource != null) {
4250 for (int i = 0; i < workSource.size(); ++i) {
4251 uid = workSource.get(i);
4252 final String workSourceName = workSource.getName(i);
4253
Tej Singh6f724c42018-01-03 20:02:03 -08004254 if (isOnBattery()) {
4255 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid,
4256 workSourceName != null ? workSourceName : packageName);
4257 pkg.noteWakeupAlarmLocked(tag);
4258 }
Yangster-mac2f5daec2018-01-16 10:23:15 -08004259 StatsLog.write_non_chained(StatsLog.WAKEUP_ALARM_OCCURRED, workSource.get(i),
4260 workSource.getName(i), tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004261 }
4262
4263 ArrayList<WorkChain> workChains = workSource.getWorkChains();
4264 if (workChains != null) {
4265 for (int i = 0; i < workChains.size(); ++i) {
4266 final WorkChain wc = workChains.get(i);
4267 uid = wc.getAttributionUid();
4268
Tej Singh6f724c42018-01-03 20:02:03 -08004269 if (isOnBattery()) {
4270 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid, packageName);
4271 pkg.noteWakeupAlarmLocked(tag);
4272 }
Yangster-macafad8c62018-01-05 22:30:49 -08004273 StatsLog.write(StatsLog.WAKEUP_ALARM_OCCURRED, wc.getUids(), wc.getTags(), tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004274 }
4275 }
4276 } else {
Tej Singh6f724c42018-01-03 20:02:03 -08004277 if (isOnBattery()) {
4278 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid, packageName);
4279 pkg.noteWakeupAlarmLocked(tag);
4280 }
Yangster-mac2f5daec2018-01-16 10:23:15 -08004281 StatsLog.write_non_chained(StatsLog.WAKEUP_ALARM_OCCURRED, uid, null, tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004282 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07004283 }
4284
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004285 private void requestWakelockCpuUpdate() {
Sudheer Shankac57729a2018-02-09 15:44:42 -08004286 mExternalSync.scheduleCpuSyncDueToWakelockChange(DELAY_UPDATE_WAKELOCKS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004287 }
4288
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004289 private void requestImmediateCpuUpdate() {
Sudheer Shankac57729a2018-02-09 15:44:42 -08004290 mExternalSync.scheduleCpuSyncDueToWakelockChange(0 /* delayMillis */);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004291 }
4292
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004293 public void setRecordAllHistoryLocked(boolean enabled) {
4294 mRecordAllHistory = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004295 if (!enabled) {
4296 // Clear out any existing state.
4297 mActiveEvents.removeEvents(HistoryItem.EVENT_WAKE_LOCK);
Dianne Hackborn1e383822015-04-10 14:02:33 -07004298 mActiveEvents.removeEvents(HistoryItem.EVENT_ALARM);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004299 // Record the currently running processes as stopping, now that we are no
4300 // longer tracking them.
4301 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
4302 HistoryItem.EVENT_PROC);
4303 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08004304 long mSecRealtime = mClocks.elapsedRealtime();
4305 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004306 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
4307 SparseIntArray uids = ent.getValue();
4308 for (int j=0; j<uids.size(); j++) {
4309 addHistoryEventLocked(mSecRealtime, mSecUptime,
4310 HistoryItem.EVENT_PROC_FINISH, ent.getKey(), uids.keyAt(j));
4311 }
4312 }
4313 }
4314 } else {
4315 // Record the currently running processes as starting, now that we are tracking them.
4316 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
4317 HistoryItem.EVENT_PROC);
4318 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08004319 long mSecRealtime = mClocks.elapsedRealtime();
4320 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004321 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
4322 SparseIntArray uids = ent.getValue();
4323 for (int j=0; j<uids.size(); j++) {
4324 addHistoryEventLocked(mSecRealtime, mSecUptime,
4325 HistoryItem.EVENT_PROC_START, ent.getKey(), uids.keyAt(j));
4326 }
4327 }
4328 }
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004329 }
4330 }
4331
Dianne Hackborn9a755432014-05-15 17:05:22 -07004332 public void setNoAutoReset(boolean enabled) {
4333 mNoAutoReset = enabled;
4334 }
4335
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004336 public void setPretendScreenOff(boolean pretendScreenOff) {
Mike Mac2f518a2017-09-19 16:06:03 -07004337 if (mPretendScreenOff != pretendScreenOff) {
4338 mPretendScreenOff = pretendScreenOff;
4339 noteScreenStateLocked(pretendScreenOff ? Display.STATE_OFF : Display.STATE_ON);
4340 }
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004341 }
4342
Dianne Hackborn9a755432014-05-15 17:05:22 -07004343 private String mInitialAcquireWakeName;
4344 private int mInitialAcquireWakeUid = -1;
4345
Narayan Kamath81822022017-12-08 11:56:01 +00004346 public void noteStartWakeLocked(int uid, int pid, WorkChain wc, String name, String historyName,
4347 int type, boolean unimportantForLogging, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004348 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004349 if (type == WAKE_TYPE_PARTIAL) {
4350 // Only care about partial wake locks, since full wake locks
4351 // will be canceled when the user puts the screen to sleep.
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004352 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07004353 if (historyName == null) {
4354 historyName = name;
4355 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004356 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07004357 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_START, historyName,
4358 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07004359 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07004360 HistoryItem.EVENT_WAKE_LOCK_START, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07004361 }
4362 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004363 if (mWakeLockNesting == 0) {
4364 mHistoryCur.states |= HistoryItem.STATE_WAKE_LOCK_FLAG;
4365 if (DEBUG_HISTORY) Slog.v(TAG, "Start wake lock to: "
4366 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08004367 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004368 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07004369 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004370 mWakeLockImportant = !unimportantForLogging;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004371 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07004372 } else if (!mWakeLockImportant && !unimportantForLogging
4373 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004374 if (mHistoryLastWritten.wakelockTag != null) {
4375 // We'll try to update the last tag.
4376 mHistoryLastWritten.wakelockTag = null;
4377 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004378 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07004379 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004380 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004381 }
4382 mWakeLockImportant = true;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004383 }
4384 mWakeLockNesting++;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004385 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004386 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07004387 if (mOnBatteryScreenOffTimeBase.isRunning()) {
4388 // We only update the cpu time when a wake lock is acquired if the screen is off.
4389 // If the screen is on, we don't distribute the power amongst partial wakelocks.
4390 if (DEBUG_ENERGY_CPU) {
4391 Slog.d(TAG, "Updating cpu time because of +wake_lock");
4392 }
4393 requestWakelockCpuUpdate();
4394 }
Narayan Kamath81822022017-12-08 11:56:01 +00004395
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004396 getUidStatsLocked(uid).noteStartWakeLocked(pid, name, type, elapsedRealtime);
Narayan Kamath81822022017-12-08 11:56:01 +00004397
Yangster-mac20877162017-12-22 17:19:39 -08004398 if (wc != null) {
Bookatz1a1b0462018-01-12 11:47:03 -08004399 StatsLog.write(StatsLog.WAKELOCK_STATE_CHANGED, wc.getUids(), wc.getTags(),
Bookatz90867622018-01-31 15:05:57 -08004400 getPowerManagerWakeLockLevel(type), name,
4401 StatsLog.WAKELOCK_STATE_CHANGED__STATE__ACQUIRE);
Yangster-macafad8c62018-01-05 22:30:49 -08004402 } else {
Bookatz1a1b0462018-01-12 11:47:03 -08004403 StatsLog.write_non_chained(StatsLog.WAKELOCK_STATE_CHANGED, uid, null,
Bookatz90867622018-01-31 15:05:57 -08004404 getPowerManagerWakeLockLevel(type), name,
4405 StatsLog.WAKELOCK_STATE_CHANGED__STATE__ACQUIRE);
Narayan Kamath81822022017-12-08 11:56:01 +00004406 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004407 }
4408 }
4409
Narayan Kamath81822022017-12-08 11:56:01 +00004410 public void noteStopWakeLocked(int uid, int pid, WorkChain wc, String name, String historyName,
4411 int type, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004412 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004413 if (type == WAKE_TYPE_PARTIAL) {
4414 mWakeLockNesting--;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004415 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07004416 if (historyName == null) {
4417 historyName = name;
4418 }
4419 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName,
4420 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07004421 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07004422 HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07004423 }
4424 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004425 if (mWakeLockNesting == 0) {
4426 mHistoryCur.states &= ~HistoryItem.STATE_WAKE_LOCK_FLAG;
4427 if (DEBUG_HISTORY) Slog.v(TAG, "Stop wake lock to: "
4428 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn37de0982014-05-09 09:32:18 -07004429 mInitialAcquireWakeName = null;
4430 mInitialAcquireWakeUid = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004431 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004432 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004433 }
4434 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07004435 if (mOnBatteryScreenOffTimeBase.isRunning()) {
4436 if (DEBUG_ENERGY_CPU) {
4437 Slog.d(TAG, "Updating cpu time because of -wake_lock");
4438 }
4439 requestWakelockCpuUpdate();
4440 }
Narayan Kamath81822022017-12-08 11:56:01 +00004441
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004442 getUidStatsLocked(uid).noteStopWakeLocked(pid, name, type, elapsedRealtime);
Yangster-mac20877162017-12-22 17:19:39 -08004443 if (wc != null) {
Bookatz1a1b0462018-01-12 11:47:03 -08004444 StatsLog.write(StatsLog.WAKELOCK_STATE_CHANGED, wc.getUids(), wc.getTags(),
Bookatz90867622018-01-31 15:05:57 -08004445 getPowerManagerWakeLockLevel(type), name,
4446 StatsLog.WAKELOCK_STATE_CHANGED__STATE__RELEASE);
Yangster-macafad8c62018-01-05 22:30:49 -08004447 } else {
Bookatz1a1b0462018-01-12 11:47:03 -08004448 StatsLog.write_non_chained(StatsLog.WAKELOCK_STATE_CHANGED, uid, null,
Bookatz90867622018-01-31 15:05:57 -08004449 getPowerManagerWakeLockLevel(type), name,
4450 StatsLog.WAKELOCK_STATE_CHANGED__STATE__RELEASE);
Narayan Kamath81822022017-12-08 11:56:01 +00004451 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004452 }
4453 }
4454
Bookatz1a1b0462018-01-12 11:47:03 -08004455 /**
4456 * Converts BatteryStats wakelock types back into PowerManager wakelock levels.
4457 * This is the inverse map of Notifier.getBatteryStatsWakeLockMonitorType().
4458 * These are estimations, since batterystats loses some of the original data.
4459 * TODO: Delete this. Instead, StatsLog.write should be called from PowerManager's Notifier.
4460 */
4461 private int getPowerManagerWakeLockLevel(int battertStatsWakelockType) {
4462 switch (battertStatsWakelockType) {
4463 // PowerManager.PARTIAL_WAKE_LOCK or PROXIMITY_SCREEN_OFF_WAKE_LOCK
4464 case BatteryStats.WAKE_TYPE_PARTIAL:
4465 return PowerManager.PARTIAL_WAKE_LOCK;
4466
4467 // PowerManager.SCREEN_DIM_WAKE_LOCK or SCREEN_BRIGHT_WAKE_LOCK
4468 case BatteryStats.WAKE_TYPE_FULL:
4469 return PowerManager.FULL_WAKE_LOCK;
4470
4471 case BatteryStats.WAKE_TYPE_DRAW:
4472 return PowerManager.DRAW_WAKE_LOCK;
4473
4474 // It appears that nothing can ever make a Window and PowerManager lacks an equivalent.
4475 case BatteryStats.WAKE_TYPE_WINDOW:
4476 Slog.e(TAG, "Illegal window wakelock type observed in batterystats.");
4477 return -1;
4478
4479 default:
4480 Slog.e(TAG, "Illegal wakelock type in batterystats: " + battertStatsWakelockType);
4481 return -1;
4482 }
4483 }
4484
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004485 public void noteStartWakeFromSourceLocked(WorkSource ws, int pid, String name,
4486 String historyName, int type, boolean unimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08004487 final long elapsedRealtime = mClocks.elapsedRealtime();
4488 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004489 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004490 for (int i=0; i<N; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004491 noteStartWakeLocked(ws.get(i), pid, null, name, historyName, type,
4492 unimportantForLogging, elapsedRealtime, uptime);
4493 }
4494
4495 List<WorkChain> wcs = ws.getWorkChains();
4496 if (wcs != null) {
4497 for (int i = 0; i < wcs.size(); ++i) {
4498 final WorkChain wc = wcs.get(i);
4499 noteStartWakeLocked(wc.getAttributionUid(), pid, wc, name, historyName, type,
4500 unimportantForLogging, elapsedRealtime, uptime);
4501 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004502 }
4503 }
4504
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004505 public void noteChangeWakelockFromSourceLocked(WorkSource ws, int pid, String name,
4506 String historyName, int type, WorkSource newWs, int newPid, String newName,
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004507 String newHistoryName, int newType, boolean newUnimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08004508 final long elapsedRealtime = mClocks.elapsedRealtime();
4509 final long uptime = mClocks.uptimeMillis();
Narayan Kamath81822022017-12-08 11:56:01 +00004510
4511 List<WorkChain>[] wcs = WorkSource.diffChains(ws, newWs);
4512
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004513 // For correct semantics, we start the need worksources first, so that we won't
4514 // make inappropriate history items as if all wake locks went away and new ones
4515 // appeared. This is okay because tracking of wake locks allows nesting.
Narayan Kamath81822022017-12-08 11:56:01 +00004516 //
4517 // First the starts :
Dianne Hackborn40c87252014-03-19 16:55:40 -07004518 final int NN = newWs.size();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004519 for (int i=0; i<NN; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004520 noteStartWakeLocked(newWs.get(i), newPid, null, newName, newHistoryName, newType,
Dianne Hackborn40c87252014-03-19 16:55:40 -07004521 newUnimportantForLogging, elapsedRealtime, uptime);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004522 }
Narayan Kamath81822022017-12-08 11:56:01 +00004523 if (wcs != null) {
4524 List<WorkChain> newChains = wcs[0];
4525 if (newChains != null) {
4526 for (int i = 0; i < newChains.size(); ++i) {
4527 final WorkChain newChain = newChains.get(i);
4528 noteStartWakeLocked(newChain.getAttributionUid(), newPid, newChain, newName,
4529 newHistoryName, newType, newUnimportantForLogging, elapsedRealtime,
4530 uptime);
4531 }
4532 }
4533 }
4534
4535 // Then the stops :
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004536 final int NO = ws.size();
4537 for (int i=0; i<NO; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004538 noteStopWakeLocked(ws.get(i), pid, null, name, historyName, type, elapsedRealtime,
4539 uptime);
4540 }
4541 if (wcs != null) {
4542 List<WorkChain> goneChains = wcs[1];
4543 if (goneChains != null) {
4544 for (int i = 0; i < goneChains.size(); ++i) {
4545 final WorkChain goneChain = goneChains.get(i);
4546 noteStopWakeLocked(goneChain.getAttributionUid(), pid, goneChain, name,
4547 historyName, type, elapsedRealtime, uptime);
4548 }
4549 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004550 }
4551 }
4552
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004553 public void noteStopWakeFromSourceLocked(WorkSource ws, int pid, String name,
4554 String historyName, int type) {
Joe Onoratoabded112016-02-08 16:49:39 -08004555 final long elapsedRealtime = mClocks.elapsedRealtime();
4556 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004557 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004558 for (int i=0; i<N; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004559 noteStopWakeLocked(ws.get(i), pid, null, name, historyName, type, elapsedRealtime,
4560 uptime);
4561 }
4562
4563 List<WorkChain> wcs = ws.getWorkChains();
4564 if (wcs != null) {
4565 for (int i = 0; i < wcs.size(); ++i) {
4566 final WorkChain wc = wcs.get(i);
4567 noteStopWakeLocked(wc.getAttributionUid(), pid, wc, name, historyName, type,
4568 elapsedRealtime, uptime);
4569 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004570 }
4571 }
4572
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004573 public void noteLongPartialWakelockStart(String name, String historyName, int uid) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08004574 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004575 uid, null, name, historyName,
4576 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
Yangster-macafad8c62018-01-05 22:30:49 -08004577
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004578 uid = mapUid(uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004579 noteLongPartialWakeLockStartInternal(name, historyName, uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004580 }
4581
4582 public void noteLongPartialWakelockStartFromSource(String name, String historyName,
4583 WorkSource workSource) {
4584 final int N = workSource.size();
4585 for (int i = 0; i < N; ++i) {
4586 final int uid = mapUid(workSource.get(i));
4587 noteLongPartialWakeLockStartInternal(name, historyName, uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08004588 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004589 workSource.get(i), workSource.getName(i), name, historyName,
4590 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath96a92562018-01-02 18:57:17 +00004591 }
4592
4593 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
4594 if (workChains != null) {
4595 for (int i = 0; i < workChains.size(); ++i) {
4596 final WorkChain workChain = workChains.get(i);
4597 final int uid = workChain.getAttributionUid();
4598 noteLongPartialWakeLockStartInternal(name, historyName, uid);
4599
Yangster-macafad8c62018-01-05 22:30:49 -08004600 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004601 workChain.getUids(), workChain.getTags(), name, historyName,
4602 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath96a92562018-01-02 18:57:17 +00004603 }
4604 }
4605 }
4606
4607 private void noteLongPartialWakeLockStartInternal(String name, String historyName, int uid) {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004608 final long elapsedRealtime = mClocks.elapsedRealtime();
4609 final long uptime = mClocks.uptimeMillis();
4610 if (historyName == null) {
4611 historyName = name;
4612 }
4613 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_START, historyName, uid,
4614 0)) {
4615 return;
4616 }
4617 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_START,
4618 historyName, uid);
4619 }
4620
4621 public void noteLongPartialWakelockFinish(String name, String historyName, int uid) {
Bookatz90867622018-01-31 15:05:57 -08004622 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED, uid, null,
4623 name, historyName, StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
Yangster-macafad8c62018-01-05 22:30:49 -08004624
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004625 uid = mapUid(uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004626 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004627 }
4628
4629 public void noteLongPartialWakelockFinishFromSource(String name, String historyName,
4630 WorkSource workSource) {
4631 final int N = workSource.size();
4632 for (int i = 0; i < N; ++i) {
4633 final int uid = mapUid(workSource.get(i));
4634 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08004635 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004636 workSource.get(i), workSource.getName(i), name, historyName,
4637 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath96a92562018-01-02 18:57:17 +00004638 }
4639
4640 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
4641 if (workChains != null) {
4642 for (int i = 0; i < workChains.size(); ++i) {
4643 final WorkChain workChain = workChains.get(i);
4644 final int uid = workChain.getAttributionUid();
Narayan Kamath96a92562018-01-02 18:57:17 +00004645 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Yangster-macafad8c62018-01-05 22:30:49 -08004646 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004647 workChain.getUids(), workChain.getTags(), name, historyName,
4648 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath96a92562018-01-02 18:57:17 +00004649 }
4650 }
4651 }
4652
4653 private void noteLongPartialWakeLockFinishInternal(String name, String historyName, int uid) {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004654 final long elapsedRealtime = mClocks.elapsedRealtime();
4655 final long uptime = mClocks.uptimeMillis();
4656 if (historyName == null) {
4657 historyName = name;
4658 }
4659 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH, historyName, uid,
4660 0)) {
4661 return;
4662 }
4663 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH,
4664 historyName, uid);
4665 }
4666
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004667 void aggregateLastWakeupUptimeLocked(long uptimeMs) {
4668 if (mLastWakeupReason != null) {
4669 long deltaUptime = uptimeMs - mLastWakeupUptimeMs;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004670 SamplingTimer timer = getWakeupReasonTimerLocked(mLastWakeupReason);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07004671 timer.add(deltaUptime * 1000, 1); // time in in microseconds
Bookatz90867622018-01-31 15:05:57 -08004672 StatsLog.write(StatsLog.KERNEL_WAKEUP_REPORTED, mLastWakeupReason,
4673 /* duration_usec */ deltaUptime * 1000);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004674 mLastWakeupReason = null;
4675 }
4676 }
4677
4678 public void noteWakeupReasonLocked(String reason) {
Joe Onoratoabded112016-02-08 16:49:39 -08004679 final long elapsedRealtime = mClocks.elapsedRealtime();
4680 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004681 if (DEBUG_HISTORY) Slog.v(TAG, "Wakeup reason \"" + reason +"\": "
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004682 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004683 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004684 mHistoryCur.wakeReasonTag = mHistoryCur.localWakeReasonTag;
4685 mHistoryCur.wakeReasonTag.string = reason;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004686 mHistoryCur.wakeReasonTag.uid = 0;
4687 mLastWakeupReason = reason;
4688 mLastWakeupUptimeMs = uptime;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004689 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004690 }
4691
Adam Lesinski72478f02015-06-17 15:39:43 -07004692 public boolean startAddingCpuLocked() {
Sudheer Shankac57729a2018-02-09 15:44:42 -08004693 mExternalSync.cancelCpuSyncDueToWakelockChange();
Adam Lesinski72478f02015-06-17 15:39:43 -07004694 return mOnBatteryInternal;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004695 }
4696
Adam Lesinski72478f02015-06-17 15:39:43 -07004697 public void finishAddingCpuLocked(int totalUTime, int totalSTime, int statUserTime,
4698 int statSystemTime, int statIOWaitTime, int statIrqTime,
4699 int statSoftIrqTime, int statIdleTime) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004700 if (DEBUG) Slog.d(TAG, "Adding cpu: tuser=" + totalUTime + " tsys=" + totalSTime
4701 + " user=" + statUserTime + " sys=" + statSystemTime
4702 + " io=" + statIOWaitTime + " irq=" + statIrqTime
4703 + " sirq=" + statSoftIrqTime + " idle=" + statIdleTime);
4704 mCurStepCpuUserTime += totalUTime;
4705 mCurStepCpuSystemTime += totalSTime;
4706 mCurStepStatUserTime += statUserTime;
4707 mCurStepStatSystemTime += statSystemTime;
4708 mCurStepStatIOWaitTime += statIOWaitTime;
4709 mCurStepStatIrqTime += statIrqTime;
4710 mCurStepStatSoftIrqTime += statSoftIrqTime;
4711 mCurStepStatIdleTime += statIdleTime;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004712 }
4713
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004714 public void noteProcessDiedLocked(int uid, int pid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004715 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004716 Uid u = mUidStats.get(uid);
4717 if (u != null) {
4718 u.mPids.remove(pid);
4719 }
4720 }
4721
4722 public long getProcessWakeTime(int uid, int pid, long realtime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004723 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004724 Uid u = mUidStats.get(uid);
4725 if (u != null) {
4726 Uid.Pid p = u.mPids.get(pid);
4727 if (p != null) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004728 return p.mWakeSumMs + (p.mWakeNesting > 0 ? (realtime - p.mWakeStartMs) : 0);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004729 }
4730 }
4731 return 0;
4732 }
4733
Dianne Hackborn287952c2010-09-22 22:34:31 -07004734 public void reportExcessiveCpuLocked(int uid, String proc, long overTime, long usedTime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004735 uid = mapUid(uid);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004736 Uid u = mUidStats.get(uid);
4737 if (u != null) {
4738 u.reportExcessiveCpuLocked(proc, overTime, usedTime);
4739 }
4740 }
4741
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004742 int mSensorNesting;
4743
4744 public void noteStartSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004745 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004746 final long elapsedRealtime = mClocks.elapsedRealtime();
4747 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004748 if (mSensorNesting == 0) {
4749 mHistoryCur.states |= HistoryItem.STATE_SENSOR_ON_FLAG;
4750 if (DEBUG_HISTORY) Slog.v(TAG, "Start sensor to: "
4751 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004752 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004753 }
4754 mSensorNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004755 getUidStatsLocked(uid).noteStartSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004756 }
4757
4758 public void noteStopSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004759 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004760 final long elapsedRealtime = mClocks.elapsedRealtime();
4761 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004762 mSensorNesting--;
4763 if (mSensorNesting == 0) {
4764 mHistoryCur.states &= ~HistoryItem.STATE_SENSOR_ON_FLAG;
4765 if (DEBUG_HISTORY) Slog.v(TAG, "Stop sensor to: "
4766 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004767 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004768 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004769 getUidStatsLocked(uid).noteStopSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004770 }
4771
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004772 int mGpsNesting;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004773
Narayan Kamath32684dd2018-01-08 17:32:51 +00004774 public void noteGpsChangedLocked(WorkSource oldWs, WorkSource newWs) {
4775 for (int i = 0; i < newWs.size(); ++i) {
4776 noteStartGpsLocked(newWs.get(i), null);
4777 }
4778
4779 for (int i = 0; i < oldWs.size(); ++i) {
4780 noteStopGpsLocked((oldWs.get(i)), null);
4781 }
4782
4783 List<WorkChain>[] wcs = WorkSource.diffChains(oldWs, newWs);
4784 if (wcs != null) {
4785 if (wcs[0] != null) {
4786 final List<WorkChain> newChains = wcs[0];
4787 for (int i = 0; i < newChains.size(); ++i) {
4788 noteStartGpsLocked(-1, newChains.get(i));
4789 }
4790 }
4791
4792 if (wcs[1] != null) {
4793 final List<WorkChain> goneChains = wcs[1];
4794 for (int i = 0; i < goneChains.size(); ++i) {
4795 noteStopGpsLocked(-1, goneChains.get(i));
4796 }
4797 }
4798 }
4799 }
4800
4801 private void noteStartGpsLocked(int uid, WorkChain workChain) {
4802 uid = getAttributionUid(uid, workChain);
Joe Onoratoabded112016-02-08 16:49:39 -08004803 final long elapsedRealtime = mClocks.elapsedRealtime();
4804 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004805 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004806 mHistoryCur.states |= HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004807 if (DEBUG_HISTORY) Slog.v(TAG, "Start GPS to: "
4808 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004809 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004810 }
4811 mGpsNesting++;
Narayan Kamath32684dd2018-01-08 17:32:51 +00004812
4813 if (workChain == null) {
Bookatz90867622018-01-31 15:05:57 -08004814 StatsLog.write_non_chained(StatsLog.GPS_SCAN_STATE_CHANGED, uid, null,
4815 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004816 } else {
4817 StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004818 workChain.getUids(), workChain.getTags(),
4819 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004820 }
4821
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004822 getUidStatsLocked(uid).noteStartGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004823 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004824
Narayan Kamath32684dd2018-01-08 17:32:51 +00004825 private void noteStopGpsLocked(int uid, WorkChain workChain) {
4826 uid = getAttributionUid(uid, workChain);
Joe Onoratoabded112016-02-08 16:49:39 -08004827 final long elapsedRealtime = mClocks.elapsedRealtime();
4828 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004829 mGpsNesting--;
4830 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004831 mHistoryCur.states &= ~HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004832 if (DEBUG_HISTORY) Slog.v(TAG, "Stop GPS to: "
4833 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004834 addHistoryRecordLocked(elapsedRealtime, uptime);
Siddharth Ray78ccaf52017-12-23 16:16:21 -08004835 stopAllGpsSignalQualityTimersLocked(-1);
4836 mGpsSignalQualityBin = -1;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004837 }
Narayan Kamath32684dd2018-01-08 17:32:51 +00004838
4839 if (workChain == null) {
Bookatz90867622018-01-31 15:05:57 -08004840 StatsLog.write_non_chained(StatsLog.GPS_SCAN_STATE_CHANGED, uid, null,
4841 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004842 } else {
4843 StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED, workChain.getUids(),
Bookatz90867622018-01-31 15:05:57 -08004844 workChain.getTags(), StatsLog.GPS_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004845 }
4846
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004847 getUidStatsLocked(uid).noteStopGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004848 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07004849
Siddharth Ray78ccaf52017-12-23 16:16:21 -08004850 public void noteGpsSignalQualityLocked(int signalLevel) {
4851 if (mGpsNesting == 0) {
4852 return;
4853 }
4854 if (signalLevel < 0 || signalLevel >= GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS) {
4855 stopAllGpsSignalQualityTimersLocked(-1);
4856 return;
4857 }
4858 final long elapsedRealtime = mClocks.elapsedRealtime();
4859 final long uptime = mClocks.uptimeMillis();
4860 if (mGpsSignalQualityBin != signalLevel) {
4861 if (mGpsSignalQualityBin >= 0) {
4862 mGpsSignalQualityTimer[mGpsSignalQualityBin].stopRunningLocked(elapsedRealtime);
4863 }
4864 if(!mGpsSignalQualityTimer[signalLevel].isRunningLocked()) {
4865 mGpsSignalQualityTimer[signalLevel].startRunningLocked(elapsedRealtime);
4866 }
4867 mHistoryCur.states2 = (mHistoryCur.states2&~HistoryItem.STATE2_GPS_SIGNAL_QUALITY_MASK)
4868 | (signalLevel << HistoryItem.STATE2_GPS_SIGNAL_QUALITY_SHIFT);
4869 addHistoryRecordLocked(elapsedRealtime, uptime);
4870 mGpsSignalQualityBin = signalLevel;
4871 }
4872 return;
4873 }
4874
Andreas Gampe3f24e692018-02-05 13:24:28 -08004875 @GuardedBy("this")
Jeff Browne95c3cd2014-05-02 16:59:26 -07004876 public void noteScreenStateLocked(int state) {
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004877 state = mPretendScreenOff ? Display.STATE_OFF : state;
Santos Cordone94f0502017-02-24 12:31:20 -08004878
4879 // Battery stats relies on there being 4 states. To accommodate this, new states beyond the
4880 // original 4 are mapped to one of the originals.
4881 if (state > MAX_TRACKED_SCREEN_STATE) {
4882 switch (state) {
4883 case Display.STATE_VR:
4884 state = Display.STATE_ON;
4885 break;
4886 default:
4887 Slog.wtf(TAG, "Unknown screen state (not mapped): " + state);
4888 break;
4889 }
4890 }
4891
Jeff Browne95c3cd2014-05-02 16:59:26 -07004892 if (mScreenState != state) {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08004893 recordDailyStatsIfNeededLocked(true);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004894 final int oldState = mScreenState;
4895 mScreenState = state;
4896 if (DEBUG) Slog.v(TAG, "Screen state: oldState=" + Display.stateToString(oldState)
4897 + ", newState=" + Display.stateToString(state));
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004898
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004899 if (state != Display.STATE_UNKNOWN) {
4900 int stepState = state-1;
Santos Cordone94f0502017-02-24 12:31:20 -08004901 if ((stepState & STEP_LEVEL_MODE_SCREEN_STATE) == stepState) {
4902 mModStepMode |= (mCurStepMode & STEP_LEVEL_MODE_SCREEN_STATE) ^ stepState;
4903 mCurStepMode = (mCurStepMode & ~STEP_LEVEL_MODE_SCREEN_STATE) | stepState;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004904 } else {
4905 Slog.wtf(TAG, "Unexpected screen state: " + state);
4906 }
4907 }
4908
Mike Mac2f518a2017-09-19 16:06:03 -07004909 final long elapsedRealtime = mClocks.elapsedRealtime();
4910 final long uptime = mClocks.uptimeMillis();
4911
4912 boolean updateHistory = false;
4913 if (isScreenDoze(state)) {
4914 mHistoryCur.states |= HistoryItem.STATE_SCREEN_DOZE_FLAG;
4915 mScreenDozeTimer.startRunningLocked(elapsedRealtime);
4916 updateHistory = true;
4917 } else if (isScreenDoze(oldState)) {
4918 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_DOZE_FLAG;
4919 mScreenDozeTimer.stopRunningLocked(elapsedRealtime);
4920 updateHistory = true;
4921 }
4922 if (isScreenOn(state)) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07004923 mHistoryCur.states |= HistoryItem.STATE_SCREEN_ON_FLAG;
4924 if (DEBUG_HISTORY) Slog.v(TAG, "Screen on to: "
4925 + Integer.toHexString(mHistoryCur.states));
Jeff Browne95c3cd2014-05-02 16:59:26 -07004926 mScreenOnTimer.startRunningLocked(elapsedRealtime);
4927 if (mScreenBrightnessBin >= 0) {
4928 mScreenBrightnessTimer[mScreenBrightnessBin].startRunningLocked(elapsedRealtime);
4929 }
Mike Mac2f518a2017-09-19 16:06:03 -07004930 updateHistory = true;
4931 } else if (isScreenOn(oldState)) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07004932 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_ON_FLAG;
4933 if (DEBUG_HISTORY) Slog.v(TAG, "Screen off to: "
4934 + Integer.toHexString(mHistoryCur.states));
Jeff Browne95c3cd2014-05-02 16:59:26 -07004935 mScreenOnTimer.stopRunningLocked(elapsedRealtime);
4936 if (mScreenBrightnessBin >= 0) {
4937 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
4938 }
Mike Mac2f518a2017-09-19 16:06:03 -07004939 updateHistory = true;
4940 }
4941 if (updateHistory) {
4942 if (DEBUG_HISTORY) Slog.v(TAG, "Screen state to: "
4943 + Display.stateToString(state));
4944 addHistoryRecordLocked(elapsedRealtime, uptime);
4945 }
Sudheer Shankac57729a2018-02-09 15:44:42 -08004946 mExternalSync.scheduleCpuSyncDueToScreenStateChange(
4947 mOnBatteryTimeBase.isRunning(), mOnBatteryScreenOffTimeBase.isRunning());
Mike Mac2f518a2017-09-19 16:06:03 -07004948 if (isScreenOn(state)) {
4949 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), state,
4950 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
4951 // Fake a wake lock, so we consider the device waked as long as the screen is on.
Narayan Kamath81822022017-12-08 11:56:01 +00004952 noteStartWakeLocked(-1, -1, null, "screen", null, WAKE_TYPE_PARTIAL, false,
Mike Mac2f518a2017-09-19 16:06:03 -07004953 elapsedRealtime, uptime);
4954 } else if (isScreenOn(oldState)) {
Narayan Kamath81822022017-12-08 11:56:01 +00004955 noteStopWakeLocked(-1, -1, null, "screen", "screen", WAKE_TYPE_PARTIAL,
Jeff Browne95c3cd2014-05-02 16:59:26 -07004956 elapsedRealtime, uptime);
Mike Mac2f518a2017-09-19 16:06:03 -07004957 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), state,
Joe Onoratoabded112016-02-08 16:49:39 -08004958 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
Mike Mac2f518a2017-09-19 16:06:03 -07004959 }
4960 // Update discharge amounts.
4961 if (mOnBatteryInternal) {
4962 updateDischargeScreenLevelsLocked(oldState, state);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08004963 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07004964 }
4965 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004966
Dianne Hackborn617f8772009-03-31 15:04:46 -07004967 public void noteScreenBrightnessLocked(int brightness) {
4968 // Bin the brightness.
4969 int bin = brightness / (256/NUM_SCREEN_BRIGHTNESS_BINS);
4970 if (bin < 0) bin = 0;
4971 else if (bin >= NUM_SCREEN_BRIGHTNESS_BINS) bin = NUM_SCREEN_BRIGHTNESS_BINS-1;
4972 if (mScreenBrightnessBin != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08004973 final long elapsedRealtime = mClocks.elapsedRealtime();
4974 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004975 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_BRIGHTNESS_MASK)
4976 | (bin << HistoryItem.STATE_BRIGHTNESS_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004977 if (DEBUG_HISTORY) Slog.v(TAG, "Screen brightness " + bin + " to: "
4978 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004979 addHistoryRecordLocked(elapsedRealtime, uptime);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004980 if (mScreenState == Display.STATE_ON) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07004981 if (mScreenBrightnessBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004982 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07004983 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004984 mScreenBrightnessTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07004985 }
4986 mScreenBrightnessBin = bin;
4987 }
4988 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004989
Dianne Hackborn617f8772009-03-31 15:04:46 -07004990 public void noteUserActivityLocked(int uid, int event) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08004991 if (mOnBatteryInternal) {
4992 uid = mapUid(uid);
4993 getUidStatsLocked(uid).noteUserActivityLocked(event);
4994 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004995 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004996
Dianne Hackborn280a64e2015-07-13 14:48:08 -07004997 public void noteWakeUpLocked(String reason, int reasonUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004998 final long elapsedRealtime = mClocks.elapsedRealtime();
4999 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn280a64e2015-07-13 14:48:08 -07005000 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SCREEN_WAKE_UP,
5001 reason, reasonUid);
5002 }
5003
Jeff Browne95c3cd2014-05-02 16:59:26 -07005004 public void noteInteractiveLocked(boolean interactive) {
5005 if (mInteractive != interactive) {
Joe Onoratoabded112016-02-08 16:49:39 -08005006 final long elapsedRealtime = mClocks.elapsedRealtime();
Jeff Browne95c3cd2014-05-02 16:59:26 -07005007 mInteractive = interactive;
5008 if (DEBUG) Slog.v(TAG, "Interactive: " + interactive);
5009 if (interactive) {
5010 mInteractiveTimer.startRunningLocked(elapsedRealtime);
5011 } else {
5012 mInteractiveTimer.stopRunningLocked(elapsedRealtime);
5013 }
5014 }
5015 }
5016
Dianne Hackborn1e01d162014-12-04 17:46:42 -08005017 public void noteConnectivityChangedLocked(int type, String extra) {
Joe Onoratoabded112016-02-08 16:49:39 -08005018 final long elapsedRealtime = mClocks.elapsedRealtime();
5019 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08005020 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_CONNECTIVITY_CHANGED,
5021 extra, type);
5022 mNumConnectivityChange++;
5023 }
5024
Adam Lesinski5f056f62016-07-14 16:56:08 -07005025 private void noteMobileRadioApWakeupLocked(final long elapsedRealtimeMillis,
5026 final long uptimeMillis, int uid) {
5027 uid = mapUid(uid);
5028 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
5029 uid);
5030 getUidStatsLocked(uid).noteMobileRadioApWakeupLocked();
5031 }
5032
Adam Lesinski14ae39a2017-05-26 11:50:40 -07005033 /**
5034 * Updates the radio power state and returns true if an external stats collection should occur.
5035 */
5036 public boolean noteMobileRadioPowerStateLocked(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005037 final long elapsedRealtime = mClocks.elapsedRealtime();
5038 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005039 if (mMobileRadioPowerState != powerState) {
5040 long realElapsedRealtimeMs;
5041 final boolean active =
5042 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
5043 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
5044 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07005045 if (uid > 0) {
5046 noteMobileRadioApWakeupLocked(elapsedRealtime, uptime, uid);
5047 }
5048
Adam Lesinski9acfd812016-04-19 18:29:50 -07005049 mMobileRadioActiveStartTime = realElapsedRealtimeMs = timestampNs / (1000 * 1000);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005050 mHistoryCur.states |= HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
5051 } else {
5052 realElapsedRealtimeMs = timestampNs / (1000*1000);
Dianne Hackbornf7097a52014-05-13 09:56:14 -07005053 long lastUpdateTimeMs = mMobileRadioActiveStartTime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005054 if (realElapsedRealtimeMs < lastUpdateTimeMs) {
5055 Slog.wtf(TAG, "Data connection inactive timestamp " + realElapsedRealtimeMs
5056 + " is before start time " + lastUpdateTimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005057 realElapsedRealtimeMs = elapsedRealtime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005058 } else if (realElapsedRealtimeMs < elapsedRealtime) {
5059 mMobileRadioActiveAdjustedTime.addCountLocked(elapsedRealtime
5060 - realElapsedRealtimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005061 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005062 mHistoryCur.states &= ~HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
5063 }
5064 if (DEBUG_HISTORY) Slog.v(TAG, "Mobile network active " + active + " to: "
5065 + Integer.toHexString(mHistoryCur.states));
5066 addHistoryRecordLocked(elapsedRealtime, uptime);
5067 mMobileRadioPowerState = powerState;
Bookatzddccf0a2017-11-28 16:48:14 -08005068 StatsLog.write(StatsLog.MOBILE_RADIO_POWER_STATE_CHANGED, uid, powerState);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005069 if (active) {
5070 mMobileRadioActiveTimer.startRunningLocked(elapsedRealtime);
5071 mMobileRadioActivePerAppTimer.startRunningLocked(elapsedRealtime);
5072 } else {
5073 mMobileRadioActiveTimer.stopRunningLocked(realElapsedRealtimeMs);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005074 mMobileRadioActivePerAppTimer.stopRunningLocked(realElapsedRealtimeMs);
Adam Lesinski14ae39a2017-05-26 11:50:40 -07005075 // Tell the caller to collect radio network/power stats.
5076 return true;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08005077 }
Dianne Hackborne13c4c02014-02-11 17:18:35 -08005078 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -07005079 return false;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08005080 }
5081
Adam Lesinski14ae39a2017-05-26 11:50:40 -07005082 public void notePowerSaveModeLocked(boolean enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005083 if (mPowerSaveModeEnabled != enabled) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07005084 int stepState = enabled ? STEP_LEVEL_MODE_POWER_SAVE : 0;
5085 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_POWER_SAVE) ^ stepState;
5086 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_POWER_SAVE) | stepState;
Joe Onoratoabded112016-02-08 16:49:39 -08005087 final long elapsedRealtime = mClocks.elapsedRealtime();
5088 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005089 mPowerSaveModeEnabled = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005090 if (enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005091 mHistoryCur.states2 |= HistoryItem.STATE2_POWER_SAVE_FLAG;
5092 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode enabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005093 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005094 mPowerSaveModeEnabledTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005095 } else {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005096 mHistoryCur.states2 &= ~HistoryItem.STATE2_POWER_SAVE_FLAG;
5097 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode disabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005098 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005099 mPowerSaveModeEnabledTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005100 }
5101 addHistoryRecordLocked(elapsedRealtime, uptime);
Bookatz90867622018-01-31 15:05:57 -08005102 StatsLog.write(StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED, enabled ?
5103 StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED__STATE__ON :
5104 StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED__STATE__OFF);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005105 }
5106 }
5107
Bookatzddccf0a2017-11-28 16:48:14 -08005108 public void noteDeviceIdleModeLocked(final int mode, String activeReason, int activeUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005109 final long elapsedRealtime = mClocks.elapsedRealtime();
5110 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005111 boolean nowIdling = mode == DEVICE_IDLE_MODE_DEEP;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005112 if (mDeviceIdling && !nowIdling && activeReason == null) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005113 // We don't go out of general idling mode until explicitly taken out of
5114 // device idle through going active or significant motion.
5115 nowIdling = true;
5116 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005117 boolean nowLightIdling = mode == DEVICE_IDLE_MODE_LIGHT;
5118 if (mDeviceLightIdling && !nowLightIdling && !nowIdling && activeReason == null) {
5119 // We don't go out of general light idling mode until explicitly taken out of
5120 // device idle through going active or significant motion.
5121 nowLightIdling = true;
5122 }
5123 if (activeReason != null && (mDeviceIdling || mDeviceLightIdling)) {
5124 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_ACTIVE,
5125 activeReason, activeUid);
5126 }
Bookatzddccf0a2017-11-28 16:48:14 -08005127 if (mDeviceIdling != nowIdling || mDeviceLightIdling != nowLightIdling) {
5128 int statsmode;
5129 if (nowIdling) statsmode = DEVICE_IDLE_MODE_DEEP;
5130 else if (nowLightIdling) statsmode = DEVICE_IDLE_MODE_LIGHT;
5131 else statsmode = DEVICE_IDLE_MODE_OFF;
5132 StatsLog.write(StatsLog.DEVICE_IDLING_MODE_STATE_CHANGED, statsmode);
5133 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005134 if (mDeviceIdling != nowIdling) {
5135 mDeviceIdling = nowIdling;
5136 int stepState = nowIdling ? STEP_LEVEL_MODE_DEVICE_IDLE : 0;
5137 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_DEVICE_IDLE) ^ stepState;
5138 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_DEVICE_IDLE) | stepState;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005139 if (nowIdling) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005140 mDeviceIdlingTimer.startRunningLocked(elapsedRealtime);
5141 } else {
5142 mDeviceIdlingTimer.stopRunningLocked(elapsedRealtime);
5143 }
5144 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005145 if (mDeviceLightIdling != nowLightIdling) {
5146 mDeviceLightIdling = nowLightIdling;
5147 if (nowLightIdling) {
5148 mDeviceLightIdlingTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005149 } else {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005150 mDeviceLightIdlingTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005151 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005152 }
5153 if (mDeviceIdleMode != mode) {
5154 mHistoryCur.states2 = (mHistoryCur.states2 & ~HistoryItem.STATE2_DEVICE_IDLE_MASK)
5155 | (mode << HistoryItem.STATE2_DEVICE_IDLE_SHIFT);
5156 if (DEBUG_HISTORY) Slog.v(TAG, "Device idle mode changed to: "
5157 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005158 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005159 long lastDuration = elapsedRealtime - mLastIdleTimeStart;
5160 mLastIdleTimeStart = elapsedRealtime;
5161 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
5162 if (lastDuration > mLongestLightIdleTime) {
5163 mLongestLightIdleTime = lastDuration;
5164 }
5165 mDeviceIdleModeLightTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005166 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005167 if (lastDuration > mLongestFullIdleTime) {
5168 mLongestFullIdleTime = lastDuration;
5169 }
5170 mDeviceIdleModeFullTimer.stopRunningLocked(elapsedRealtime);
5171 }
5172 if (mode == DEVICE_IDLE_MODE_LIGHT) {
5173 mDeviceIdleModeLightTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005174 } else if (mode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005175 mDeviceIdleModeFullTimer.startRunningLocked(elapsedRealtime);
5176 }
5177 mDeviceIdleMode = mode;
Bookatzddccf0a2017-11-28 16:48:14 -08005178 StatsLog.write(StatsLog.DEVICE_IDLE_MODE_STATE_CHANGED, mode);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005179 }
5180 }
5181
Dianne Hackborn3accca02013-09-20 09:32:11 -07005182 public void notePackageInstalledLocked(String pkgName, long versionCode) {
Joe Onoratoabded112016-02-08 16:49:39 -08005183 final long elapsedRealtime = mClocks.elapsedRealtime();
5184 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3accca02013-09-20 09:32:11 -07005185 // XXX need to figure out what to do with long version codes.
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005186 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_INSTALLED,
Dianne Hackborn3accca02013-09-20 09:32:11 -07005187 pkgName, (int)versionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005188 PackageChange pc = new PackageChange();
5189 pc.mPackageName = pkgName;
5190 pc.mUpdate = true;
5191 pc.mVersionCode = versionCode;
5192 addPackageChange(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005193 }
5194
5195 public void notePackageUninstalledLocked(String pkgName) {
Joe Onoratoabded112016-02-08 16:49:39 -08005196 final long elapsedRealtime = mClocks.elapsedRealtime();
5197 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005198 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_UNINSTALLED,
5199 pkgName, 0);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005200 PackageChange pc = new PackageChange();
5201 pc.mPackageName = pkgName;
5202 pc.mUpdate = true;
5203 addPackageChange(pc);
5204 }
5205
5206 private void addPackageChange(PackageChange pc) {
5207 if (mDailyPackageChanges == null) {
5208 mDailyPackageChanges = new ArrayList<>();
5209 }
5210 mDailyPackageChanges.add(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005211 }
5212
Siddharth Ray78ccaf52017-12-23 16:16:21 -08005213 void stopAllGpsSignalQualityTimersLocked(int except) {
5214 final long elapsedRealtime = mClocks.elapsedRealtime();
5215 for (int i = 0; i < GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
5216 if (i == except) {
5217 continue;
5218 }
5219 while (mGpsSignalQualityTimer[i].isRunningLocked()) {
5220 mGpsSignalQualityTimer[i].stopRunningLocked(elapsedRealtime);
5221 }
5222 }
5223 }
5224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005225 public void notePhoneOnLocked() {
5226 if (!mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005227 final long elapsedRealtime = mClocks.elapsedRealtime();
5228 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005229 mHistoryCur.states2 |= HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005230 if (DEBUG_HISTORY) Slog.v(TAG, "Phone on to: "
5231 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005232 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005233 mPhoneOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005234 mPhoneOnTimer.startRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005235 }
5236 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005238 public void notePhoneOffLocked() {
5239 if (mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005240 final long elapsedRealtime = mClocks.elapsedRealtime();
5241 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005242 mHistoryCur.states2 &= ~HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005243 if (DEBUG_HISTORY) Slog.v(TAG, "Phone off to: "
5244 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005245 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005246 mPhoneOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005247 mPhoneOnTimer.stopRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005248 }
5249 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07005250
Mike Mafbc01fc2018-04-02 10:28:28 -07005251 private void registerUsbStateReceiver(Context context) {
5252 final IntentFilter usbStateFilter = new IntentFilter();
5253 usbStateFilter.addAction(UsbManager.ACTION_USB_STATE);
5254 context.registerReceiver(new BroadcastReceiver() {
5255 @Override
5256 public void onReceive(Context context, Intent intent) {
5257 final boolean state = intent.getBooleanExtra(UsbManager.USB_CONNECTED, false);
5258 synchronized (BatteryStatsImpl.this) {
5259 noteUsbConnectionStateLocked(state);
5260 }
5261 }
5262 }, usbStateFilter);
5263 synchronized (this) {
5264 if (mUsbDataState == USB_DATA_UNKNOWN) {
5265 final Intent usbState = context.registerReceiver(null, usbStateFilter);
5266 final boolean initState = usbState != null && usbState.getBooleanExtra(
5267 UsbManager.USB_CONNECTED, false);
5268 noteUsbConnectionStateLocked(initState);
5269 }
5270 }
5271 }
5272
5273 private void noteUsbConnectionStateLocked(boolean connected) {
5274 int newState = connected ? USB_DATA_CONNECTED : USB_DATA_DISCONNECTED;
Mike Ma926a97c2018-03-25 02:32:35 -07005275 if (mUsbDataState != newState) {
5276 mUsbDataState = newState;
5277 if (connected) {
5278 mHistoryCur.states2 |= HistoryItem.STATE2_USB_DATA_LINK_FLAG;
5279 } else {
5280 mHistoryCur.states2 &= ~HistoryItem.STATE2_USB_DATA_LINK_FLAG;
5281 }
5282 addHistoryRecordLocked(mClocks.elapsedRealtime(), mClocks.uptimeMillis());
5283 }
5284 }
5285
Dianne Hackborn3251b902014-06-20 14:40:53 -07005286 void stopAllPhoneSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005287 final long elapsedRealtime = mClocks.elapsedRealtime();
Wink Saville52840902011-02-18 12:40:47 -08005288 for (int i = 0; i < SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005289 if (i == except) {
5290 continue;
5291 }
5292 while (mPhoneSignalStrengthsTimer[i].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005293 mPhoneSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005294 }
5295 }
5296 }
5297
Dianne Hackborne4a59512010-12-07 11:08:07 -08005298 private int fixPhoneServiceState(int state, int signalBin) {
5299 if (mPhoneSimStateRaw == TelephonyManager.SIM_STATE_ABSENT) {
5300 // In this case we will always be STATE_OUT_OF_SERVICE, so need
5301 // to infer that we are scanning from other data.
5302 if (state == ServiceState.STATE_OUT_OF_SERVICE
Wink Saville52840902011-02-18 12:40:47 -08005303 && signalBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005304 state = ServiceState.STATE_IN_SERVICE;
5305 }
5306 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005307
Dianne Hackborne4a59512010-12-07 11:08:07 -08005308 return state;
5309 }
5310
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005311 private void updateAllPhoneStateLocked(int state, int simState, int strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005312 boolean scanning = false;
5313 boolean newHistory = false;
5314
5315 mPhoneServiceStateRaw = state;
5316 mPhoneSimStateRaw = simState;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005317 mPhoneSignalStrengthBinRaw = strengthBin;
5318
Joe Onoratoabded112016-02-08 16:49:39 -08005319 final long elapsedRealtime = mClocks.elapsedRealtime();
5320 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne4a59512010-12-07 11:08:07 -08005321
5322 if (simState == TelephonyManager.SIM_STATE_ABSENT) {
5323 // In this case we will always be STATE_OUT_OF_SERVICE, so need
5324 // to infer that we are scanning from other data.
5325 if (state == ServiceState.STATE_OUT_OF_SERVICE
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005326 && strengthBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005327 state = ServiceState.STATE_IN_SERVICE;
5328 }
5329 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005330
5331 // If the phone is powered off, stop all timers.
5332 if (state == ServiceState.STATE_POWER_OFF) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005333 strengthBin = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -07005334
Dianne Hackborne4a59512010-12-07 11:08:07 -08005335 // If we are in service, make sure the correct signal string timer is running.
5336 } else if (state == ServiceState.STATE_IN_SERVICE) {
5337 // Bin will be changed below.
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005338
5339 // If we're out of service, we are in the lowest signal strength
5340 // bin and have the scanning bit set.
Amith Yamasanif37447b2009-10-08 18:28:01 -07005341 } else if (state == ServiceState.STATE_OUT_OF_SERVICE) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005342 scanning = true;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005343 strengthBin = SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN;
Amith Yamasanif37447b2009-10-08 18:28:01 -07005344 if (!mPhoneSignalScanningTimer.isRunningLocked()) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005345 mHistoryCur.states |= HistoryItem.STATE_PHONE_SCANNING_FLAG;
Dianne Hackborne4a59512010-12-07 11:08:07 -08005346 newHistory = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005347 if (DEBUG_HISTORY) Slog.v(TAG, "Phone started scanning to: "
5348 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005349 mPhoneSignalScanningTimer.startRunningLocked(elapsedRealtime);
Amith Yamasanif37447b2009-10-08 18:28:01 -07005350 }
5351 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005352
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005353 if (!scanning) {
5354 // If we are no longer scanning, then stop the scanning timer.
5355 if (mPhoneSignalScanningTimer.isRunningLocked()) {
5356 mHistoryCur.states &= ~HistoryItem.STATE_PHONE_SCANNING_FLAG;
5357 if (DEBUG_HISTORY) Slog.v(TAG, "Phone stopped scanning to: "
5358 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08005359 newHistory = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005360 mPhoneSignalScanningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005361 }
5362 }
5363
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005364 if (mPhoneServiceState != state) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005365 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_STATE_MASK)
5366 | (state << HistoryItem.STATE_PHONE_STATE_SHIFT);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005367 if (DEBUG_HISTORY) Slog.v(TAG, "Phone state " + state + " to: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005368 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08005369 newHistory = true;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005370 mPhoneServiceState = state;
5371 }
Dianne Hackborne4a59512010-12-07 11:08:07 -08005372
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005373 if (mPhoneSignalStrengthBin != strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005374 if (mPhoneSignalStrengthBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005375 mPhoneSignalStrengthsTimer[mPhoneSignalStrengthBin].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005376 elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005377 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005378 if (strengthBin >= 0) {
5379 if (!mPhoneSignalStrengthsTimer[strengthBin].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005380 mPhoneSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005381 }
Dianne Hackborn3251b902014-06-20 14:40:53 -07005382 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_MASK)
5383 | (strengthBin << HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_SHIFT);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005384 if (DEBUG_HISTORY) Slog.v(TAG, "Signal strength " + strengthBin + " to: "
Dianne Hackborne4a59512010-12-07 11:08:07 -08005385 + Integer.toHexString(mHistoryCur.states));
5386 newHistory = true;
Bookatze5885242017-10-24 20:10:31 -07005387 StatsLog.write(StatsLog.PHONE_SIGNAL_STRENGTH_CHANGED, strengthBin);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005388 } else {
Dianne Hackborn3251b902014-06-20 14:40:53 -07005389 stopAllPhoneSignalStrengthTimersLocked(-1);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005390 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005391 mPhoneSignalStrengthBin = strengthBin;
Dianne Hackborne4a59512010-12-07 11:08:07 -08005392 }
5393
5394 if (newHistory) {
Dianne Hackborn40c87252014-03-19 16:55:40 -07005395 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005396 }
5397 }
5398
5399 /**
5400 * Telephony stack updates the phone state.
5401 * @param state phone state from ServiceState.getState()
5402 */
5403 public void notePhoneStateLocked(int state, int simState) {
5404 updateAllPhoneStateLocked(state, simState, mPhoneSignalStrengthBinRaw);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07005405 }
5406
Wink Savillee9b06d72009-05-18 21:47:50 -07005407 public void notePhoneSignalStrengthLocked(SignalStrength signalStrength) {
Dianne Hackborn627bba72009-03-24 22:32:56 -07005408 // Bin the strength.
Wink Saville52840902011-02-18 12:40:47 -08005409 int bin = signalStrength.getLevel();
Dianne Hackborne4a59512010-12-07 11:08:07 -08005410 updateAllPhoneStateLocked(mPhoneServiceStateRaw, mPhoneSimStateRaw, bin);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005411 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005412
Dianne Hackborn627bba72009-03-24 22:32:56 -07005413 public void notePhoneDataConnectionStateLocked(int dataType, boolean hasData) {
Tej Singheee317b2018-03-07 19:28:05 -08005414 // BatteryStats uses 0 to represent no network type.
5415 // Telephony does not have a concept of no network type, and uses 0 to represent unknown.
5416 // Unknown is included in DATA_CONNECTION_OTHER.
Dianne Hackborn627bba72009-03-24 22:32:56 -07005417 int bin = DATA_CONNECTION_NONE;
5418 if (hasData) {
Tej Singheee317b2018-03-07 19:28:05 -08005419 if (dataType > 0 && dataType <= TelephonyManager.MAX_NETWORK_TYPE) {
5420 bin = dataType;
5421 } else {
5422 bin = DATA_CONNECTION_OTHER;
Dianne Hackborn627bba72009-03-24 22:32:56 -07005423 }
5424 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07005425 if (DEBUG) Log.i(TAG, "Phone Data Connection -> " + dataType + " = " + hasData);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005426 if (mPhoneDataConnectionType != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005427 final long elapsedRealtime = mClocks.elapsedRealtime();
5428 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005429 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_DATA_CONNECTION_MASK)
5430 | (bin << HistoryItem.STATE_DATA_CONNECTION_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005431 if (DEBUG_HISTORY) Slog.v(TAG, "Data connection " + bin + " to: "
5432 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005433 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005434 if (mPhoneDataConnectionType >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005435 mPhoneDataConnectionsTimer[mPhoneDataConnectionType].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005436 elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005437 }
5438 mPhoneDataConnectionType = bin;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005439 mPhoneDataConnectionsTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005440 }
5441 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005442
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005443 public void noteWifiOnLocked() {
The Android Open Source Project10592532009-03-18 17:39:46 -07005444 if (!mWifiOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005445 final long elapsedRealtime = mClocks.elapsedRealtime();
5446 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005447 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005448 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI on to: "
5449 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005450 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005451 mWifiOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005452 mWifiOnTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005453 scheduleSyncExternalStatsLocked("wifi-off", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07005454 }
5455 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005456
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005457 public void noteWifiOffLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08005458 final long elapsedRealtime = mClocks.elapsedRealtime();
5459 final long uptime = mClocks.uptimeMillis();
The Android Open Source Project10592532009-03-18 17:39:46 -07005460 if (mWifiOn) {
Dianne Hackborn3251b902014-06-20 14:40:53 -07005461 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005462 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI off to: "
5463 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005464 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005465 mWifiOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005466 mWifiOnTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005467 scheduleSyncExternalStatsLocked("wifi-on", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07005468 }
5469 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005470
5471 public void noteAudioOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005472 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005473 final long elapsedRealtime = mClocks.elapsedRealtime();
5474 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005475 if (mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005476 mHistoryCur.states |= HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005477 if (DEBUG_HISTORY) Slog.v(TAG, "Audio on to: "
5478 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005479 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005480 mAudioOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005481 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005482 mAudioOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005483 getUidStatsLocked(uid).noteAudioTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005484 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005485
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005486 public void noteAudioOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005487 if (mAudioOnNesting == 0) {
5488 return;
5489 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08005490 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005491 final long elapsedRealtime = mClocks.elapsedRealtime();
5492 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005493 if (--mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005494 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005495 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
5496 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005497 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005498 mAudioOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005499 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005500 getUidStatsLocked(uid).noteAudioTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005501 }
5502
5503 public void noteVideoOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005504 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005505 final long elapsedRealtime = mClocks.elapsedRealtime();
5506 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005507 if (mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005508 mHistoryCur.states2 |= HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005509 if (DEBUG_HISTORY) Slog.v(TAG, "Video on to: "
5510 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005511 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005512 mVideoOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005513 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005514 mVideoOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005515 getUidStatsLocked(uid).noteVideoTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005516 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005517
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005518 public void noteVideoOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005519 if (mVideoOnNesting == 0) {
5520 return;
5521 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08005522 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005523 final long elapsedRealtime = mClocks.elapsedRealtime();
5524 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005525 if (--mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005526 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005527 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
5528 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005529 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005530 mVideoOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005531 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005532 getUidStatsLocked(uid).noteVideoTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005533 }
5534
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005535 public void noteResetAudioLocked() {
5536 if (mAudioOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005537 final long elapsedRealtime = mClocks.elapsedRealtime();
5538 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005539 mAudioOnNesting = 0;
5540 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
5541 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
5542 + Integer.toHexString(mHistoryCur.states));
5543 addHistoryRecordLocked(elapsedRealtime, uptime);
5544 mAudioOnTimer.stopAllRunningLocked(elapsedRealtime);
5545 for (int i=0; i<mUidStats.size(); i++) {
5546 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5547 uid.noteResetAudioLocked(elapsedRealtime);
5548 }
5549 }
5550 }
5551
5552 public void noteResetVideoLocked() {
5553 if (mVideoOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005554 final long elapsedRealtime = mClocks.elapsedRealtime();
5555 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005556 mAudioOnNesting = 0;
5557 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
5558 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
5559 + Integer.toHexString(mHistoryCur.states));
5560 addHistoryRecordLocked(elapsedRealtime, uptime);
5561 mVideoOnTimer.stopAllRunningLocked(elapsedRealtime);
5562 for (int i=0; i<mUidStats.size(); i++) {
5563 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5564 uid.noteResetVideoLocked(elapsedRealtime);
5565 }
5566 }
5567 }
5568
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005569 public void noteActivityResumedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005570 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005571 getUidStatsLocked(uid).noteActivityResumedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005572 }
5573
5574 public void noteActivityPausedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005575 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005576 getUidStatsLocked(uid).noteActivityPausedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005577 }
5578
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005579 public void noteVibratorOnLocked(int uid, long durationMillis) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005580 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005581 getUidStatsLocked(uid).noteVibratorOnLocked(durationMillis);
5582 }
5583
5584 public void noteVibratorOffLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005585 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005586 getUidStatsLocked(uid).noteVibratorOffLocked();
5587 }
5588
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005589 public void noteFlashlightOnLocked(int uid) {
5590 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005591 final long elapsedRealtime = mClocks.elapsedRealtime();
5592 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005593 if (mFlashlightOnNesting++ == 0) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005594 mHistoryCur.states2 |= HistoryItem.STATE2_FLASHLIGHT_FLAG;
5595 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight on to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005596 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005597 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005598 mFlashlightOnTimer.startRunningLocked(elapsedRealtime);
5599 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005600 getUidStatsLocked(uid).noteFlashlightTurnedOnLocked(elapsedRealtime);
5601 }
5602
5603 public void noteFlashlightOffLocked(int uid) {
5604 if (mFlashlightOnNesting == 0) {
5605 return;
5606 }
5607 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005608 final long elapsedRealtime = mClocks.elapsedRealtime();
5609 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005610 if (--mFlashlightOnNesting == 0) {
5611 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
5612 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
5613 + Integer.toHexString(mHistoryCur.states2));
5614 addHistoryRecordLocked(elapsedRealtime, uptime);
5615 mFlashlightOnTimer.stopRunningLocked(elapsedRealtime);
5616 }
5617 getUidStatsLocked(uid).noteFlashlightTurnedOffLocked(elapsedRealtime);
5618 }
5619
5620 public void noteCameraOnLocked(int uid) {
5621 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005622 final long elapsedRealtime = mClocks.elapsedRealtime();
5623 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005624 if (mCameraOnNesting++ == 0) {
5625 mHistoryCur.states2 |= HistoryItem.STATE2_CAMERA_FLAG;
5626 if (DEBUG_HISTORY) Slog.v(TAG, "Camera on to: "
5627 + Integer.toHexString(mHistoryCur.states2));
5628 addHistoryRecordLocked(elapsedRealtime, uptime);
5629 mCameraOnTimer.startRunningLocked(elapsedRealtime);
5630 }
5631 getUidStatsLocked(uid).noteCameraTurnedOnLocked(elapsedRealtime);
5632 }
5633
5634 public void noteCameraOffLocked(int uid) {
5635 if (mCameraOnNesting == 0) {
5636 return;
5637 }
5638 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005639 final long elapsedRealtime = mClocks.elapsedRealtime();
5640 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005641 if (--mCameraOnNesting == 0) {
5642 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
5643 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
5644 + Integer.toHexString(mHistoryCur.states2));
5645 addHistoryRecordLocked(elapsedRealtime, uptime);
5646 mCameraOnTimer.stopRunningLocked(elapsedRealtime);
5647 }
5648 getUidStatsLocked(uid).noteCameraTurnedOffLocked(elapsedRealtime);
5649 }
5650
5651 public void noteResetCameraLocked() {
5652 if (mCameraOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005653 final long elapsedRealtime = mClocks.elapsedRealtime();
5654 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005655 mCameraOnNesting = 0;
5656 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
5657 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
5658 + Integer.toHexString(mHistoryCur.states2));
5659 addHistoryRecordLocked(elapsedRealtime, uptime);
5660 mCameraOnTimer.stopAllRunningLocked(elapsedRealtime);
5661 for (int i=0; i<mUidStats.size(); i++) {
5662 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5663 uid.noteResetCameraLocked(elapsedRealtime);
5664 }
5665 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005666 }
5667
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005668 public void noteResetFlashlightLocked() {
5669 if (mFlashlightOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005670 final long elapsedRealtime = mClocks.elapsedRealtime();
5671 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005672 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005673 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
5674 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005675 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005676 addHistoryRecordLocked(elapsedRealtime, uptime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005677 mFlashlightOnTimer.stopAllRunningLocked(elapsedRealtime);
5678 for (int i=0; i<mUidStats.size(); i++) {
5679 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5680 uid.noteResetFlashlightLocked(elapsedRealtime);
5681 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005682 }
5683 }
5684
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005685 private void noteBluetoothScanStartedLocked(WorkChain workChain, int uid,
5686 boolean isUnoptimized) {
5687 uid = getAttributionUid(uid, workChain);
Bookatz867c0d72017-03-07 18:23:42 -08005688 final long elapsedRealtime = mClocks.elapsedRealtime();
5689 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005690 if (mBluetoothScanNesting == 0) {
5691 mHistoryCur.states2 |= HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5692 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan started for: "
5693 + Integer.toHexString(mHistoryCur.states2));
5694 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005695 mBluetoothScanTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005696 }
5697 mBluetoothScanNesting++;
Bookatzb1f04f32017-05-19 13:57:32 -07005698 getUidStatsLocked(uid).noteBluetoothScanStartedLocked(elapsedRealtime, isUnoptimized);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005699 }
5700
Bookatzb1f04f32017-05-19 13:57:32 -07005701 public void noteBluetoothScanStartedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005702 final int N = ws.size();
5703 for (int i = 0; i < N; i++) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005704 noteBluetoothScanStartedLocked(null, ws.get(i), isUnoptimized);
5705 }
5706
5707 final List<WorkChain> workChains = ws.getWorkChains();
5708 if (workChains != null) {
5709 for (int i = 0; i < workChains.size(); ++i) {
5710 noteBluetoothScanStartedLocked(workChains.get(i), -1, isUnoptimized);
5711 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005712 }
5713 }
5714
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005715 private void noteBluetoothScanStoppedLocked(WorkChain workChain, int uid,
5716 boolean isUnoptimized) {
5717 uid = getAttributionUid(uid, workChain);
Bookatz867c0d72017-03-07 18:23:42 -08005718 final long elapsedRealtime = mClocks.elapsedRealtime();
5719 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005720 mBluetoothScanNesting--;
5721 if (mBluetoothScanNesting == 0) {
5722 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5723 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan stopped for: "
5724 + Integer.toHexString(mHistoryCur.states2));
5725 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005726 mBluetoothScanTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005727 }
Bookatz94c5a312017-07-11 16:49:17 -07005728 getUidStatsLocked(uid).noteBluetoothScanStoppedLocked(elapsedRealtime, isUnoptimized);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005729 }
5730
5731 private int getAttributionUid(int uid, WorkChain workChain) {
5732 if (workChain != null) {
5733 return mapUid(workChain.getAttributionUid());
5734 }
5735
5736 return mapUid(uid);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005737 }
5738
Bookatz94c5a312017-07-11 16:49:17 -07005739 public void noteBluetoothScanStoppedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005740 final int N = ws.size();
5741 for (int i = 0; i < N; i++) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005742 noteBluetoothScanStoppedLocked(null, ws.get(i), isUnoptimized);
5743 }
5744
5745 final List<WorkChain> workChains = ws.getWorkChains();
5746 if (workChains != null) {
5747 for (int i = 0; i < workChains.size(); ++i) {
5748 noteBluetoothScanStoppedLocked(workChains.get(i), -1, isUnoptimized);
5749 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005750 }
5751 }
5752
5753 public void noteResetBluetoothScanLocked() {
5754 if (mBluetoothScanNesting > 0) {
Bookatz867c0d72017-03-07 18:23:42 -08005755 final long elapsedRealtime = mClocks.elapsedRealtime();
5756 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005757 mBluetoothScanNesting = 0;
5758 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5759 if (DEBUG_HISTORY) Slog.v(TAG, "BLE can stopped for: "
5760 + Integer.toHexString(mHistoryCur.states2));
5761 addHistoryRecordLocked(elapsedRealtime, uptime);
5762 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtime);
5763 for (int i=0; i<mUidStats.size(); i++) {
5764 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5765 uid.noteResetBluetoothScanLocked(elapsedRealtime);
5766 }
5767 }
5768 }
5769
Bookatz4ebc0642017-05-11 12:21:19 -07005770 public void noteBluetoothScanResultsFromSourceLocked(WorkSource ws, int numNewResults) {
Bookatz956f36bf2017-04-28 09:48:17 -07005771 final int N = ws.size();
5772 for (int i = 0; i < N; i++) {
5773 int uid = mapUid(ws.get(i));
Bookatz4ebc0642017-05-11 12:21:19 -07005774 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Yangster-mac2f5daec2018-01-16 10:23:15 -08005775 StatsLog.write_non_chained(StatsLog.BLE_SCAN_RESULT_RECEIVED, ws.get(i), ws.getName(i),
5776 numNewResults);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005777 }
5778
5779 final List<WorkChain> workChains = ws.getWorkChains();
5780 if (workChains != null) {
5781 for (int i = 0; i < workChains.size(); ++i) {
5782 final WorkChain wc = workChains.get(i);
5783 int uid = mapUid(wc.getAttributionUid());
5784 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Yangster-macafad8c62018-01-05 22:30:49 -08005785 StatsLog.write(StatsLog.BLE_SCAN_RESULT_RECEIVED,
5786 wc.getUids(), wc.getTags(), numNewResults);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005787 }
Bookatz956f36bf2017-04-28 09:48:17 -07005788 }
5789 }
5790
Adam Lesinski5f056f62016-07-14 16:56:08 -07005791 private void noteWifiRadioApWakeupLocked(final long elapsedRealtimeMillis,
5792 final long uptimeMillis, int uid) {
5793 uid = mapUid(uid);
5794 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
5795 uid);
5796 getUidStatsLocked(uid).noteWifiRadioApWakeupLocked();
5797 }
5798
5799 public void noteWifiRadioPowerState(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005800 final long elapsedRealtime = mClocks.elapsedRealtime();
5801 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005802 if (mWifiRadioPowerState != powerState) {
5803 final boolean active =
5804 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
5805 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
5806 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07005807 if (uid > 0) {
5808 noteWifiRadioApWakeupLocked(elapsedRealtime, uptime, uid);
5809 }
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005810 mHistoryCur.states |= HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
Siddharth Rayb50a6842017-12-14 15:15:28 -08005811 mWifiActiveTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005812 } else {
5813 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
Siddharth Rayb50a6842017-12-14 15:15:28 -08005814 mWifiActiveTimer.stopRunningLocked(
5815 timestampNs / (1000 * 1000));
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005816 }
5817 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi network active " + active + " to: "
5818 + Integer.toHexString(mHistoryCur.states));
5819 addHistoryRecordLocked(elapsedRealtime, uptime);
5820 mWifiRadioPowerState = powerState;
Bookatzddccf0a2017-11-28 16:48:14 -08005821 StatsLog.write(StatsLog.WIFI_RADIO_POWER_STATE_CHANGED, uid, powerState);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005822 }
5823 }
5824
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005825 public void noteWifiRunningLocked(WorkSource ws) {
5826 if (!mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005827 final long elapsedRealtime = mClocks.elapsedRealtime();
5828 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005829 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005830 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI running to: "
5831 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005832 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005833 mGlobalWifiRunning = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005834 mGlobalWifiRunningTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005835 int N = ws.size();
5836 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005837 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005838 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005839 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005840
5841 List<WorkChain> workChains = ws.getWorkChains();
5842 if (workChains != null) {
5843 for (int i = 0; i < workChains.size(); ++i) {
5844 int uid = mapUid(workChains.get(i).getAttributionUid());
5845 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
5846 }
5847 }
5848
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005849 scheduleSyncExternalStatsLocked("wifi-running", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005850 } else {
5851 Log.w(TAG, "noteWifiRunningLocked -- called while WIFI running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005852 }
5853 }
5854
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005855 public void noteWifiRunningChangedLocked(WorkSource oldWs, WorkSource newWs) {
5856 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005857 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005858 int N = oldWs.size();
5859 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005860 int uid = mapUid(oldWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005861 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005862 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005863
5864 List<WorkChain> workChains = oldWs.getWorkChains();
5865 if (workChains != null) {
5866 for (int i = 0; i < workChains.size(); ++i) {
5867 int uid = mapUid(workChains.get(i).getAttributionUid());
5868 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
5869 }
5870 }
5871
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005872 N = newWs.size();
5873 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005874 int uid = mapUid(newWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005875 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005876 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005877
5878 workChains = newWs.getWorkChains();
5879 if (workChains != null) {
5880 for (int i = 0; i < workChains.size(); ++i) {
5881 int uid = mapUid(workChains.get(i).getAttributionUid());
5882 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
5883 }
5884 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005885 } else {
5886 Log.w(TAG, "noteWifiRunningChangedLocked -- called while WIFI not running");
5887 }
5888 }
5889
5890 public void noteWifiStoppedLocked(WorkSource ws) {
5891 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005892 final long elapsedRealtime = mClocks.elapsedRealtime();
5893 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005894 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005895 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI stopped to: "
5896 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005897 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005898 mGlobalWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005899 mGlobalWifiRunningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005900 int N = ws.size();
5901 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005902 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005903 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005904 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005905
5906 List<WorkChain> workChains = ws.getWorkChains();
5907 if (workChains != null) {
5908 for (int i = 0; i < workChains.size(); ++i) {
5909 int uid = mapUid(workChains.get(i).getAttributionUid());
5910 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
5911 }
5912 }
5913
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005914 scheduleSyncExternalStatsLocked("wifi-stopped", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005915 } else {
5916 Log.w(TAG, "noteWifiStoppedLocked -- called while WIFI not running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005917 }
5918 }
5919
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005920 public void noteWifiStateLocked(int wifiState, String accessPoint) {
5921 if (DEBUG) Log.i(TAG, "WiFi state -> " + wifiState);
5922 if (mWifiState != wifiState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005923 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005924 if (mWifiState >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005925 mWifiStateTimer[mWifiState].stopRunningLocked(elapsedRealtime);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005926 }
5927 mWifiState = wifiState;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005928 mWifiStateTimer[wifiState].startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005929 scheduleSyncExternalStatsLocked("wifi-state", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005930 }
5931 }
5932
Dianne Hackborn3251b902014-06-20 14:40:53 -07005933 public void noteWifiSupplicantStateChangedLocked(int supplState, boolean failedAuth) {
5934 if (DEBUG) Log.i(TAG, "WiFi suppl state -> " + supplState);
5935 if (mWifiSupplState != supplState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005936 final long elapsedRealtime = mClocks.elapsedRealtime();
5937 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005938 if (mWifiSupplState >= 0) {
5939 mWifiSupplStateTimer[mWifiSupplState].stopRunningLocked(elapsedRealtime);
5940 }
5941 mWifiSupplState = supplState;
5942 mWifiSupplStateTimer[supplState].startRunningLocked(elapsedRealtime);
5943 mHistoryCur.states2 =
5944 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SUPPL_STATE_MASK)
5945 | (supplState << HistoryItem.STATE2_WIFI_SUPPL_STATE_SHIFT);
5946 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi suppl state " + supplState + " to: "
5947 + Integer.toHexString(mHistoryCur.states2));
5948 addHistoryRecordLocked(elapsedRealtime, uptime);
5949 }
5950 }
5951
5952 void stopAllWifiSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005953 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005954 for (int i = 0; i < NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
5955 if (i == except) {
5956 continue;
5957 }
5958 while (mWifiSignalStrengthsTimer[i].isRunningLocked()) {
5959 mWifiSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
5960 }
5961 }
5962 }
5963
5964 public void noteWifiRssiChangedLocked(int newRssi) {
5965 int strengthBin = WifiManager.calculateSignalLevel(newRssi, NUM_WIFI_SIGNAL_STRENGTH_BINS);
5966 if (DEBUG) Log.i(TAG, "WiFi rssi -> " + newRssi + " bin=" + strengthBin);
5967 if (mWifiSignalStrengthBin != strengthBin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005968 final long elapsedRealtime = mClocks.elapsedRealtime();
5969 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005970 if (mWifiSignalStrengthBin >= 0) {
5971 mWifiSignalStrengthsTimer[mWifiSignalStrengthBin].stopRunningLocked(
5972 elapsedRealtime);
5973 }
5974 if (strengthBin >= 0) {
5975 if (!mWifiSignalStrengthsTimer[strengthBin].isRunningLocked()) {
5976 mWifiSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
5977 }
5978 mHistoryCur.states2 =
5979 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_MASK)
5980 | (strengthBin << HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_SHIFT);
5981 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi signal strength " + strengthBin + " to: "
5982 + Integer.toHexString(mHistoryCur.states2));
5983 addHistoryRecordLocked(elapsedRealtime, uptime);
5984 } else {
5985 stopAllWifiSignalStrengthTimersLocked(-1);
5986 }
Bookatz235343d2018-03-26 13:03:50 -07005987 StatsLog.write(StatsLog.WIFI_SIGNAL_STRENGTH_CHANGED, strengthBin);
Dianne Hackborn3251b902014-06-20 14:40:53 -07005988 mWifiSignalStrengthBin = strengthBin;
5989 }
5990 }
5991
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005992 int mWifiFullLockNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005993
The Android Open Source Project10592532009-03-18 17:39:46 -07005994 public void noteFullWifiLockAcquiredLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005995 final long elapsedRealtime = mClocks.elapsedRealtime();
5996 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005997 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005998 mHistoryCur.states |= HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005999 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock on to: "
6000 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006001 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006002 }
6003 mWifiFullLockNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006004 getUidStatsLocked(uid).noteFullWifiLockAcquiredLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006005 }
6006
6007 public void noteFullWifiLockReleasedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006008 final long elapsedRealtime = mClocks.elapsedRealtime();
6009 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006010 mWifiFullLockNesting--;
6011 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006012 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006013 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock off to: "
6014 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006015 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006016 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006017 getUidStatsLocked(uid).noteFullWifiLockReleasedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006018 }
6019
Nick Pelly6ccaa542012-06-15 15:22:47 -07006020 int mWifiScanNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006021
Nick Pelly6ccaa542012-06-15 15:22:47 -07006022 public void noteWifiScanStartedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006023 final long elapsedRealtime = mClocks.elapsedRealtime();
6024 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07006025 if (mWifiScanNesting == 0) {
6026 mHistoryCur.states |= HistoryItem.STATE_WIFI_SCAN_FLAG;
6027 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan started for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006028 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006029 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006030 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07006031 mWifiScanNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006032 getUidStatsLocked(uid).noteWifiScanStartedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006033 }
6034
Nick Pelly6ccaa542012-06-15 15:22:47 -07006035 public void noteWifiScanStoppedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006036 final long elapsedRealtime = mClocks.elapsedRealtime();
6037 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07006038 mWifiScanNesting--;
6039 if (mWifiScanNesting == 0) {
6040 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_SCAN_FLAG;
6041 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan stopped for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006042 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006043 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006044 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006045 getUidStatsLocked(uid).noteWifiScanStoppedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006046 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006047
Robert Greenwalta029ea12013-09-25 16:38:12 -07006048 public void noteWifiBatchedScanStartedLocked(int uid, int csph) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006049 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006050 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006051 getUidStatsLocked(uid).noteWifiBatchedScanStartedLocked(csph, elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006052 }
6053
6054 public void noteWifiBatchedScanStoppedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006055 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006056 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006057 getUidStatsLocked(uid).noteWifiBatchedScanStoppedLocked(elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006058 }
6059
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006060 int mWifiMulticastNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006061
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006062 public void noteWifiMulticastEnabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006063 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006064 final long elapsedRealtime = mClocks.elapsedRealtime();
6065 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006066 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006067 mHistoryCur.states |= HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006068 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast on to: "
6069 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006070 addHistoryRecordLocked(elapsedRealtime, uptime);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006071
6072 // Start Wifi Multicast overall timer
6073 if (!mWifiMulticastWakelockTimer.isRunningLocked()) {
6074 if (DEBUG_HISTORY) Slog.v(TAG, "WiFi Multicast Overall Timer Started");
6075 mWifiMulticastWakelockTimer.startRunningLocked(elapsedRealtime);
6076 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006077 }
6078 mWifiMulticastNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006079 getUidStatsLocked(uid).noteWifiMulticastEnabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006080 }
6081
6082 public void noteWifiMulticastDisabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006083 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006084 final long elapsedRealtime = mClocks.elapsedRealtime();
6085 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006086 mWifiMulticastNesting--;
6087 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006088 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006089 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast off to: "
6090 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006091 addHistoryRecordLocked(elapsedRealtime, uptime);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006092
6093 // Stop Wifi Multicast overall timer
6094 if (mWifiMulticastWakelockTimer.isRunningLocked()) {
6095 if (DEBUG_HISTORY) Slog.v(TAG, "Multicast Overall Timer Stopped");
6096 mWifiMulticastWakelockTimer.stopRunningLocked(elapsedRealtime);
6097 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006098 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006099 getUidStatsLocked(uid).noteWifiMulticastDisabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006100 }
6101
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006102 public void noteFullWifiLockAcquiredFromSourceLocked(WorkSource ws) {
6103 int N = ws.size();
6104 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006105 final int uid = mapUid(ws.get(i));
6106 noteFullWifiLockAcquiredLocked(uid);
Bookatz90867622018-01-31 15:05:57 -08006107 StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, ws.get(i), ws.getName(i),
6108 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006109 }
6110
6111 final List<WorkChain> workChains = ws.getWorkChains();
6112 if (workChains != null) {
6113 for (int i = 0; i < workChains.size(); ++i) {
6114 final WorkChain workChain = workChains.get(i);
6115 final int uid = mapUid(workChain.getAttributionUid());
6116 noteFullWifiLockAcquiredLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006117 StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006118 workChain.getUids(), workChain.getTags(),
6119 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006120 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006121 }
6122 }
6123
6124 public void noteFullWifiLockReleasedFromSourceLocked(WorkSource ws) {
6125 int N = ws.size();
6126 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006127 final int uid = mapUid(ws.get(i));
6128 noteFullWifiLockReleasedLocked(uid);
Bookatz90867622018-01-31 15:05:57 -08006129 StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, ws.get(i), ws.getName(i),
6130 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006131 }
6132
6133 final List<WorkChain> workChains = ws.getWorkChains();
6134 if (workChains != null) {
6135 for (int i = 0; i < workChains.size(); ++i) {
6136 final WorkChain workChain = workChains.get(i);
6137 final int uid = mapUid(workChain.getAttributionUid());
6138 noteFullWifiLockReleasedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006139 StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006140 workChain.getUids(), workChain.getTags(),
6141 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006142 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006143 }
6144 }
6145
Nick Pelly6ccaa542012-06-15 15:22:47 -07006146 public void noteWifiScanStartedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006147 int N = ws.size();
6148 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006149 final int uid = mapUid(ws.get(i));
6150 noteWifiScanStartedLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08006151 StatsLog.write_non_chained(StatsLog.WIFI_SCAN_STATE_CHANGED, ws.get(i), ws.getName(i),
Bookatz90867622018-01-31 15:05:57 -08006152 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006153 }
6154
6155 final List<WorkChain> workChains = ws.getWorkChains();
6156 if (workChains != null) {
6157 for (int i = 0; i < workChains.size(); ++i) {
6158 final WorkChain workChain = workChains.get(i);
6159 final int uid = mapUid(workChain.getAttributionUid());
6160 noteWifiScanStartedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006161 StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED, workChain.getUids(),
Bookatz90867622018-01-31 15:05:57 -08006162 workChain.getTags(), StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006163 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006164 }
6165 }
6166
Nick Pelly6ccaa542012-06-15 15:22:47 -07006167 public void noteWifiScanStoppedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006168 int N = ws.size();
6169 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006170 final int uid = mapUid(ws.get(i));
6171 noteWifiScanStoppedLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08006172 StatsLog.write_non_chained(StatsLog.WIFI_SCAN_STATE_CHANGED, ws.get(i), ws.getName(i),
Bookatz90867622018-01-31 15:05:57 -08006173 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006174 }
6175
6176 final List<WorkChain> workChains = ws.getWorkChains();
6177 if (workChains != null) {
6178 for (int i = 0; i < workChains.size(); ++i) {
6179 final WorkChain workChain = workChains.get(i);
6180 final int uid = mapUid(workChain.getAttributionUid());
6181 noteWifiScanStoppedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006182 StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006183 workChain.getUids(), workChain.getTags(),
6184 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006185 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006186 }
6187 }
6188
Robert Greenwalta029ea12013-09-25 16:38:12 -07006189 public void noteWifiBatchedScanStartedFromSourceLocked(WorkSource ws, int csph) {
6190 int N = ws.size();
6191 for (int i=0; i<N; i++) {
6192 noteWifiBatchedScanStartedLocked(ws.get(i), csph);
6193 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00006194
6195 final List<WorkChain> workChains = ws.getWorkChains();
6196 if (workChains != null) {
6197 for (int i = 0; i < workChains.size(); ++i) {
6198 noteWifiBatchedScanStartedLocked(workChains.get(i).getAttributionUid(), csph);
6199 }
6200 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006201 }
6202
6203 public void noteWifiBatchedScanStoppedFromSourceLocked(WorkSource ws) {
6204 int N = ws.size();
6205 for (int i=0; i<N; i++) {
6206 noteWifiBatchedScanStoppedLocked(ws.get(i));
6207 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00006208
6209 final List<WorkChain> workChains = ws.getWorkChains();
6210 if (workChains != null) {
6211 for (int i = 0; i < workChains.size(); ++i) {
6212 noteWifiBatchedScanStoppedLocked(workChains.get(i).getAttributionUid());
6213 }
6214 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006215 }
6216
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08006217 private static String[] includeInStringArray(String[] array, String str) {
6218 if (ArrayUtils.indexOf(array, str) >= 0) {
6219 return array;
6220 }
6221 String[] newArray = new String[array.length+1];
6222 System.arraycopy(array, 0, newArray, 0, array.length);
6223 newArray[array.length] = str;
6224 return newArray;
6225 }
6226
6227 private static String[] excludeFromStringArray(String[] array, String str) {
6228 int index = ArrayUtils.indexOf(array, str);
6229 if (index >= 0) {
6230 String[] newArray = new String[array.length-1];
6231 if (index > 0) {
6232 System.arraycopy(array, 0, newArray, 0, index);
6233 }
6234 if (index < array.length-1) {
6235 System.arraycopy(array, index+1, newArray, index, array.length-index-1);
6236 }
6237 return newArray;
6238 }
6239 return array;
6240 }
6241
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07006242 public void noteNetworkInterfaceTypeLocked(String iface, int networkType) {
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07006243 if (TextUtils.isEmpty(iface)) return;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006244
Adam Lesinski14ae39a2017-05-26 11:50:40 -07006245 synchronized (mModemNetworkLock) {
6246 if (ConnectivityManager.isNetworkTypeMobile(networkType)) {
6247 mModemIfaces = includeInStringArray(mModemIfaces, iface);
6248 if (DEBUG) Slog.d(TAG, "Note mobile iface " + iface + ": " + mModemIfaces);
6249 } else {
6250 mModemIfaces = excludeFromStringArray(mModemIfaces, iface);
6251 if (DEBUG) Slog.d(TAG, "Note non-mobile iface " + iface + ": " + mModemIfaces);
6252 }
6253 }
6254
6255 synchronized (mWifiNetworkLock) {
6256 if (ConnectivityManager.isNetworkTypeWifi(networkType)) {
6257 mWifiIfaces = includeInStringArray(mWifiIfaces, iface);
6258 if (DEBUG) Slog.d(TAG, "Note wifi iface " + iface + ": " + mWifiIfaces);
6259 } else {
6260 mWifiIfaces = excludeFromStringArray(mWifiIfaces, iface);
6261 if (DEBUG) Slog.d(TAG, "Note non-wifi iface " + iface + ": " + mWifiIfaces);
6262 }
6263 }
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07006264 }
6265
David Chenc8a43242017-10-17 16:23:28 -07006266 public String[] getWifiIfaces() {
6267 synchronized (mWifiNetworkLock) {
6268 return mWifiIfaces;
6269 }
6270 }
6271
6272 public String[] getMobileIfaces() {
6273 synchronized (mModemNetworkLock) {
6274 return mModemIfaces;
6275 }
6276 }
6277
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006278 @Override public long getScreenOnTime(long elapsedRealtimeUs, int which) {
6279 return mScreenOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006280 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006281
Dianne Hackborn77b987f2014-02-26 16:20:52 -08006282 @Override public int getScreenOnCount(int which) {
6283 return mScreenOnTimer.getCountLocked(which);
6284 }
6285
Mike Mac2f518a2017-09-19 16:06:03 -07006286 @Override public long getScreenDozeTime(long elapsedRealtimeUs, int which) {
6287 return mScreenDozeTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6288 }
6289
6290 @Override public int getScreenDozeCount(int which) {
6291 return mScreenDozeTimer.getCountLocked(which);
6292 }
6293
Dianne Hackborn617f8772009-03-31 15:04:46 -07006294 @Override public long getScreenBrightnessTime(int brightnessBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006295 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006296 return mScreenBrightnessTimer[brightnessBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006297 elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006298 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006299
Kweku Adams87b19ec2017-10-09 12:40:03 -07006300 @Override public Timer getScreenBrightnessTimer(int brightnessBin) {
6301 return mScreenBrightnessTimer[brightnessBin];
6302 }
6303
Jeff Browne95c3cd2014-05-02 16:59:26 -07006304 @Override public long getInteractiveTime(long elapsedRealtimeUs, int which) {
6305 return mInteractiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006306 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006307
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006308 @Override public long getPowerSaveModeEnabledTime(long elapsedRealtimeUs, int which) {
6309 return mPowerSaveModeEnabledTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07006310 }
6311
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006312 @Override public int getPowerSaveModeEnabledCount(int which) {
6313 return mPowerSaveModeEnabledTimer.getCountLocked(which);
6314 }
6315
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006316 @Override public long getDeviceIdleModeTime(int mode, long elapsedRealtimeUs,
6317 int which) {
6318 switch (mode) {
6319 case DEVICE_IDLE_MODE_LIGHT:
6320 return mDeviceIdleModeLightTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006321 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006322 return mDeviceIdleModeFullTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6323 }
6324 return 0;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006325 }
6326
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006327 @Override public int getDeviceIdleModeCount(int mode, int which) {
6328 switch (mode) {
6329 case DEVICE_IDLE_MODE_LIGHT:
6330 return mDeviceIdleModeLightTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006331 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006332 return mDeviceIdleModeFullTimer.getCountLocked(which);
6333 }
6334 return 0;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07006335 }
6336
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006337 @Override public long getLongestDeviceIdleModeTime(int mode) {
6338 switch (mode) {
6339 case DEVICE_IDLE_MODE_LIGHT:
6340 return mLongestLightIdleTime;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006341 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006342 return mLongestFullIdleTime;
6343 }
6344 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07006345 }
6346
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006347 @Override public long getDeviceIdlingTime(int mode, long elapsedRealtimeUs, int which) {
6348 switch (mode) {
6349 case DEVICE_IDLE_MODE_LIGHT:
6350 return mDeviceLightIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006351 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006352 return mDeviceIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6353 }
6354 return 0;
6355 }
6356
6357 @Override public int getDeviceIdlingCount(int mode, int which) {
6358 switch (mode) {
6359 case DEVICE_IDLE_MODE_LIGHT:
6360 return mDeviceLightIdlingTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006361 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006362 return mDeviceIdlingTimer.getCountLocked(which);
6363 }
6364 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07006365 }
6366
Dianne Hackborn1e01d162014-12-04 17:46:42 -08006367 @Override public int getNumConnectivityChange(int which) {
6368 int val = mNumConnectivityChange;
6369 if (which == STATS_CURRENT) {
6370 val -= mLoadedNumConnectivityChange;
6371 } else if (which == STATS_SINCE_UNPLUGGED) {
6372 val -= mUnpluggedNumConnectivityChange;
6373 }
6374 return val;
6375 }
6376
Siddharth Ray78ccaf52017-12-23 16:16:21 -08006377 @Override public long getGpsSignalQualityTime(int strengthBin,
6378 long elapsedRealtimeUs, int which) {
6379 if (strengthBin < 0 || strengthBin >= GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS) {
6380 return 0;
6381 }
6382 return mGpsSignalQualityTimer[strengthBin].getTotalTimeLocked(
6383 elapsedRealtimeUs, which);
6384 }
6385
6386 @Override public long getGpsBatteryDrainMaMs() {
Siddharth Ray0ed2e952018-01-22 11:32:14 -08006387 final double opVolt = mPowerProfile.getAveragePower(
6388 PowerProfile.POWER_GPS_OPERATING_VOLTAGE) / 1000.0;
6389 if (opVolt == 0) {
6390 return 0;
6391 }
6392 double energyUsedMaMs = 0.0;
6393 final int which = STATS_SINCE_CHARGED;
6394 final long rawRealtime = SystemClock.elapsedRealtime() * 1000;
6395 for(int i=0; i < GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
6396 energyUsedMaMs
6397 += mPowerProfile.getAveragePower(PowerProfile.POWER_GPS_SIGNAL_QUALITY_BASED, i)
6398 * (getGpsSignalQualityTime(i, rawRealtime, which) / 1000);
6399 }
6400 return (long) energyUsedMaMs;
Siddharth Ray78ccaf52017-12-23 16:16:21 -08006401 }
6402
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006403 @Override public long getPhoneOnTime(long elapsedRealtimeUs, int which) {
6404 return mPhoneOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006405 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006406
Dianne Hackborn77b987f2014-02-26 16:20:52 -08006407 @Override public int getPhoneOnCount(int which) {
6408 return mPhoneOnTimer.getCountLocked(which);
6409 }
6410
Dianne Hackborn627bba72009-03-24 22:32:56 -07006411 @Override public long getPhoneSignalStrengthTime(int strengthBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006412 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006413 return mPhoneSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006414 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07006415 }
Amith Yamasanif37447b2009-10-08 18:28:01 -07006416
6417 @Override public long getPhoneSignalScanningTime(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006418 long elapsedRealtimeUs, int which) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07006419 return mPhoneSignalScanningTimer.getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006420 elapsedRealtimeUs, which);
Amith Yamasanif37447b2009-10-08 18:28:01 -07006421 }
6422
Kweku Adams87b19ec2017-10-09 12:40:03 -07006423 @Override public Timer getPhoneSignalScanningTimer() {
6424 return mPhoneSignalScanningTimer;
6425 }
6426
Catherine Liufb900812012-07-17 14:12:56 -05006427 @Override public int getPhoneSignalStrengthCount(int strengthBin, int which) {
6428 return mPhoneSignalStrengthsTimer[strengthBin].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006429 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006430
Kweku Adams87b19ec2017-10-09 12:40:03 -07006431 @Override public Timer getPhoneSignalStrengthTimer(int strengthBin) {
6432 return mPhoneSignalStrengthsTimer[strengthBin];
6433 }
6434
Dianne Hackborn627bba72009-03-24 22:32:56 -07006435 @Override public long getPhoneDataConnectionTime(int dataType,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006436 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006437 return mPhoneDataConnectionsTimer[dataType].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006438 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07006439 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006440
Dianne Hackborn617f8772009-03-31 15:04:46 -07006441 @Override public int getPhoneDataConnectionCount(int dataType, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006442 return mPhoneDataConnectionsTimer[dataType].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006443 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006444
Kweku Adams87b19ec2017-10-09 12:40:03 -07006445 @Override public Timer getPhoneDataConnectionTimer(int dataType) {
6446 return mPhoneDataConnectionsTimer[dataType];
6447 }
6448
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006449 @Override public long getMobileRadioActiveTime(long elapsedRealtimeUs, int which) {
6450 return mMobileRadioActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborne13c4c02014-02-11 17:18:35 -08006451 }
6452
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006453 @Override public int getMobileRadioActiveCount(int which) {
6454 return mMobileRadioActiveTimer.getCountLocked(which);
6455 }
6456
Dianne Hackborna1bd7922014-03-21 11:07:11 -07006457 @Override public long getMobileRadioActiveAdjustedTime(int which) {
6458 return mMobileRadioActiveAdjustedTime.getCountLocked(which);
6459 }
6460
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006461 @Override public long getMobileRadioActiveUnknownTime(int which) {
6462 return mMobileRadioActiveUnknownTime.getCountLocked(which);
6463 }
6464
6465 @Override public int getMobileRadioActiveUnknownCount(int which) {
6466 return (int)mMobileRadioActiveUnknownCount.getCountLocked(which);
6467 }
6468
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006469 @Override public long getWifiMulticastWakelockTime(
6470 long elapsedRealtimeUs, int which) {
6471 return mWifiMulticastWakelockTimer.getTotalTimeLocked(
6472 elapsedRealtimeUs, which);
6473 }
6474
6475 @Override public int getWifiMulticastWakelockCount(int which) {
6476 return mWifiMulticastWakelockTimer.getCountLocked(which);
6477 }
6478
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006479 @Override public long getWifiOnTime(long elapsedRealtimeUs, int which) {
6480 return mWifiOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07006481 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006482
Siddharth Rayb50a6842017-12-14 15:15:28 -08006483 @Override public long getWifiActiveTime(long elapsedRealtimeUs, int which) {
6484 return mWifiActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6485 }
6486
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006487 @Override public long getGlobalWifiRunningTime(long elapsedRealtimeUs, int which) {
6488 return mGlobalWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07006489 }
6490
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006491 @Override public long getWifiStateTime(int wifiState,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006492 long elapsedRealtimeUs, int which) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006493 return mWifiStateTimer[wifiState].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006494 elapsedRealtimeUs, which);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006495 }
6496
6497 @Override public int getWifiStateCount(int wifiState, int which) {
6498 return mWifiStateTimer[wifiState].getCountLocked(which);
6499 }
6500
Kweku Adams87b19ec2017-10-09 12:40:03 -07006501 @Override public Timer getWifiStateTimer(int wifiState) {
6502 return mWifiStateTimer[wifiState];
6503 }
6504
Dianne Hackborn3251b902014-06-20 14:40:53 -07006505 @Override public long getWifiSupplStateTime(int state,
6506 long elapsedRealtimeUs, int which) {
6507 return mWifiSupplStateTimer[state].getTotalTimeLocked(
6508 elapsedRealtimeUs, which);
6509 }
6510
6511 @Override public int getWifiSupplStateCount(int state, int which) {
6512 return mWifiSupplStateTimer[state].getCountLocked(which);
6513 }
6514
Kweku Adams87b19ec2017-10-09 12:40:03 -07006515 @Override public Timer getWifiSupplStateTimer(int state) {
6516 return mWifiSupplStateTimer[state];
6517 }
6518
Dianne Hackborn3251b902014-06-20 14:40:53 -07006519 @Override public long getWifiSignalStrengthTime(int strengthBin,
6520 long elapsedRealtimeUs, int which) {
6521 return mWifiSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
6522 elapsedRealtimeUs, which);
6523 }
6524
6525 @Override public int getWifiSignalStrengthCount(int strengthBin, int which) {
6526 return mWifiSignalStrengthsTimer[strengthBin].getCountLocked(which);
6527 }
6528
Kweku Adams87b19ec2017-10-09 12:40:03 -07006529 @Override public Timer getWifiSignalStrengthTimer(int strengthBin) {
6530 return mWifiSignalStrengthsTimer[strengthBin];
6531 }
6532
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006533 @Override
6534 public ControllerActivityCounter getBluetoothControllerActivity() {
6535 return mBluetoothActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07006536 }
6537
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006538 @Override
6539 public ControllerActivityCounter getWifiControllerActivity() {
6540 return mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -07006541 }
6542
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006543 @Override
6544 public ControllerActivityCounter getModemControllerActivity() {
6545 return mModemActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07006546 }
6547
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006548 @Override
6549 public boolean hasBluetoothActivityReporting() {
6550 return mHasBluetoothReporting;
6551 }
6552
6553 @Override
6554 public boolean hasWifiActivityReporting() {
6555 return mHasWifiReporting;
6556 }
6557
6558 @Override
6559 public boolean hasModemActivityReporting() {
6560 return mHasModemReporting;
Adam Lesinski33dac552015-03-09 15:24:48 -07006561 }
6562
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006563 @Override
6564 public long getFlashlightOnTime(long elapsedRealtimeUs, int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07006565 return mFlashlightOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6566 }
6567
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006568 @Override
6569 public long getFlashlightOnCount(int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07006570 return mFlashlightOnTimer.getCountLocked(which);
6571 }
6572
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006573 @Override
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006574 public long getCameraOnTime(long elapsedRealtimeUs, int which) {
6575 return mCameraOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6576 }
6577
6578 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006579 public long getBluetoothScanTime(long elapsedRealtimeUs, int which) {
6580 return mBluetoothScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6581 }
6582
6583 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006584 public long getNetworkActivityBytes(int type, int which) {
6585 if (type >= 0 && type < mNetworkByteActivityCounters.length) {
6586 return mNetworkByteActivityCounters[type].getCountLocked(which);
6587 } else {
6588 return 0;
6589 }
6590 }
6591
6592 @Override
6593 public long getNetworkActivityPackets(int type, int which) {
6594 if (type >= 0 && type < mNetworkPacketActivityCounters.length) {
6595 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006596 } else {
6597 return 0;
6598 }
6599 }
6600
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08006601 @Override public long getStartClockTime() {
Dianne Hackbornd48954f2015-07-22 17:20:33 -07006602 final long currentTime = System.currentTimeMillis();
6603 if (ensureStartClockTime(currentTime)) {
Joe Onoratoabded112016-02-08 16:49:39 -08006604 recordCurrentTimeChangeLocked(currentTime, mClocks.elapsedRealtime(),
6605 mClocks.uptimeMillis());
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07006606 }
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08006607 return mStartClockTime;
6608 }
6609
Dianne Hackborncd0e3352014-08-07 17:08:09 -07006610 @Override public String getStartPlatformVersion() {
6611 return mStartPlatformVersion;
6612 }
6613
6614 @Override public String getEndPlatformVersion() {
6615 return mEndPlatformVersion;
6616 }
6617
6618 @Override public int getParcelVersion() {
6619 return VERSION;
6620 }
6621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006622 @Override public boolean getIsOnBattery() {
6623 return mOnBattery;
6624 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006626 @Override public SparseArray<? extends BatteryStats.Uid> getUidStats() {
6627 return mUidStats;
6628 }
6629
Adam Lesinski5f056f62016-07-14 16:56:08 -07006630 private static void detachTimerIfNotNull(BatteryStatsImpl.Timer timer) {
6631 if (timer != null) {
6632 timer.detach();
6633 }
6634 }
6635
6636 private static boolean resetTimerIfNotNull(BatteryStatsImpl.Timer timer,
6637 boolean detachIfReset) {
6638 if (timer != null) {
6639 return timer.reset(detachIfReset);
6640 }
6641 return true;
6642 }
6643
Bookatz867c0d72017-03-07 18:23:42 -08006644 private static boolean resetTimerIfNotNull(DualTimer timer, boolean detachIfReset) {
6645 if (timer != null) {
6646 return timer.reset(detachIfReset);
6647 }
6648 return true;
6649 }
6650
Adam Lesinski5f056f62016-07-14 16:56:08 -07006651 private static void detachLongCounterIfNotNull(LongSamplingCounter counter) {
6652 if (counter != null) {
6653 counter.detach();
6654 }
6655 }
6656
6657 private static void resetLongCounterIfNotNull(LongSamplingCounter counter,
6658 boolean detachIfReset) {
6659 if (counter != null) {
6660 counter.reset(detachIfReset);
6661 }
6662 }
6663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006664 /**
6665 * The statistics associated with a particular uid.
6666 */
Joe Onoratoabded112016-02-08 16:49:39 -08006667 public static class Uid extends BatteryStats.Uid {
6668 /**
6669 * BatteryStatsImpl that we are associated with.
6670 */
6671 protected BatteryStatsImpl mBsi;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006673 final int mUid;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006674
Bookatz867c0d72017-03-07 18:23:42 -08006675 /** TimeBase for when uid is in background and device is on battery. */
6676 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6677 public final TimeBase mOnBatteryBackgroundTimeBase;
Bookatzc8c44962017-05-11 12:12:54 -07006678 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6679 public final TimeBase mOnBatteryScreenOffBackgroundTimeBase;
Bookatz867c0d72017-03-07 18:23:42 -08006680
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006681 boolean mWifiRunning;
6682 StopwatchTimer mWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006683
The Android Open Source Project10592532009-03-18 17:39:46 -07006684 boolean mFullWifiLockOut;
Evan Millarc64edde2009-04-18 12:26:32 -07006685 StopwatchTimer mFullWifiLockTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006686
Nick Pelly6ccaa542012-06-15 15:22:47 -07006687 boolean mWifiScanStarted;
Bookatz867c0d72017-03-07 18:23:42 -08006688 DualTimer mWifiScanTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006689
Dianne Hackborn61659e52014-07-09 16:13:01 -07006690 static final int NO_BATCHED_SCAN_STARTED = -1;
Robert Greenwalta029ea12013-09-25 16:38:12 -07006691 int mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
6692 StopwatchTimer[] mWifiBatchedScanTimer;
6693
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006694 boolean mWifiMulticastEnabled;
6695 StopwatchTimer mWifiMulticastTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006696
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006697 StopwatchTimer mAudioTurnedOnTimer;
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006698 StopwatchTimer mVideoTurnedOnTimer;
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006699 StopwatchTimer mFlashlightTurnedOnTimer;
6700 StopwatchTimer mCameraTurnedOnTimer;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006701 StopwatchTimer mForegroundActivityTimer;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006702 StopwatchTimer mForegroundServiceTimer;
Bookatzc8c44962017-05-11 12:12:54 -07006703 /** Total time spent by the uid holding any partial wakelocks. */
6704 DualTimer mAggregatedPartialWakelockTimer;
Bookatz867c0d72017-03-07 18:23:42 -08006705 DualTimer mBluetoothScanTimer;
Bookatzb1f04f32017-05-19 13:57:32 -07006706 DualTimer mBluetoothUnoptimizedScanTimer;
Bookatz956f36bf2017-04-28 09:48:17 -07006707 Counter mBluetoothScanResultCounter;
Bookatzb1f04f32017-05-19 13:57:32 -07006708 Counter mBluetoothScanResultBgCounter;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006709
Dianne Hackborna8d10942015-11-19 17:55:19 -08006710 int mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07006711 StopwatchTimer[] mProcessStateTimer;
6712
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006713 boolean mInForegroundService = false;
6714
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006715 BatchTimer mVibratorOnTimer;
6716
Dianne Hackborn617f8772009-03-31 15:04:46 -07006717 Counter[] mUserActivityCounters;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006718
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006719 LongSamplingCounter[] mNetworkByteActivityCounters;
6720 LongSamplingCounter[] mNetworkPacketActivityCounters;
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006721 LongSamplingCounter mMobileRadioActiveTime;
6722 LongSamplingCounter mMobileRadioActiveCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006724 /**
Adam Lesinski5f056f62016-07-14 16:56:08 -07006725 * How many times this UID woke up the Application Processor due to a Mobile radio packet.
6726 */
6727 private LongSamplingCounter mMobileRadioApWakeupCount;
6728
6729 /**
6730 * How many times this UID woke up the Application Processor due to a Wifi packet.
6731 */
6732 private LongSamplingCounter mWifiRadioApWakeupCount;
6733
6734 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07006735 * The amount of time this uid has kept the WiFi controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006736 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07006737 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006738 private ControllerActivityCounterImpl mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006739
6740 /**
6741 * The amount of time this uid has kept the Bluetooth controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006742 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07006743 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006744 private ControllerActivityCounterImpl mBluetoothControllerActivity;
6745
6746 /**
6747 * The amount of time this uid has kept the Modem controller in idle, tx, and rx mode.
6748 * Can be null if the UID has had no such activity.
6749 */
6750 private ControllerActivityCounterImpl mModemControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006751
6752 /**
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006753 * The CPU times we had at the last history details update.
6754 */
6755 long mLastStepUserTime;
6756 long mLastStepSystemTime;
6757 long mCurStepUserTime;
6758 long mCurStepSystemTime;
6759
Joe Onoratoabded112016-02-08 16:49:39 -08006760 LongSamplingCounter mUserCpuTime;
6761 LongSamplingCounter mSystemCpuTime;
Sudheer Shankaaf857412017-07-21 00:14:24 -07006762 LongSamplingCounter[][] mCpuClusterSpeedTimesUs;
Mike Ma3d422c32017-10-25 11:08:57 -07006763 LongSamplingCounter mCpuActiveTimeMs;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006764
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006765 LongSamplingCounterArray mCpuFreqTimeMs;
6766 LongSamplingCounterArray mScreenOffCpuFreqTimeMs;
Mike Ma3d422c32017-10-25 11:08:57 -07006767 LongSamplingCounterArray mCpuClusterTimesMs;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006768
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006769 LongSamplingCounterArray[] mProcStateTimeMs;
6770 LongSamplingCounterArray[] mProcStateScreenOffTimeMs;
6771
6772 IntArray mChildUids;
6773
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006774 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006775 * The statistics we have collected for this uid's wake locks.
6776 */
Joe Onoratoabded112016-02-08 16:49:39 -08006777 final OverflowArrayMap<Wakelock> mWakelockStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006778
6779 /**
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006780 * The statistics we have collected for this uid's syncs.
6781 */
Bookatz2bffb5b2017-04-13 11:59:33 -07006782 final OverflowArrayMap<DualTimer> mSyncStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006783
6784 /**
6785 * The statistics we have collected for this uid's jobs.
6786 */
Bookatzaa4594a2017-03-24 12:39:56 -07006787 final OverflowArrayMap<DualTimer> mJobStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006788
6789 /**
Dianne Hackborn94326cb2017-06-28 16:17:20 -07006790 * Count of the jobs that have completed and the reasons why they completed.
6791 */
6792 final ArrayMap<String, SparseIntArray> mJobCompletions = new ArrayMap<>();
6793
6794 /**
Amith Yamasani977e11f2018-02-16 11:29:54 -08006795 * Count of app launch events that had associated deferred job counts or info about
6796 * last time a job was run.
6797 */
6798 Counter mJobsDeferredEventCount;
6799
6800 /**
6801 * Count of deferred jobs that were pending when the app was launched or brought to
6802 * the foreground through a user interaction.
6803 */
6804 Counter mJobsDeferredCount;
6805
6806 /**
6807 * Sum of time since the last time a job was run for this app before it was launched.
6808 */
6809 LongSamplingCounter mJobsFreshnessTimeMs;
6810
6811 /**
6812 * Array of counts of instances where the time since the last job was run for the app
6813 * fell within one of the thresholds in {@link #JOB_FRESHNESS_BUCKETS}.
6814 */
6815 final Counter[] mJobsFreshnessBuckets;
6816
6817 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006818 * The statistics we have collected for this uid's sensor activations.
6819 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006820 final SparseArray<Sensor> mSensorStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006821
6822 /**
6823 * The statistics we have collected for this uid's processes.
6824 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006825 final ArrayMap<String, Proc> mProcessStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006826
6827 /**
6828 * The statistics we have collected for this uid's processes.
6829 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006830 final ArrayMap<String, Pkg> mPackageStats = new ArrayMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006831
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006832 /**
6833 * The transient wake stats we have collected for this uid's pids.
6834 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006835 final SparseArray<Pid> mPids = new SparseArray<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006836
Joe Onoratoabded112016-02-08 16:49:39 -08006837 public Uid(BatteryStatsImpl bsi, int uid) {
6838 mBsi = bsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006839 mUid = uid;
Joe Onoratoabded112016-02-08 16:49:39 -08006840
Bookatz867c0d72017-03-07 18:23:42 -08006841 mOnBatteryBackgroundTimeBase = new TimeBase();
6842 mOnBatteryBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
6843 mBsi.mClocks.elapsedRealtime() * 1000);
6844
Bookatzc8c44962017-05-11 12:12:54 -07006845 mOnBatteryScreenOffBackgroundTimeBase = new TimeBase();
6846 mOnBatteryScreenOffBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
6847 mBsi.mClocks.elapsedRealtime() * 1000);
6848
Joe Onoratoabded112016-02-08 16:49:39 -08006849 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6850 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Mike Ma3d422c32017-10-25 11:08:57 -07006851 mCpuActiveTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6852 mCpuClusterTimesMs = new LongSamplingCounterArray(mBsi.mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006853
Dianne Hackborn657153b2016-07-29 14:54:14 -07006854 mWakelockStats = mBsi.new OverflowArrayMap<Wakelock>(uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006855 @Override public Wakelock instantiateObject() {
6856 return new Wakelock(mBsi, Uid.this);
6857 }
6858 };
Bookatz2bffb5b2017-04-13 11:59:33 -07006859 mSyncStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
6860 @Override public DualTimer instantiateObject() {
6861 return new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
6862 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006863 }
6864 };
Bookatzaa4594a2017-03-24 12:39:56 -07006865 mJobStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
6866 @Override public DualTimer instantiateObject() {
6867 return new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
6868 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006869 }
6870 };
6871
6872 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_RUNNING,
6873 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
6874 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, this, FULL_WIFI_LOCK,
6875 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Bookatz867c0d72017-03-07 18:23:42 -08006876 mWifiScanTimer = new DualTimer(mBsi.mClocks, this, WIFI_SCAN,
6877 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006878 mWifiBatchedScanTimer = new StopwatchTimer[NUM_WIFI_BATCHED_SCAN_BINS];
Joe Onoratoabded112016-02-08 16:49:39 -08006879 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_MULTICAST_ENABLED,
6880 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006881 mProcessStateTimer = new StopwatchTimer[NUM_PROCESS_STATE];
Amith Yamasani977e11f2018-02-16 11:29:54 -08006882 mJobsDeferredEventCount = new Counter(mBsi.mOnBatteryTimeBase);
6883 mJobsDeferredCount = new Counter(mBsi.mOnBatteryTimeBase);
6884 mJobsFreshnessTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6885 mJobsFreshnessBuckets = new Counter[JOB_FRESHNESS_BUCKETS.length];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006886 }
6887
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006888 @VisibleForTesting
6889 public void setProcessStateForTest(int procState) {
6890 mProcessState = procState;
6891 }
6892
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006893 @Override
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006894 public long[] getCpuFreqTimes(int which) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006895 return nullIfAllZeros(mCpuFreqTimeMs, which);
6896 }
6897
6898 @Override
6899 public long[] getScreenOffCpuFreqTimes(int which) {
6900 return nullIfAllZeros(mScreenOffCpuFreqTimeMs, which);
6901 }
6902
6903 @Override
Mike Ma3d422c32017-10-25 11:08:57 -07006904 public long getCpuActiveTime() {
6905 return mCpuActiveTimeMs.getCountLocked(STATS_SINCE_CHARGED);
6906 }
6907
6908 @Override
6909 public long[] getCpuClusterTimes() {
6910 return nullIfAllZeros(mCpuClusterTimesMs, STATS_SINCE_CHARGED);
6911 }
6912
6913
6914 @Override
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006915 public long[] getCpuFreqTimes(int which, int procState) {
6916 if (which < 0 || which >= NUM_PROCESS_STATE) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006917 return null;
6918 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006919 if (mProcStateTimeMs == null) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006920 return null;
6921 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006922 if (!mBsi.mPerProcStateCpuTimesAvailable) {
6923 mProcStateTimeMs = null;
6924 return null;
6925 }
6926 return nullIfAllZeros(mProcStateTimeMs[procState], which);
6927 }
6928
6929 @Override
6930 public long[] getScreenOffCpuFreqTimes(int which, int procState) {
6931 if (which < 0 || which >= NUM_PROCESS_STATE) {
6932 return null;
6933 }
6934 if (mProcStateScreenOffTimeMs == null) {
6935 return null;
6936 }
6937 if (!mBsi.mPerProcStateCpuTimesAvailable) {
6938 mProcStateScreenOffTimeMs = null;
6939 return null;
6940 }
6941 return nullIfAllZeros(mProcStateScreenOffTimeMs[procState], which);
6942 }
6943
6944 public void addIsolatedUid(int isolatedUid) {
6945 if (mChildUids == null) {
6946 mChildUids = new IntArray();
6947 } else if (mChildUids.indexOf(isolatedUid) >= 0) {
6948 return;
6949 }
6950 mChildUids.add(isolatedUid);
6951 }
6952
6953 public void removeIsolatedUid(int isolatedUid) {
6954 final int idx = mChildUids == null ? -1 : mChildUids.indexOf(isolatedUid);
6955 if (idx < 0) {
6956 return;
6957 }
6958 mChildUids.remove(idx);
6959 }
6960
6961 private long[] nullIfAllZeros(LongSamplingCounterArray cpuTimesMs, int which) {
6962 if (cpuTimesMs == null) {
6963 return null;
6964 }
6965 final long[] counts = cpuTimesMs.getCountsLocked(which);
6966 if (counts == null) {
6967 return null;
6968 }
6969 // Return counts only if at least one of the elements is non-zero.
6970 for (int i = counts.length - 1; i >= 0; --i) {
6971 if (counts[i] != 0) {
6972 return counts;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006973 }
6974 }
6975 return null;
6976 }
6977
Sudheer Shankae544d162017-12-28 17:06:20 -08006978 private void addProcStateTimesMs(int procState, long[] cpuTimesMs, boolean onBattery) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006979 if (mProcStateTimeMs == null) {
6980 mProcStateTimeMs = new LongSamplingCounterArray[NUM_PROCESS_STATE];
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006981 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006982 if (mProcStateTimeMs[procState] == null
6983 || mProcStateTimeMs[procState].getSize() != cpuTimesMs.length) {
6984 mProcStateTimeMs[procState] = new LongSamplingCounterArray(
6985 mBsi.mOnBatteryTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006986 }
Sudheer Shankae544d162017-12-28 17:06:20 -08006987 mProcStateTimeMs[procState].addCountLocked(cpuTimesMs, onBattery);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006988 }
6989
Sudheer Shankae544d162017-12-28 17:06:20 -08006990 private void addProcStateScreenOffTimesMs(int procState, long[] cpuTimesMs,
6991 boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006992 if (mProcStateScreenOffTimeMs == null) {
6993 mProcStateScreenOffTimeMs = new LongSamplingCounterArray[NUM_PROCESS_STATE];
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006994 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006995 if (mProcStateScreenOffTimeMs[procState] == null
6996 || mProcStateScreenOffTimeMs[procState].getSize() != cpuTimesMs.length) {
6997 mProcStateScreenOffTimeMs[procState] = new LongSamplingCounterArray(
6998 mBsi.mOnBatteryScreenOffTimeBase);
6999 }
Sudheer Shankae544d162017-12-28 17:06:20 -08007000 mProcStateScreenOffTimeMs[procState].addCountLocked(cpuTimesMs, onBatteryScreenOff);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007001 }
7002
7003 @Override
Bookatzc8c44962017-05-11 12:12:54 -07007004 public Timer getAggregatedPartialWakelockTimer() {
7005 return mAggregatedPartialWakelockTimer;
7006 }
7007
7008 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007009 public ArrayMap<String, ? extends BatteryStats.Uid.Wakelock> getWakelockStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007010 return mWakelockStats.getMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007011 }
7012
7013 @Override
Ahmed ElArabawyddd09692017-10-30 17:58:29 -07007014 public Timer getMulticastWakelockStats() {
7015 return mWifiMulticastTimer;
7016 }
7017
7018 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007019 public ArrayMap<String, ? extends BatteryStats.Timer> getSyncStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007020 return mSyncStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007021 }
7022
7023 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007024 public ArrayMap<String, ? extends BatteryStats.Timer> getJobStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007025 return mJobStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007026 }
7027
7028 @Override
Dianne Hackborn94326cb2017-06-28 16:17:20 -07007029 public ArrayMap<String, SparseIntArray> getJobCompletionStats() {
7030 return mJobCompletions;
7031 }
7032
7033 @Override
Dianne Hackborn61659e52014-07-09 16:13:01 -07007034 public SparseArray<? extends BatteryStats.Uid.Sensor> getSensorStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007035 return mSensorStats;
7036 }
7037
7038 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007039 public ArrayMap<String, ? extends BatteryStats.Uid.Proc> getProcessStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007040 return mProcessStats;
7041 }
7042
7043 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007044 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg> getPackageStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007045 return mPackageStats;
7046 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007047
7048 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007049 public int getUid() {
7050 return mUid;
7051 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007052
7053 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007054 public void noteWifiRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007055 if (!mWifiRunning) {
7056 mWifiRunning = true;
7057 if (mWifiRunningTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007058 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
7059 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007060 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007061 mWifiRunningTimer.startRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007062 }
7063 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007064
Dianne Hackborn617f8772009-03-31 15:04:46 -07007065 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007066 public void noteWifiStoppedLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007067 if (mWifiRunning) {
7068 mWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007069 mWifiRunningTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007070 }
7071 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007072
Dianne Hackborn617f8772009-03-31 15:04:46 -07007073 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007074 public void noteFullWifiLockAcquiredLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07007075 if (!mFullWifiLockOut) {
7076 mFullWifiLockOut = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007077 if (mFullWifiLockTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007078 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
7079 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007080 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007081 mFullWifiLockTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007082 }
7083 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007084
The Android Open Source Project10592532009-03-18 17:39:46 -07007085 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007086 public void noteFullWifiLockReleasedLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07007087 if (mFullWifiLockOut) {
7088 mFullWifiLockOut = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007089 mFullWifiLockTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007090 }
7091 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007092
The Android Open Source Project10592532009-03-18 17:39:46 -07007093 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007094 public void noteWifiScanStartedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007095 if (!mWifiScanStarted) {
7096 mWifiScanStarted = true;
7097 if (mWifiScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007098 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
7099 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase,
7100 mOnBatteryBackgroundTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007101 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007102 mWifiScanTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007103 }
7104 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007105
The Android Open Source Project10592532009-03-18 17:39:46 -07007106 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007107 public void noteWifiScanStoppedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007108 if (mWifiScanStarted) {
7109 mWifiScanStarted = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007110 mWifiScanTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007111 }
7112 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007113
7114 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007115 public void noteWifiBatchedScanStartedLocked(int csph, long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007116 int bin = 0;
Navtej Singh Mann3c0ce5c2015-06-11 16:53:11 -07007117 while (csph > 8 && bin < NUM_WIFI_BATCHED_SCAN_BINS-1) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007118 csph = csph >> 3;
7119 bin++;
7120 }
7121
7122 if (mWifiBatchedScanBinStarted == bin) return;
7123
7124 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
7125 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007126 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007127 }
7128 mWifiBatchedScanBinStarted = bin;
7129 if (mWifiBatchedScanTimer[bin] == null) {
7130 makeWifiBatchedScanBin(bin, null);
7131 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007132 mWifiBatchedScanTimer[bin].startRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007133 }
7134
7135 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007136 public void noteWifiBatchedScanStoppedLocked(long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007137 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
7138 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007139 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007140 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
7141 }
7142 }
7143
7144 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007145 public void noteWifiMulticastEnabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007146 if (!mWifiMulticastEnabled) {
7147 mWifiMulticastEnabled = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007148 if (mWifiMulticastTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007149 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7150 WIFI_MULTICAST_ENABLED, mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007151 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007152 mWifiMulticastTimer.startRunningLocked(elapsedRealtimeMs);
Tej Singh4503e102018-01-04 14:35:01 -08007153 StatsLog.write_non_chained(
Bookatz90867622018-01-31 15:05:57 -08007154 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED, getUid(), null,
7155 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED__STATE__ON);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007156 }
7157 }
7158
7159 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007160 public void noteWifiMulticastDisabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007161 if (mWifiMulticastEnabled) {
7162 mWifiMulticastEnabled = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007163 mWifiMulticastTimer.stopRunningLocked(elapsedRealtimeMs);
Tej Singh4503e102018-01-04 14:35:01 -08007164 StatsLog.write_non_chained(
Bookatz90867622018-01-31 15:05:57 -08007165 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED, getUid(), null,
7166 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED__STATE__OFF);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007167 }
7168 }
7169
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007170 @Override
7171 public ControllerActivityCounter getWifiControllerActivity() {
7172 return mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07007173 }
7174
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007175 @Override
7176 public ControllerActivityCounter getBluetoothControllerActivity() {
7177 return mBluetoothControllerActivity;
7178 }
7179
7180 @Override
7181 public ControllerActivityCounter getModemControllerActivity() {
7182 return mModemControllerActivity;
7183 }
7184
7185 public ControllerActivityCounterImpl getOrCreateWifiControllerActivityLocked() {
7186 if (mWifiControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007187 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007188 NUM_BT_TX_LEVELS);
Adam Lesinski50e47602015-12-04 17:04:54 -08007189 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007190 return mWifiControllerActivity;
7191 }
7192
7193 public ControllerActivityCounterImpl getOrCreateBluetoothControllerActivityLocked() {
7194 if (mBluetoothControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007195 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007196 NUM_BT_TX_LEVELS);
7197 }
7198 return mBluetoothControllerActivity;
7199 }
7200
7201 public ControllerActivityCounterImpl getOrCreateModemControllerActivityLocked() {
7202 if (mModemControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007203 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007204 ModemActivityInfo.TX_POWER_LEVELS);
7205 }
7206 return mModemControllerActivity;
Adam Lesinski50e47602015-12-04 17:04:54 -08007207 }
7208
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007209 public StopwatchTimer createAudioTurnedOnTimerLocked() {
7210 if (mAudioTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007211 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
7212 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007213 }
7214 return mAudioTurnedOnTimer;
7215 }
7216
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007217 public void noteAudioTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007218 createAudioTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
7219 }
7220
7221 public void noteAudioTurnedOffLocked(long elapsedRealtimeMs) {
7222 if (mAudioTurnedOnTimer != null) {
7223 mAudioTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007224 }
7225 }
7226
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007227 public void noteResetAudioLocked(long elapsedRealtimeMs) {
7228 if (mAudioTurnedOnTimer != null) {
7229 mAudioTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007230 }
7231 }
7232
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007233 public StopwatchTimer createVideoTurnedOnTimerLocked() {
7234 if (mVideoTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007235 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
7236 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007237 }
7238 return mVideoTurnedOnTimer;
7239 }
7240
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007241 public void noteVideoTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007242 createVideoTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
7243 }
7244
7245 public void noteVideoTurnedOffLocked(long elapsedRealtimeMs) {
7246 if (mVideoTurnedOnTimer != null) {
7247 mVideoTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007248 }
7249 }
7250
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007251 public void noteResetVideoLocked(long elapsedRealtimeMs) {
7252 if (mVideoTurnedOnTimer != null) {
7253 mVideoTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007254 }
7255 }
7256
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007257 public StopwatchTimer createFlashlightTurnedOnTimerLocked() {
7258 if (mFlashlightTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007259 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7260 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007261 }
7262 return mFlashlightTurnedOnTimer;
7263 }
7264
7265 public void noteFlashlightTurnedOnLocked(long elapsedRealtimeMs) {
7266 createFlashlightTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
7267 }
7268
7269 public void noteFlashlightTurnedOffLocked(long elapsedRealtimeMs) {
7270 if (mFlashlightTurnedOnTimer != null) {
7271 mFlashlightTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
7272 }
7273 }
7274
7275 public void noteResetFlashlightLocked(long elapsedRealtimeMs) {
7276 if (mFlashlightTurnedOnTimer != null) {
7277 mFlashlightTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
7278 }
7279 }
7280
7281 public StopwatchTimer createCameraTurnedOnTimerLocked() {
7282 if (mCameraTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007283 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
7284 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007285 }
7286 return mCameraTurnedOnTimer;
7287 }
7288
7289 public void noteCameraTurnedOnLocked(long elapsedRealtimeMs) {
7290 createCameraTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
7291 }
7292
7293 public void noteCameraTurnedOffLocked(long elapsedRealtimeMs) {
7294 if (mCameraTurnedOnTimer != null) {
7295 mCameraTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
7296 }
7297 }
7298
7299 public void noteResetCameraLocked(long elapsedRealtimeMs) {
7300 if (mCameraTurnedOnTimer != null) {
7301 mCameraTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
7302 }
7303 }
7304
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007305 public StopwatchTimer createForegroundActivityTimerLocked() {
7306 if (mForegroundActivityTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007307 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7308 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007309 }
7310 return mForegroundActivityTimer;
7311 }
7312
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007313 public StopwatchTimer createForegroundServiceTimerLocked() {
7314 if (mForegroundServiceTimer == null) {
7315 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7316 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase);
7317 }
7318 return mForegroundServiceTimer;
7319 }
7320
Bookatzc8c44962017-05-11 12:12:54 -07007321 public DualTimer createAggregatedPartialWakelockTimerLocked() {
7322 if (mAggregatedPartialWakelockTimer == null) {
7323 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
7324 AGGREGATED_WAKE_TYPE_PARTIAL, null,
7325 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase);
7326 }
7327 return mAggregatedPartialWakelockTimer;
7328 }
7329
Bookatz867c0d72017-03-07 18:23:42 -08007330 public DualTimer createBluetoothScanTimerLocked() {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007331 if (mBluetoothScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007332 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
7333 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
7334 mOnBatteryBackgroundTimeBase);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007335 }
7336 return mBluetoothScanTimer;
7337 }
7338
Bookatzb1f04f32017-05-19 13:57:32 -07007339 public DualTimer createBluetoothUnoptimizedScanTimerLocked() {
7340 if (mBluetoothUnoptimizedScanTimer == null) {
7341 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
7342 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
7343 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
7344 }
7345 return mBluetoothUnoptimizedScanTimer;
7346 }
7347
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00007348 public void noteBluetoothScanStartedLocked(long elapsedRealtimeMs,
7349 boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007350 createBluetoothScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatzb1f04f32017-05-19 13:57:32 -07007351 if (isUnoptimized) {
7352 createBluetoothUnoptimizedScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
7353 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007354 }
7355
Bookatz94c5a312017-07-11 16:49:17 -07007356 public void noteBluetoothScanStoppedLocked(long elapsedRealtimeMs, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007357 if (mBluetoothScanTimer != null) {
7358 mBluetoothScanTimer.stopRunningLocked(elapsedRealtimeMs);
7359 }
Bookatz94c5a312017-07-11 16:49:17 -07007360 if (isUnoptimized && mBluetoothUnoptimizedScanTimer != null) {
Bookatzb1f04f32017-05-19 13:57:32 -07007361 mBluetoothUnoptimizedScanTimer.stopRunningLocked(elapsedRealtimeMs);
7362 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007363 }
7364
7365 public void noteResetBluetoothScanLocked(long elapsedRealtimeMs) {
7366 if (mBluetoothScanTimer != null) {
7367 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
7368 }
Bookatzb1f04f32017-05-19 13:57:32 -07007369 if (mBluetoothUnoptimizedScanTimer != null) {
7370 mBluetoothUnoptimizedScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
7371 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007372 }
7373
Bookatz956f36bf2017-04-28 09:48:17 -07007374 public Counter createBluetoothScanResultCounterLocked() {
7375 if (mBluetoothScanResultCounter == null) {
7376 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase);
7377 }
7378 return mBluetoothScanResultCounter;
7379 }
7380
Bookatzb1f04f32017-05-19 13:57:32 -07007381 public Counter createBluetoothScanResultBgCounterLocked() {
7382 if (mBluetoothScanResultBgCounter == null) {
7383 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase);
7384 }
7385 return mBluetoothScanResultBgCounter;
7386 }
7387
Bookatz4ebc0642017-05-11 12:21:19 -07007388 public void noteBluetoothScanResultsLocked(int numNewResults) {
7389 createBluetoothScanResultCounterLocked().addAtomic(numNewResults);
Bookatzb1f04f32017-05-19 13:57:32 -07007390 // Uses background timebase, so the count will only be incremented if uid in background.
7391 createBluetoothScanResultBgCounterLocked().addAtomic(numNewResults);
Bookatz956f36bf2017-04-28 09:48:17 -07007392 }
7393
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007394 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007395 public void noteActivityResumedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007396 // We always start, since we want multiple foreground PIDs to nest
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007397 createForegroundActivityTimerLocked().startRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007398 }
7399
7400 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007401 public void noteActivityPausedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007402 if (mForegroundActivityTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007403 mForegroundActivityTimer.stopRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007404 }
7405 }
7406
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007407 public void noteForegroundServiceResumedLocked(long elapsedRealtimeMs) {
7408 createForegroundServiceTimerLocked().startRunningLocked(elapsedRealtimeMs);
7409 }
7410
7411 public void noteForegroundServicePausedLocked(long elapsedRealtimeMs) {
7412 if (mForegroundServiceTimer != null) {
7413 mForegroundServiceTimer.stopRunningLocked(elapsedRealtimeMs);
7414 }
7415 }
7416
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007417 public BatchTimer createVibratorOnTimerLocked() {
7418 if (mVibratorOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007419 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
7420 mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007421 }
7422 return mVibratorOnTimer;
7423 }
7424
7425 public void noteVibratorOnLocked(long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08007426 createVibratorOnTimerLocked().addDuration(mBsi, durationMillis);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007427 }
7428
7429 public void noteVibratorOffLocked() {
7430 if (mVibratorOnTimer != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007431 mVibratorOnTimer.abortLastDuration(mBsi);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007432 }
7433 }
7434
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007435 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007436 public long getWifiRunningTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007437 if (mWifiRunningTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007438 return 0;
7439 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007440 return mWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007441 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07007442
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007443 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007444 public long getFullWifiLockTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007445 if (mFullWifiLockTimer == null) {
7446 return 0;
7447 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007448 return mFullWifiLockTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07007449 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007450
7451 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007452 public long getWifiScanTime(long elapsedRealtimeUs, int which) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007453 if (mWifiScanTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007454 return 0;
7455 }
Bookatzaa4594a2017-03-24 12:39:56 -07007456 return mWifiScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07007457 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007458
7459 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07007460 public int getWifiScanCount(int which) {
7461 if (mWifiScanTimer == null) {
7462 return 0;
7463 }
Bookatzaa4594a2017-03-24 12:39:56 -07007464 return mWifiScanTimer.getCountLocked(which);
Bookatz867c0d72017-03-07 18:23:42 -08007465 }
7466
7467 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07007468 public Timer getWifiScanTimer() {
7469 return mWifiScanTimer;
7470 }
7471
7472 @Override
Bookatz867c0d72017-03-07 18:23:42 -08007473 public int getWifiScanBackgroundCount(int which) {
Bookatzaa4594a2017-03-24 12:39:56 -07007474 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007475 return 0;
7476 }
7477 return mWifiScanTimer.getSubTimer().getCountLocked(which);
7478 }
7479
7480 @Override
7481 public long getWifiScanActualTime(final long elapsedRealtimeUs) {
7482 if (mWifiScanTimer == null) {
7483 return 0;
7484 }
7485 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
Bookatzaa4594a2017-03-24 12:39:56 -07007486 return mWifiScanTimer.getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Bookatz867c0d72017-03-07 18:23:42 -08007487 }
7488
7489 @Override
7490 public long getWifiScanBackgroundTime(final long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07007491 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007492 return 0;
7493 }
7494 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
7495 return mWifiScanTimer.getSubTimer().getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Dianne Hackborn62793e42015-03-09 11:15:41 -07007496 }
7497
7498 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07007499 public Timer getWifiScanBackgroundTimer() {
7500 if (mWifiScanTimer == null) {
7501 return null;
7502 }
7503 return mWifiScanTimer.getSubTimer();
7504 }
7505
7506 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007507 public long getWifiBatchedScanTime(int csphBin, long elapsedRealtimeUs, int which) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007508 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
7509 if (mWifiBatchedScanTimer[csphBin] == null) {
7510 return 0;
7511 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007512 return mWifiBatchedScanTimer[csphBin].getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007513 }
7514
7515 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07007516 public int getWifiBatchedScanCount(int csphBin, int which) {
7517 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
7518 if (mWifiBatchedScanTimer[csphBin] == null) {
7519 return 0;
7520 }
7521 return mWifiBatchedScanTimer[csphBin].getCountLocked(which);
7522 }
7523
7524 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007525 public long getWifiMulticastTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007526 if (mWifiMulticastTimer == null) {
7527 return 0;
7528 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007529 return mWifiMulticastTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007530 }
7531
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007532 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007533 public Timer getAudioTurnedOnTimer() {
7534 return mAudioTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007535 }
7536
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007537 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007538 public Timer getVideoTurnedOnTimer() {
7539 return mVideoTurnedOnTimer;
7540 }
7541
7542 @Override
7543 public Timer getFlashlightTurnedOnTimer() {
7544 return mFlashlightTurnedOnTimer;
7545 }
7546
7547 @Override
7548 public Timer getCameraTurnedOnTimer() {
7549 return mCameraTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007550 }
7551
Dianne Hackborn617f8772009-03-31 15:04:46 -07007552 @Override
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007553 public Timer getForegroundActivityTimer() {
7554 return mForegroundActivityTimer;
7555 }
7556
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007557 @Override
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007558 public Timer getForegroundServiceTimer() {
7559 return mForegroundServiceTimer;
7560 }
7561
7562 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007563 public Timer getBluetoothScanTimer() {
Bookatzaa4594a2017-03-24 12:39:56 -07007564 return mBluetoothScanTimer;
Bookatz867c0d72017-03-07 18:23:42 -08007565 }
7566
7567 @Override
7568 public Timer getBluetoothScanBackgroundTimer() {
7569 if (mBluetoothScanTimer == null) {
7570 return null;
7571 }
7572 return mBluetoothScanTimer.getSubTimer();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007573 }
7574
Bookatz956f36bf2017-04-28 09:48:17 -07007575 @Override
Bookatzb1f04f32017-05-19 13:57:32 -07007576 public Timer getBluetoothUnoptimizedScanTimer() {
7577 return mBluetoothUnoptimizedScanTimer;
7578 }
7579
7580 @Override
7581 public Timer getBluetoothUnoptimizedScanBackgroundTimer() {
7582 if (mBluetoothUnoptimizedScanTimer == null) {
7583 return null;
7584 }
7585 return mBluetoothUnoptimizedScanTimer.getSubTimer();
7586 }
7587
7588 @Override
Bookatz956f36bf2017-04-28 09:48:17 -07007589 public Counter getBluetoothScanResultCounter() {
7590 return mBluetoothScanResultCounter;
7591 }
7592
Bookatzb1f04f32017-05-19 13:57:32 -07007593 @Override
7594 public Counter getBluetoothScanResultBgCounter() {
7595 return mBluetoothScanResultBgCounter;
7596 }
7597
Dianne Hackborn61659e52014-07-09 16:13:01 -07007598 void makeProcessState(int i, Parcel in) {
7599 if (i < 0 || i >= NUM_PROCESS_STATE) return;
7600
7601 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007602 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
7603 mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007604 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08007605 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
7606 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007607 }
7608 }
7609
7610 @Override
7611 public long getProcessStateTime(int state, long elapsedRealtimeUs, int which) {
7612 if (state < 0 || state >= NUM_PROCESS_STATE) return 0;
7613 if (mProcessStateTimer[state] == null) {
7614 return 0;
7615 }
7616 return mProcessStateTimer[state].getTotalTimeLocked(elapsedRealtimeUs, which);
7617 }
7618
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007619 @Override
Joe Onorato713fec82016-03-04 10:34:02 -08007620 public Timer getProcessStateTimer(int state) {
7621 if (state < 0 || state >= NUM_PROCESS_STATE) return null;
7622 return mProcessStateTimer[state];
7623 }
7624
7625 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007626 public Timer getVibratorOnTimer() {
7627 return mVibratorOnTimer;
7628 }
7629
7630 @Override
Dianne Hackborn617f8772009-03-31 15:04:46 -07007631 public void noteUserActivityLocked(int type) {
7632 if (mUserActivityCounters == null) {
7633 initUserActivityLocked();
7634 }
Jeff Browndf693de2012-07-27 12:03:38 -07007635 if (type >= 0 && type < NUM_USER_ACTIVITY_TYPES) {
7636 mUserActivityCounters[type].stepAtomic();
7637 } else {
7638 Slog.w(TAG, "Unknown user activity type " + type + " was specified.",
7639 new Throwable());
7640 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07007641 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007642
Dianne Hackborn617f8772009-03-31 15:04:46 -07007643 @Override
7644 public boolean hasUserActivity() {
7645 return mUserActivityCounters != null;
7646 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007647
Dianne Hackborn617f8772009-03-31 15:04:46 -07007648 @Override
7649 public int getUserActivityCount(int type, int which) {
7650 if (mUserActivityCounters == null) {
7651 return 0;
7652 }
Evan Millarc64edde2009-04-18 12:26:32 -07007653 return mUserActivityCounters[type].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007654 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007655
Robert Greenwalta029ea12013-09-25 16:38:12 -07007656 void makeWifiBatchedScanBin(int i, Parcel in) {
7657 if (i < 0 || i >= NUM_WIFI_BATCHED_SCAN_BINS) return;
7658
Joe Onoratoabded112016-02-08 16:49:39 -08007659 ArrayList<StopwatchTimer> collected = mBsi.mWifiBatchedScanTimers.get(i);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007660 if (collected == null) {
7661 collected = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08007662 mBsi.mWifiBatchedScanTimers.put(i, collected);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007663 }
7664 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007665 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
7666 collected, mBsi.mOnBatteryTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007667 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08007668 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
7669 collected, mBsi.mOnBatteryTimeBase, in);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007670 }
7671 }
7672
7673
Dianne Hackborn617f8772009-03-31 15:04:46 -07007674 void initUserActivityLocked() {
7675 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
7676 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007677 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007678 }
7679 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007680
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007681 void noteNetworkActivityLocked(int type, long deltaBytes, long deltaPackets) {
7682 if (mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007683 initNetworkActivityLocked();
7684 }
7685 if (type >= 0 && type < NUM_NETWORK_ACTIVITY_TYPES) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007686 mNetworkByteActivityCounters[type].addCountLocked(deltaBytes);
7687 mNetworkPacketActivityCounters[type].addCountLocked(deltaPackets);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007688 } else {
7689 Slog.w(TAG, "Unknown network activity type " + type + " was specified.",
7690 new Throwable());
7691 }
7692 }
7693
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007694 void noteMobileRadioActiveTimeLocked(long batteryUptime) {
7695 if (mNetworkByteActivityCounters == null) {
7696 initNetworkActivityLocked();
7697 }
7698 mMobileRadioActiveTime.addCountLocked(batteryUptime);
7699 mMobileRadioActiveCount.addCountLocked(1);
7700 }
7701
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007702 @Override
7703 public boolean hasNetworkActivity() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007704 return mNetworkByteActivityCounters != null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007705 }
7706
7707 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007708 public long getNetworkActivityBytes(int type, int which) {
7709 if (mNetworkByteActivityCounters != null && type >= 0
7710 && type < mNetworkByteActivityCounters.length) {
7711 return mNetworkByteActivityCounters[type].getCountLocked(which);
7712 } else {
7713 return 0;
7714 }
7715 }
7716
7717 @Override
7718 public long getNetworkActivityPackets(int type, int which) {
7719 if (mNetworkPacketActivityCounters != null && type >= 0
7720 && type < mNetworkPacketActivityCounters.length) {
7721 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007722 } else {
7723 return 0;
7724 }
7725 }
7726
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007727 @Override
7728 public long getMobileRadioActiveTime(int which) {
7729 return mMobileRadioActiveTime != null
7730 ? mMobileRadioActiveTime.getCountLocked(which) : 0;
7731 }
7732
7733 @Override
7734 public int getMobileRadioActiveCount(int which) {
7735 return mMobileRadioActiveCount != null
7736 ? (int)mMobileRadioActiveCount.getCountLocked(which) : 0;
7737 }
7738
Adam Lesinskie08af192015-03-25 16:42:59 -07007739 @Override
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007740 public long getUserCpuTimeUs(int which) {
7741 return mUserCpuTime.getCountLocked(which);
7742 }
7743
7744 @Override
7745 public long getSystemCpuTimeUs(int which) {
7746 return mSystemCpuTime.getCountLocked(which);
7747 }
7748
7749 @Override
Adam Lesinski6832f392015-09-05 18:05:40 -07007750 public long getTimeAtCpuSpeed(int cluster, int step, int which) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07007751 if (mCpuClusterSpeedTimesUs != null) {
7752 if (cluster >= 0 && cluster < mCpuClusterSpeedTimesUs.length) {
7753 final LongSamplingCounter[] cpuSpeedTimesUs = mCpuClusterSpeedTimesUs[cluster];
7754 if (cpuSpeedTimesUs != null) {
7755 if (step >= 0 && step < cpuSpeedTimesUs.length) {
7756 final LongSamplingCounter c = cpuSpeedTimesUs[step];
Adam Lesinski6832f392015-09-05 18:05:40 -07007757 if (c != null) {
7758 return c.getCountLocked(which);
7759 }
7760 }
7761 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007762 }
7763 }
7764 return 0;
7765 }
7766
Adam Lesinski5f056f62016-07-14 16:56:08 -07007767 public void noteMobileRadioApWakeupLocked() {
7768 if (mMobileRadioApWakeupCount == null) {
7769 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7770 }
7771 mMobileRadioApWakeupCount.addCountLocked(1);
7772 }
7773
7774 @Override
7775 public long getMobileRadioApWakeupCount(int which) {
7776 if (mMobileRadioApWakeupCount != null) {
7777 return mMobileRadioApWakeupCount.getCountLocked(which);
7778 }
7779 return 0;
7780 }
7781
7782 public void noteWifiRadioApWakeupLocked() {
7783 if (mWifiRadioApWakeupCount == null) {
7784 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7785 }
7786 mWifiRadioApWakeupCount.addCountLocked(1);
7787 }
7788
7789 @Override
7790 public long getWifiRadioApWakeupCount(int which) {
7791 if (mWifiRadioApWakeupCount != null) {
7792 return mWifiRadioApWakeupCount.getCountLocked(which);
7793 }
7794 return 0;
7795 }
7796
Amith Yamasani977e11f2018-02-16 11:29:54 -08007797 @Override
7798 public void getDeferredJobsCheckinLineLocked(StringBuilder sb, int which) {
7799 sb.setLength(0);
7800 final int deferredEventCount = mJobsDeferredEventCount.getCountLocked(which);
7801 if (deferredEventCount == 0) {
7802 return;
7803 }
7804 final int deferredCount = mJobsDeferredCount.getCountLocked(which);
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007805 final long totalLatency = mJobsFreshnessTimeMs.getCountLocked(which);
Amith Yamasani977e11f2018-02-16 11:29:54 -08007806 sb.append(deferredEventCount); sb.append(',');
7807 sb.append(deferredCount); sb.append(',');
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007808 sb.append(totalLatency);
Amith Yamasani977e11f2018-02-16 11:29:54 -08007809 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
7810 if (mJobsFreshnessBuckets[i] == null) {
7811 sb.append(",0");
7812 } else {
7813 sb.append(",");
7814 sb.append(mJobsFreshnessBuckets[i].getCountLocked(which));
7815 }
7816 }
7817 }
7818
7819 @Override
7820 public void getDeferredJobsLineLocked(StringBuilder sb, int which) {
7821 sb.setLength(0);
7822 final int deferredEventCount = mJobsDeferredEventCount.getCountLocked(which);
7823 if (deferredEventCount == 0) {
7824 return;
7825 }
7826 final int deferredCount = mJobsDeferredCount.getCountLocked(which);
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007827 final long totalLatency = mJobsFreshnessTimeMs.getCountLocked(which);
Amith Yamasani977e11f2018-02-16 11:29:54 -08007828 sb.append("times="); sb.append(deferredEventCount); sb.append(", ");
7829 sb.append("count="); sb.append(deferredCount); sb.append(", ");
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007830 sb.append("totalLatencyMs="); sb.append(totalLatency); sb.append(", ");
Amith Yamasani977e11f2018-02-16 11:29:54 -08007831 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
7832 sb.append("<"); sb.append(JOB_FRESHNESS_BUCKETS[i]); sb.append("ms=");
7833 if (mJobsFreshnessBuckets[i] == null) {
7834 sb.append("0");
7835 } else {
7836 sb.append(mJobsFreshnessBuckets[i].getCountLocked(which));
7837 }
7838 sb.append(" ");
7839 }
7840 }
7841
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007842 void initNetworkActivityLocked() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007843 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
7844 mNetworkPacketActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007845 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007846 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7847 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007848 }
Joe Onoratoabded112016-02-08 16:49:39 -08007849 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7850 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007851 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07007852
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007853 /**
7854 * Clear all stats for this uid. Returns true if the uid is completely
7855 * inactive so can be dropped.
7856 */
Adam Lesinski5f212c82017-03-13 12:25:13 -07007857 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
Bookatz993a0be2017-07-21 09:03:23 -07007858 public boolean reset(long uptime, long realtime) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007859 boolean active = false;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007860
Bookatz993a0be2017-07-21 09:03:23 -07007861 mOnBatteryBackgroundTimeBase.init(uptime, realtime);
7862 mOnBatteryScreenOffBackgroundTimeBase.init(uptime, realtime);
7863
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007864 if (mWifiRunningTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007865 active |= !mWifiRunningTimer.reset(false);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007866 active |= mWifiRunning;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007867 }
7868 if (mFullWifiLockTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007869 active |= !mFullWifiLockTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007870 active |= mFullWifiLockOut;
7871 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07007872 if (mWifiScanTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007873 active |= !mWifiScanTimer.reset(false);
Nick Pelly6ccaa542012-06-15 15:22:47 -07007874 active |= mWifiScanStarted;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007875 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07007876 if (mWifiBatchedScanTimer != null) {
7877 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
7878 if (mWifiBatchedScanTimer[i] != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007879 active |= !mWifiBatchedScanTimer[i].reset(false);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007880 }
7881 }
7882 active |= (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED);
7883 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007884 if (mWifiMulticastTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007885 active |= !mWifiMulticastTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007886 active |= mWifiMulticastEnabled;
7887 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007888
7889 active |= !resetTimerIfNotNull(mAudioTurnedOnTimer, false);
7890 active |= !resetTimerIfNotNull(mVideoTurnedOnTimer, false);
7891 active |= !resetTimerIfNotNull(mFlashlightTurnedOnTimer, false);
7892 active |= !resetTimerIfNotNull(mCameraTurnedOnTimer, false);
7893 active |= !resetTimerIfNotNull(mForegroundActivityTimer, false);
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007894 active |= !resetTimerIfNotNull(mForegroundServiceTimer, false);
Bookatzc8c44962017-05-11 12:12:54 -07007895 active |= !resetTimerIfNotNull(mAggregatedPartialWakelockTimer, false);
Adam Lesinski5f056f62016-07-14 16:56:08 -07007896 active |= !resetTimerIfNotNull(mBluetoothScanTimer, false);
Bookatzb1f04f32017-05-19 13:57:32 -07007897 active |= !resetTimerIfNotNull(mBluetoothUnoptimizedScanTimer, false);
Bookatz956f36bf2017-04-28 09:48:17 -07007898 if (mBluetoothScanResultCounter != null) {
7899 mBluetoothScanResultCounter.reset(false);
7900 }
Bookatzb1f04f32017-05-19 13:57:32 -07007901 if (mBluetoothScanResultBgCounter != null) {
7902 mBluetoothScanResultBgCounter.reset(false);
7903 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007904
Dianne Hackborn61659e52014-07-09 16:13:01 -07007905 if (mProcessStateTimer != null) {
7906 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
7907 if (mProcessStateTimer[i] != null) {
7908 active |= !mProcessStateTimer[i].reset(false);
7909 }
7910 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08007911 active |= (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007912 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007913 if (mVibratorOnTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007914 if (mVibratorOnTimer.reset(false)) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007915 mVibratorOnTimer.detach();
7916 mVibratorOnTimer = null;
7917 } else {
7918 active = true;
7919 }
7920 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007921
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007922 if (mUserActivityCounters != null) {
7923 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
7924 mUserActivityCounters[i].reset(false);
7925 }
7926 }
7927
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007928 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007929 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007930 mNetworkByteActivityCounters[i].reset(false);
7931 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007932 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007933 mMobileRadioActiveTime.reset(false);
7934 mMobileRadioActiveCount.reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007935 }
7936
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007937 if (mWifiControllerActivity != null) {
7938 mWifiControllerActivity.reset(false);
7939 }
Adam Lesinskie08af192015-03-25 16:42:59 -07007940
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07007941 if (mBluetoothControllerActivity != null) {
7942 mBluetoothControllerActivity.reset(false);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007943 }
7944
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07007945 if (mModemControllerActivity != null) {
7946 mModemControllerActivity.reset(false);
Adam Lesinskie08af192015-03-25 16:42:59 -07007947 }
7948
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007949 mUserCpuTime.reset(false);
7950 mSystemCpuTime.reset(false);
Adam Lesinski6832f392015-09-05 18:05:40 -07007951
Sudheer Shankaaf857412017-07-21 00:14:24 -07007952 if (mCpuClusterSpeedTimesUs != null) {
7953 for (LongSamplingCounter[] speeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07007954 if (speeds != null) {
7955 for (LongSamplingCounter speed : speeds) {
7956 if (speed != null) {
7957 speed.reset(false);
7958 }
7959 }
7960 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007961 }
7962 }
7963
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007964 if (mCpuFreqTimeMs != null) {
7965 mCpuFreqTimeMs.reset(false);
7966 }
7967 if (mScreenOffCpuFreqTimeMs != null) {
7968 mScreenOffCpuFreqTimeMs.reset(false);
7969 }
7970
Mike Ma3d422c32017-10-25 11:08:57 -07007971 mCpuActiveTimeMs.reset(false);
7972 mCpuClusterTimesMs.reset(false);
7973
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007974 if (mProcStateTimeMs != null) {
7975 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
7976 if (counters != null) {
7977 counters.reset(false);
7978 }
7979 }
7980 }
7981 if (mProcStateScreenOffTimeMs != null) {
7982 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
7983 if (counters != null) {
7984 counters.reset(false);
7985 }
7986 }
7987 }
7988
Adam Lesinski5f056f62016-07-14 16:56:08 -07007989 resetLongCounterIfNotNull(mMobileRadioApWakeupCount, false);
7990 resetLongCounterIfNotNull(mWifiRadioApWakeupCount, false);
7991
Dianne Hackbornd953c532014-08-16 18:17:38 -07007992 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
7993 for (int iw=wakeStats.size()-1; iw>=0; iw--) {
7994 Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007995 if (wl.reset()) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007996 wakeStats.removeAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007997 } else {
7998 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007999 }
8000 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07008001 mWakelockStats.cleanup();
Bookatz2bffb5b2017-04-13 11:59:33 -07008002 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008003 for (int is=syncStats.size()-1; is>=0; is--) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008004 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008005 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008006 syncStats.removeAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008007 timer.detach();
8008 } else {
8009 active = true;
8010 }
8011 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07008012 mSyncStats.cleanup();
Bookatzaa4594a2017-03-24 12:39:56 -07008013 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008014 for (int ij=jobStats.size()-1; ij>=0; ij--) {
Bookatzaa4594a2017-03-24 12:39:56 -07008015 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008016 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008017 jobStats.removeAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008018 timer.detach();
8019 } else {
8020 active = true;
8021 }
8022 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07008023 mJobStats.cleanup();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008024 mJobCompletions.clear();
Amith Yamasani977e11f2018-02-16 11:29:54 -08008025
8026 mJobsDeferredEventCount.reset(false);
8027 mJobsDeferredCount.reset(false);
8028 mJobsFreshnessTimeMs.reset(false);
8029 for (int ij = 0; ij < JOB_FRESHNESS_BUCKETS.length; ij++) {
8030 if (mJobsFreshnessBuckets[ij] != null) {
8031 mJobsFreshnessBuckets[ij].reset(false);
8032 }
8033 }
8034
Dianne Hackborn61659e52014-07-09 16:13:01 -07008035 for (int ise=mSensorStats.size()-1; ise>=0; ise--) {
8036 Sensor s = mSensorStats.valueAt(ise);
8037 if (s.reset()) {
8038 mSensorStats.removeAt(ise);
8039 } else {
8040 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008041 }
8042 }
Amith Yamasani977e11f2018-02-16 11:29:54 -08008043
Dianne Hackborn61659e52014-07-09 16:13:01 -07008044 for (int ip=mProcessStats.size()-1; ip>=0; ip--) {
8045 Proc proc = mProcessStats.valueAt(ip);
Dianne Hackborna8d10942015-11-19 17:55:19 -08008046 proc.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008047 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08008048 mProcessStats.clear();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008049 if (mPids.size() > 0) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008050 for (int i=mPids.size()-1; i>=0; i--) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008051 Pid pid = mPids.valueAt(i);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008052 if (pid.mWakeNesting > 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008053 active = true;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008054 } else {
8055 mPids.removeAt(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008056 }
8057 }
8058 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008059 if (mPackageStats.size() > 0) {
8060 Iterator<Map.Entry<String, Pkg>> it = mPackageStats.entrySet().iterator();
8061 while (it.hasNext()) {
8062 Map.Entry<String, Pkg> pkgEntry = it.next();
8063 Pkg p = pkgEntry.getValue();
8064 p.detach();
8065 if (p.mServiceStats.size() > 0) {
8066 Iterator<Map.Entry<String, Pkg.Serv>> it2
8067 = p.mServiceStats.entrySet().iterator();
8068 while (it2.hasNext()) {
8069 Map.Entry<String, Pkg.Serv> servEntry = it2.next();
8070 servEntry.getValue().detach();
8071 }
8072 }
8073 }
8074 mPackageStats.clear();
8075 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008076
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08008077 mLastStepUserTime = mLastStepSystemTime = 0;
8078 mCurStepUserTime = mCurStepSystemTime = 0;
8079
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008080 if (!active) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008081 if (mWifiRunningTimer != null) {
8082 mWifiRunningTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008083 }
8084 if (mFullWifiLockTimer != null) {
8085 mFullWifiLockTimer.detach();
8086 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008087 if (mWifiScanTimer != null) {
8088 mWifiScanTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008089 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008090 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8091 if (mWifiBatchedScanTimer[i] != null) {
8092 mWifiBatchedScanTimer[i].detach();
8093 }
8094 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008095 if (mWifiMulticastTimer != null) {
8096 mWifiMulticastTimer.detach();
8097 }
8098 if (mAudioTurnedOnTimer != null) {
8099 mAudioTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008100 mAudioTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008101 }
8102 if (mVideoTurnedOnTimer != null) {
8103 mVideoTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008104 mVideoTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008105 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008106 if (mFlashlightTurnedOnTimer != null) {
8107 mFlashlightTurnedOnTimer.detach();
8108 mFlashlightTurnedOnTimer = null;
8109 }
8110 if (mCameraTurnedOnTimer != null) {
8111 mCameraTurnedOnTimer.detach();
8112 mCameraTurnedOnTimer = null;
8113 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008114 if (mForegroundActivityTimer != null) {
8115 mForegroundActivityTimer.detach();
8116 mForegroundActivityTimer = null;
8117 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008118 if (mForegroundServiceTimer != null) {
8119 mForegroundServiceTimer.detach();
8120 mForegroundServiceTimer = null;
8121 }
Bookatzc8c44962017-05-11 12:12:54 -07008122 if (mAggregatedPartialWakelockTimer != null) {
8123 mAggregatedPartialWakelockTimer.detach();
8124 mAggregatedPartialWakelockTimer = null;
8125 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008126 if (mBluetoothScanTimer != null) {
8127 mBluetoothScanTimer.detach();
8128 mBluetoothScanTimer = null;
8129 }
Bookatzb1f04f32017-05-19 13:57:32 -07008130 if (mBluetoothUnoptimizedScanTimer != null) {
8131 mBluetoothUnoptimizedScanTimer.detach();
8132 mBluetoothUnoptimizedScanTimer = null;
8133 }
Bookatz956f36bf2017-04-28 09:48:17 -07008134 if (mBluetoothScanResultCounter != null) {
8135 mBluetoothScanResultCounter.detach();
8136 mBluetoothScanResultCounter = null;
8137 }
Bookatzb1f04f32017-05-19 13:57:32 -07008138 if (mBluetoothScanResultBgCounter != null) {
8139 mBluetoothScanResultBgCounter.detach();
8140 mBluetoothScanResultBgCounter = null;
8141 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008142 if (mUserActivityCounters != null) {
8143 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
8144 mUserActivityCounters[i].detach();
8145 }
8146 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008147 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008148 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008149 mNetworkByteActivityCounters[i].detach();
8150 mNetworkPacketActivityCounters[i].detach();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008151 }
8152 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008153
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008154 if (mWifiControllerActivity != null) {
8155 mWifiControllerActivity.detach();
Adam Lesinskie08af192015-03-25 16:42:59 -07008156 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008157
8158 if (mBluetoothControllerActivity != null) {
8159 mBluetoothControllerActivity.detach();
8160 }
8161
8162 if (mModemControllerActivity != null) {
8163 mModemControllerActivity.detach();
8164 }
8165
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008166 mPids.clear();
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008167
8168 mUserCpuTime.detach();
8169 mSystemCpuTime.detach();
Adam Lesinski6832f392015-09-05 18:05:40 -07008170
Sudheer Shankaaf857412017-07-21 00:14:24 -07008171 if (mCpuClusterSpeedTimesUs != null) {
8172 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008173 if (cpuSpeeds != null) {
8174 for (LongSamplingCounter c : cpuSpeeds) {
8175 if (c != null) {
8176 c.detach();
8177 }
8178 }
8179 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008180 }
8181 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008182
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008183 if (mCpuFreqTimeMs != null) {
8184 mCpuFreqTimeMs.detach();
8185 }
8186 if (mScreenOffCpuFreqTimeMs != null) {
8187 mScreenOffCpuFreqTimeMs.detach();
8188 }
Mike Ma3d422c32017-10-25 11:08:57 -07008189 mCpuActiveTimeMs.detach();
8190 mCpuClusterTimesMs.detach();
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008191
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008192 if (mProcStateTimeMs != null) {
8193 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8194 if (counters != null) {
8195 counters.detach();
8196 }
8197 }
8198 }
8199 if (mProcStateScreenOffTimeMs != null) {
8200 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8201 if (counters != null) {
8202 counters.detach();
8203 }
8204 }
8205 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008206 detachLongCounterIfNotNull(mMobileRadioApWakeupCount);
8207 detachLongCounterIfNotNull(mWifiRadioApWakeupCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008208 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008209
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008210 return !active;
8211 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008212
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008213 void writeJobCompletionsToParcelLocked(Parcel out) {
8214 int NJC = mJobCompletions.size();
8215 out.writeInt(NJC);
8216 for (int ijc=0; ijc<NJC; ijc++) {
8217 out.writeString(mJobCompletions.keyAt(ijc));
8218 SparseIntArray types = mJobCompletions.valueAt(ijc);
8219 int NT = types.size();
8220 out.writeInt(NT);
8221 for (int it=0; it<NT; it++) {
8222 out.writeInt(types.keyAt(it));
8223 out.writeInt(types.valueAt(it));
8224 }
8225 }
8226 }
8227
Bookatz867c0d72017-03-07 18:23:42 -08008228 void writeToParcelLocked(Parcel out, long uptimeUs, long elapsedRealtimeUs) {
8229 mOnBatteryBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatzc8c44962017-05-11 12:12:54 -07008230 mOnBatteryScreenOffBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08008231
Dianne Hackbornd953c532014-08-16 18:17:38 -07008232 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
8233 int NW = wakeStats.size();
Dianne Hackborn61659e52014-07-09 16:13:01 -07008234 out.writeInt(NW);
8235 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008236 out.writeString(wakeStats.keyAt(iw));
8237 Uid.Wakelock wakelock = wakeStats.valueAt(iw);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008238 wakelock.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008239 }
8240
Bookatz2bffb5b2017-04-13 11:59:33 -07008241 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008242 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008243 out.writeInt(NS);
8244 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008245 out.writeString(syncStats.keyAt(is));
Bookatz2bffb5b2017-04-13 11:59:33 -07008246 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008247 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
8248 }
8249
Bookatzaa4594a2017-03-24 12:39:56 -07008250 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008251 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008252 out.writeInt(NJ);
8253 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008254 out.writeString(jobStats.keyAt(ij));
Bookatzaa4594a2017-03-24 12:39:56 -07008255 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008256 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
8257 }
8258
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008259 writeJobCompletionsToParcelLocked(out);
8260
Amith Yamasani977e11f2018-02-16 11:29:54 -08008261 mJobsDeferredEventCount.writeToParcel(out);
8262 mJobsDeferredCount.writeToParcel(out);
8263 mJobsFreshnessTimeMs.writeToParcel(out);
8264 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
8265 Counter.writeCounterToParcel(out, mJobsFreshnessBuckets[i]);
8266 }
8267
Dianne Hackborn61659e52014-07-09 16:13:01 -07008268 int NSE = mSensorStats.size();
8269 out.writeInt(NSE);
8270 for (int ise=0; ise<NSE; ise++) {
8271 out.writeInt(mSensorStats.keyAt(ise));
8272 Uid.Sensor sensor = mSensorStats.valueAt(ise);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008273 sensor.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008274 }
8275
Dianne Hackborn61659e52014-07-09 16:13:01 -07008276 int NP = mProcessStats.size();
8277 out.writeInt(NP);
8278 for (int ip=0; ip<NP; ip++) {
8279 out.writeString(mProcessStats.keyAt(ip));
8280 Uid.Proc proc = mProcessStats.valueAt(ip);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008281 proc.writeToParcelLocked(out);
8282 }
8283
8284 out.writeInt(mPackageStats.size());
8285 for (Map.Entry<String, Uid.Pkg> pkgEntry : mPackageStats.entrySet()) {
8286 out.writeString(pkgEntry.getKey());
8287 Uid.Pkg pkg = pkgEntry.getValue();
8288 pkg.writeToParcelLocked(out);
8289 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008290
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008291 if (mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008292 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008293 mWifiRunningTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008294 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008295 out.writeInt(0);
8296 }
8297 if (mFullWifiLockTimer != null) {
8298 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008299 mFullWifiLockTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008300 } else {
8301 out.writeInt(0);
8302 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008303 if (mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008304 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008305 mWifiScanTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008306 } else {
8307 out.writeInt(0);
8308 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008309 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8310 if (mWifiBatchedScanTimer[i] != null) {
8311 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008312 mWifiBatchedScanTimer[i].writeToParcel(out, elapsedRealtimeUs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07008313 } else {
8314 out.writeInt(0);
8315 }
8316 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008317 if (mWifiMulticastTimer != null) {
8318 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008319 mWifiMulticastTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008320 } else {
8321 out.writeInt(0);
8322 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008323
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008324 if (mAudioTurnedOnTimer != null) {
8325 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008326 mAudioTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008327 } else {
8328 out.writeInt(0);
8329 }
8330 if (mVideoTurnedOnTimer != null) {
8331 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008332 mVideoTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008333 } else {
8334 out.writeInt(0);
8335 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008336 if (mFlashlightTurnedOnTimer != null) {
8337 out.writeInt(1);
8338 mFlashlightTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
8339 } else {
8340 out.writeInt(0);
8341 }
8342 if (mCameraTurnedOnTimer != null) {
8343 out.writeInt(1);
8344 mCameraTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
8345 } else {
8346 out.writeInt(0);
8347 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008348 if (mForegroundActivityTimer != null) {
8349 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008350 mForegroundActivityTimer.writeToParcel(out, elapsedRealtimeUs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008351 } else {
8352 out.writeInt(0);
8353 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008354 if (mForegroundServiceTimer != null) {
8355 out.writeInt(1);
8356 mForegroundServiceTimer.writeToParcel(out, elapsedRealtimeUs);
8357 } else {
8358 out.writeInt(0);
8359 }
Bookatzc8c44962017-05-11 12:12:54 -07008360 if (mAggregatedPartialWakelockTimer != null) {
8361 out.writeInt(1);
8362 mAggregatedPartialWakelockTimer.writeToParcel(out, elapsedRealtimeUs);
8363 } else {
8364 out.writeInt(0);
8365 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008366 if (mBluetoothScanTimer != null) {
8367 out.writeInt(1);
8368 mBluetoothScanTimer.writeToParcel(out, elapsedRealtimeUs);
8369 } else {
8370 out.writeInt(0);
8371 }
Bookatzb1f04f32017-05-19 13:57:32 -07008372 if (mBluetoothUnoptimizedScanTimer != null) {
8373 out.writeInt(1);
8374 mBluetoothUnoptimizedScanTimer.writeToParcel(out, elapsedRealtimeUs);
8375 } else {
8376 out.writeInt(0);
8377 }
Bookatz956f36bf2017-04-28 09:48:17 -07008378 if (mBluetoothScanResultCounter != null) {
8379 out.writeInt(1);
8380 mBluetoothScanResultCounter.writeToParcel(out);
8381 } else {
8382 out.writeInt(0);
8383 }
Bookatzb1f04f32017-05-19 13:57:32 -07008384 if (mBluetoothScanResultBgCounter != null) {
8385 out.writeInt(1);
8386 mBluetoothScanResultBgCounter.writeToParcel(out);
8387 } else {
8388 out.writeInt(0);
8389 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07008390 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8391 if (mProcessStateTimer[i] != null) {
8392 out.writeInt(1);
8393 mProcessStateTimer[i].writeToParcel(out, elapsedRealtimeUs);
8394 } else {
8395 out.writeInt(0);
8396 }
8397 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008398 if (mVibratorOnTimer != null) {
8399 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008400 mVibratorOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008401 } else {
8402 out.writeInt(0);
8403 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008404 if (mUserActivityCounters != null) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07008405 out.writeInt(1);
8406 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
8407 mUserActivityCounters[i].writeToParcel(out);
8408 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008409 } else {
8410 out.writeInt(0);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008411 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008412 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008413 out.writeInt(1);
8414 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008415 mNetworkByteActivityCounters[i].writeToParcel(out);
8416 mNetworkPacketActivityCounters[i].writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008417 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08008418 mMobileRadioActiveTime.writeToParcel(out);
8419 mMobileRadioActiveCount.writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008420 } else {
8421 out.writeInt(0);
8422 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008423
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008424 if (mWifiControllerActivity != null) {
8425 out.writeInt(1);
8426 mWifiControllerActivity.writeToParcel(out, 0);
8427 } else {
8428 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07008429 }
8430
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008431 if (mBluetoothControllerActivity != null) {
8432 out.writeInt(1);
8433 mBluetoothControllerActivity.writeToParcel(out, 0);
8434 } else {
8435 out.writeInt(0);
8436 }
8437
8438 if (mModemControllerActivity != null) {
8439 out.writeInt(1);
8440 mModemControllerActivity.writeToParcel(out, 0);
8441 } else {
8442 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07008443 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008444
8445 mUserCpuTime.writeToParcel(out);
8446 mSystemCpuTime.writeToParcel(out);
8447
Sudheer Shankaaf857412017-07-21 00:14:24 -07008448 if (mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008449 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -07008450 out.writeInt(mCpuClusterSpeedTimesUs.length);
8451 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008452 if (cpuSpeeds != null) {
8453 out.writeInt(1);
8454 out.writeInt(cpuSpeeds.length);
8455 for (LongSamplingCounter c : cpuSpeeds) {
8456 if (c != null) {
8457 out.writeInt(1);
8458 c.writeToParcel(out);
8459 } else {
8460 out.writeInt(0);
8461 }
8462 }
8463 } else {
8464 out.writeInt(0);
8465 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008466 }
Adam Lesinski6832f392015-09-05 18:05:40 -07008467 } else {
8468 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008469 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008470
Sudheer Shanka59f5c002017-05-15 10:57:15 -07008471 LongSamplingCounterArray.writeToParcel(out, mCpuFreqTimeMs);
8472 LongSamplingCounterArray.writeToParcel(out, mScreenOffCpuFreqTimeMs);
Mike Ma3d422c32017-10-25 11:08:57 -07008473
8474 mCpuActiveTimeMs.writeToParcel(out);
8475 mCpuClusterTimesMs.writeToParcel(out);
8476
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008477 if (mProcStateTimeMs != null) {
8478 out.writeInt(mProcStateTimeMs.length);
8479 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8480 LongSamplingCounterArray.writeToParcel(out, counters);
8481 }
8482 } else {
8483 out.writeInt(0);
8484 }
8485 if (mProcStateScreenOffTimeMs != null) {
8486 out.writeInt(mProcStateScreenOffTimeMs.length);
8487 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8488 LongSamplingCounterArray.writeToParcel(out, counters);
8489 }
8490 } else {
8491 out.writeInt(0);
8492 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008493
Adam Lesinski5f056f62016-07-14 16:56:08 -07008494 if (mMobileRadioApWakeupCount != null) {
8495 out.writeInt(1);
8496 mMobileRadioApWakeupCount.writeToParcel(out);
8497 } else {
8498 out.writeInt(0);
8499 }
8500
8501 if (mWifiRadioApWakeupCount != null) {
8502 out.writeInt(1);
8503 mWifiRadioApWakeupCount.writeToParcel(out);
8504 } else {
8505 out.writeInt(0);
8506 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008507 }
8508
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008509 void readJobCompletionsFromParcelLocked(Parcel in) {
8510 int numJobCompletions = in.readInt();
8511 mJobCompletions.clear();
8512 for (int j = 0; j < numJobCompletions; j++) {
8513 String jobName = in.readString();
8514 int numTypes = in.readInt();
8515 if (numTypes > 0) {
8516 SparseIntArray types = new SparseIntArray();
8517 for (int k = 0; k < numTypes; k++) {
8518 int type = in.readInt();
8519 int count = in.readInt();
8520 types.put(type, count);
8521 }
8522 mJobCompletions.put(jobName, types);
8523 }
8524 }
8525 }
8526
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008527 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase, Parcel in) {
Bookatz867c0d72017-03-07 18:23:42 -08008528 mOnBatteryBackgroundTimeBase.readFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -07008529 mOnBatteryScreenOffBackgroundTimeBase.readFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -08008530
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008531 int numWakelocks = in.readInt();
8532 mWakelockStats.clear();
8533 for (int j = 0; j < numWakelocks; j++) {
8534 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008535 Uid.Wakelock wakelock = new Wakelock(mBsi, this);
Bookatz5b5ec322017-05-26 09:40:38 -07008536 wakelock.readFromParcelLocked(
8537 timeBase, screenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase, in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07008538 mWakelockStats.add(wakelockName, wakelock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008539 }
8540
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008541 int numSyncs = in.readInt();
8542 mSyncStats.clear();
8543 for (int j = 0; j < numSyncs; j++) {
8544 String syncName = in.readString();
8545 if (in.readInt() != 0) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008546 mSyncStats.add(syncName, new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
8547 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008548 }
8549 }
8550
8551 int numJobs = in.readInt();
8552 mJobStats.clear();
8553 for (int j = 0; j < numJobs; j++) {
8554 String jobName = in.readString();
8555 if (in.readInt() != 0) {
Bookatzaa4594a2017-03-24 12:39:56 -07008556 mJobStats.add(jobName, new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
8557 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008558 }
8559 }
8560
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008561 readJobCompletionsFromParcelLocked(in);
8562
Amith Yamasani977e11f2018-02-16 11:29:54 -08008563 mJobsDeferredEventCount = new Counter(mBsi.mOnBatteryTimeBase, in);
8564 mJobsDeferredCount = new Counter(mBsi.mOnBatteryTimeBase, in);
8565 mJobsFreshnessTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8566 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
8567 mJobsFreshnessBuckets[i] = Counter.readCounterFromParcel(mBsi.mOnBatteryTimeBase,
8568 in);
8569 }
8570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008571 int numSensors = in.readInt();
8572 mSensorStats.clear();
8573 for (int k = 0; k < numSensors; k++) {
8574 int sensorNumber = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008575 Uid.Sensor sensor = new Sensor(mBsi, this, sensorNumber);
Bookatz867c0d72017-03-07 18:23:42 -08008576 sensor.readFromParcelLocked(mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
8577 in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008578 mSensorStats.put(sensorNumber, sensor);
8579 }
8580
8581 int numProcs = in.readInt();
8582 mProcessStats.clear();
8583 for (int k = 0; k < numProcs; k++) {
8584 String processName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008585 Uid.Proc proc = new Proc(mBsi, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008586 proc.readFromParcelLocked(in);
8587 mProcessStats.put(processName, proc);
8588 }
8589
8590 int numPkgs = in.readInt();
8591 mPackageStats.clear();
8592 for (int l = 0; l < numPkgs; l++) {
8593 String packageName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008594 Uid.Pkg pkg = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008595 pkg.readFromParcelLocked(in);
8596 mPackageStats.put(packageName, pkg);
8597 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008598
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008599 mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008600 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008601 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
8602 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008603 } else {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008604 mWifiRunningTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008605 }
8606 mFullWifiLockOut = false;
8607 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008608 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
8609 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008610 } else {
8611 mFullWifiLockTimer = null;
8612 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008613 mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008614 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08008615 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
8616 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
8617 in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008618 } else {
Nick Pelly6ccaa542012-06-15 15:22:47 -07008619 mWifiScanTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008620 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008621 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
8622 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8623 if (in.readInt() != 0) {
8624 makeWifiBatchedScanBin(i, in);
8625 } else {
8626 mWifiBatchedScanTimer[i] = null;
8627 }
8628 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008629 mWifiMulticastEnabled = false;
8630 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008631 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_MULTICAST_ENABLED,
8632 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008633 } else {
8634 mWifiMulticastTimer = null;
8635 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008636 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008637 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
8638 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008639 } else {
8640 mAudioTurnedOnTimer = null;
8641 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008642 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008643 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
8644 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008645 } else {
8646 mVideoTurnedOnTimer = null;
8647 }
8648 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008649 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8650 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008651 } else {
8652 mFlashlightTurnedOnTimer = null;
8653 }
8654 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008655 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
8656 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008657 } else {
8658 mCameraTurnedOnTimer = null;
8659 }
8660 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008661 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8662 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008663 } else {
8664 mForegroundActivityTimer = null;
8665 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008666 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008667 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8668 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase, in);
8669 } else {
8670 mForegroundServiceTimer = null;
8671 }
8672 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -07008673 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
8674 AGGREGATED_WAKE_TYPE_PARTIAL, null,
8675 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase,
8676 in);
8677 } else {
8678 mAggregatedPartialWakelockTimer = null;
8679 }
8680 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08008681 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
8682 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
8683 mOnBatteryBackgroundTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008684 } else {
8685 mBluetoothScanTimer = null;
8686 }
Bookatz956f36bf2017-04-28 09:48:17 -07008687 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -07008688 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
8689 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
8690 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in);
8691 } else {
8692 mBluetoothUnoptimizedScanTimer = null;
8693 }
8694 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -07008695 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase, in);
8696 } else {
8697 mBluetoothScanResultCounter = null;
8698 }
Bookatzb1f04f32017-05-19 13:57:32 -07008699 if (in.readInt() != 0) {
8700 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase, in);
8701 } else {
8702 mBluetoothScanResultBgCounter = null;
8703 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08008704 mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07008705 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8706 if (in.readInt() != 0) {
8707 makeProcessState(i, in);
8708 } else {
8709 mProcessStateTimer[i] = null;
8710 }
8711 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008712 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008713 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
8714 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008715 } else {
8716 mVibratorOnTimer = null;
8717 }
8718 if (in.readInt() != 0) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07008719 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
8720 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08008721 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008722 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008723 } else {
8724 mUserActivityCounters = null;
Dianne Hackborn617f8772009-03-31 15:04:46 -07008725 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008726 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008727 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
8728 mNetworkPacketActivityCounters
8729 = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008730 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008731 mNetworkByteActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08008732 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008733 mNetworkPacketActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08008734 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008735 }
Joe Onoratoabded112016-02-08 16:49:39 -08008736 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8737 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008738 } else {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008739 mNetworkByteActivityCounters = null;
8740 mNetworkPacketActivityCounters = null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008741 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008742
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008743 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008744 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008745 NUM_WIFI_TX_LEVELS, in);
8746 } else {
8747 mWifiControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07008748 }
8749
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008750 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008751 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008752 NUM_BT_TX_LEVELS, in);
8753 } else {
8754 mBluetoothControllerActivity = null;
8755 }
8756
8757 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008758 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008759 ModemActivityInfo.TX_POWER_LEVELS, in);
8760 } else {
8761 mModemControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07008762 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008763
Joe Onoratoabded112016-02-08 16:49:39 -08008764 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8765 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008766
Adam Lesinski6832f392015-09-05 18:05:40 -07008767 if (in.readInt() != 0) {
8768 int numCpuClusters = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008769 if (mBsi.mPowerProfile != null && mBsi.mPowerProfile.getNumCpuClusters() != numCpuClusters) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008770 throw new ParcelFormatException("Incompatible number of cpu clusters");
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008771 }
Adam Lesinski6832f392015-09-05 18:05:40 -07008772
Sudheer Shankaaf857412017-07-21 00:14:24 -07008773 mCpuClusterSpeedTimesUs = new LongSamplingCounter[numCpuClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -07008774 for (int cluster = 0; cluster < numCpuClusters; cluster++) {
8775 if (in.readInt() != 0) {
8776 int numSpeeds = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008777 if (mBsi.mPowerProfile != null &&
8778 mBsi.mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != numSpeeds) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008779 throw new ParcelFormatException("Incompatible number of cpu speeds");
8780 }
8781
8782 final LongSamplingCounter[] cpuSpeeds = new LongSamplingCounter[numSpeeds];
Sudheer Shankaaf857412017-07-21 00:14:24 -07008783 mCpuClusterSpeedTimesUs[cluster] = cpuSpeeds;
Adam Lesinski6832f392015-09-05 18:05:40 -07008784 for (int speed = 0; speed < numSpeeds; speed++) {
8785 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008786 cpuSpeeds[speed] = new LongSamplingCounter(
8787 mBsi.mOnBatteryTimeBase, in);
Adam Lesinski6832f392015-09-05 18:05:40 -07008788 }
8789 }
Adam Lesinskia57a5402015-09-28 10:21:33 -07008790 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008791 mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -07008792 }
8793 }
8794 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008795 mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008796 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008797
Sudheer Shanka59f5c002017-05-15 10:57:15 -07008798 mCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(in, mBsi.mOnBatteryTimeBase);
8799 mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(
8800 in, mBsi.mOnBatteryScreenOffTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008801
Mike Ma3d422c32017-10-25 11:08:57 -07008802 mCpuActiveTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8803 mCpuClusterTimesMs = new LongSamplingCounterArray(mBsi.mOnBatteryTimeBase, in);
8804
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008805 int length = in.readInt();
8806 if (length == NUM_PROCESS_STATE) {
8807 mProcStateTimeMs = new LongSamplingCounterArray[length];
8808 for (int procState = 0; procState < length; ++procState) {
8809 mProcStateTimeMs[procState] = LongSamplingCounterArray.readFromParcel(
8810 in, mBsi.mOnBatteryTimeBase);
8811 }
8812 } else {
8813 mProcStateTimeMs = null;
8814 }
8815 length = in.readInt();
8816 if (length == NUM_PROCESS_STATE) {
8817 mProcStateScreenOffTimeMs = new LongSamplingCounterArray[length];
8818 for (int procState = 0; procState < length; ++procState) {
8819 mProcStateScreenOffTimeMs[procState] = LongSamplingCounterArray.readFromParcel(
8820 in, mBsi.mOnBatteryScreenOffTimeBase);
8821 }
8822 } else {
8823 mProcStateScreenOffTimeMs = null;
8824 }
8825
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008826 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07008827 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8828 } else {
8829 mMobileRadioApWakeupCount = null;
8830 }
8831
8832 if (in.readInt() != 0) {
8833 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8834 } else {
8835 mWifiRadioApWakeupCount = null;
8836 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008837 }
8838
Amith Yamasani977e11f2018-02-16 11:29:54 -08008839 public void noteJobsDeferredLocked(int numDeferred, long sinceLast) {
8840 mJobsDeferredEventCount.addAtomic(1);
8841 mJobsDeferredCount.addAtomic(numDeferred);
8842 if (sinceLast != 0) {
8843 // Add the total time, which can be divided by the event count to get an average
8844 mJobsFreshnessTimeMs.addCountLocked(sinceLast);
8845 // Also keep track of how many times there were in these different buckets.
8846 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
8847 if (sinceLast < JOB_FRESHNESS_BUCKETS[i]) {
8848 if (mJobsFreshnessBuckets[i] == null) {
8849 mJobsFreshnessBuckets[i] = new Counter(
8850 mBsi.mOnBatteryTimeBase);
8851 }
8852 mJobsFreshnessBuckets[i].addAtomic(1);
8853 break;
8854 }
8855 }
8856 }
8857 }
8858
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008859 /**
8860 * The statistics associated with a particular wake lock.
8861 */
Joe Onoratoabded112016-02-08 16:49:39 -08008862 public static class Wakelock extends BatteryStats.Uid.Wakelock {
8863 /**
8864 * BatteryStatsImpl that we are associated with.
8865 */
8866 protected BatteryStatsImpl mBsi;
8867
8868 /**
8869 * BatteryStatsImpl that we are associated with.
8870 */
8871 protected Uid mUid;
8872
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008873 /**
8874 * How long (in ms) this uid has been keeping the device partially awake.
Bookatz5b5ec322017-05-26 09:40:38 -07008875 * 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 -08008876 */
Bookatz5b5ec322017-05-26 09:40:38 -07008877 DualTimer mTimerPartial;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008878
8879 /**
8880 * How long (in ms) this uid has been keeping the device fully awake.
8881 */
Evan Millarc64edde2009-04-18 12:26:32 -07008882 StopwatchTimer mTimerFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008883
8884 /**
8885 * How long (in ms) this uid has had a window keeping the device awake.
8886 */
Evan Millarc64edde2009-04-18 12:26:32 -07008887 StopwatchTimer mTimerWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008888
8889 /**
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008890 * How long (in ms) this uid has had a draw wake lock.
Adam Lesinski9425fe22015-06-19 12:02:13 -07008891 */
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008892 StopwatchTimer mTimerDraw;
Adam Lesinski9425fe22015-06-19 12:02:13 -07008893
Joe Onoratoabded112016-02-08 16:49:39 -08008894 public Wakelock(BatteryStatsImpl bsi, Uid uid) {
8895 mBsi = bsi;
8896 mUid = uid;
8897 }
8898
Adam Lesinski9425fe22015-06-19 12:02:13 -07008899 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008900 * Reads a possibly null Timer from a Parcel. The timer is associated with the
8901 * proper timer pool from the given BatteryStatsImpl object.
8902 *
8903 * @param in the Parcel to be read from.
8904 * return a new Timer, or null.
8905 */
Joe Onorato92fd23f2016-07-25 11:18:42 -07008906 private StopwatchTimer readStopwatchTimerFromParcel(int type,
8907 ArrayList<StopwatchTimer> pool, TimeBase timeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008908 if (in.readInt() == 0) {
8909 return null;
8910 }
8911
Joe Onoratoabded112016-02-08 16:49:39 -08008912 return new StopwatchTimer(mBsi.mClocks, mUid, type, pool, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008913 }
8914
Joe Onorato92fd23f2016-07-25 11:18:42 -07008915 /**
8916 * Reads a possibly null Timer from a Parcel. The timer is associated with the
8917 * proper timer pool from the given BatteryStatsImpl object.
8918 *
8919 * @param in the Parcel to be read from.
8920 * return a new Timer, or null.
8921 */
Bookatz5b5ec322017-05-26 09:40:38 -07008922 private DualTimer readDualTimerFromParcel(int type, ArrayList<StopwatchTimer> pool,
8923 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07008924 if (in.readInt() == 0) {
8925 return null;
8926 }
8927
Bookatz5b5ec322017-05-26 09:40:38 -07008928 return new DualTimer(mBsi.mClocks, mUid, type, pool, timeBase, bgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07008929 }
8930
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008931 boolean reset() {
8932 boolean wlactive = false;
8933 if (mTimerFull != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008934 wlactive |= !mTimerFull.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008935 }
8936 if (mTimerPartial != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008937 wlactive |= !mTimerPartial.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008938 }
8939 if (mTimerWindow != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008940 wlactive |= !mTimerWindow.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008941 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008942 if (mTimerDraw != null) {
8943 wlactive |= !mTimerDraw.reset(false);
Adam Lesinski9425fe22015-06-19 12:02:13 -07008944 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008945 if (!wlactive) {
8946 if (mTimerFull != null) {
8947 mTimerFull.detach();
8948 mTimerFull = null;
8949 }
8950 if (mTimerPartial != null) {
8951 mTimerPartial.detach();
8952 mTimerPartial = null;
8953 }
8954 if (mTimerWindow != null) {
8955 mTimerWindow.detach();
8956 mTimerWindow = null;
8957 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008958 if (mTimerDraw != null) {
8959 mTimerDraw.detach();
8960 mTimerDraw = null;
Adam Lesinski9425fe22015-06-19 12:02:13 -07008961 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008962 }
8963 return !wlactive;
8964 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008965
Bookatz5b5ec322017-05-26 09:40:38 -07008966 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase,
8967 TimeBase screenOffBgTimeBase, Parcel in) {
8968 mTimerPartial = readDualTimerFromParcel(WAKE_TYPE_PARTIAL,
8969 mBsi.mPartialTimers, screenOffTimeBase, screenOffBgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07008970 mTimerFull = readStopwatchTimerFromParcel(WAKE_TYPE_FULL,
8971 mBsi.mFullTimers, timeBase, in);
8972 mTimerWindow = readStopwatchTimerFromParcel(WAKE_TYPE_WINDOW,
8973 mBsi.mWindowTimers, timeBase, in);
8974 mTimerDraw = readStopwatchTimerFromParcel(WAKE_TYPE_DRAW,
8975 mBsi.mDrawTimers, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008976 }
8977
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008978 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
8979 Timer.writeTimerToParcel(out, mTimerPartial, elapsedRealtimeUs);
8980 Timer.writeTimerToParcel(out, mTimerFull, elapsedRealtimeUs);
8981 Timer.writeTimerToParcel(out, mTimerWindow, elapsedRealtimeUs);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008982 Timer.writeTimerToParcel(out, mTimerDraw, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008983 }
8984
8985 @Override
8986 public Timer getWakeTime(int type) {
8987 switch (type) {
8988 case WAKE_TYPE_FULL: return mTimerFull;
8989 case WAKE_TYPE_PARTIAL: return mTimerPartial;
8990 case WAKE_TYPE_WINDOW: return mTimerWindow;
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008991 case WAKE_TYPE_DRAW: return mTimerDraw;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008992 default: throw new IllegalArgumentException("type = " + type);
8993 }
8994 }
8995 }
8996
Joe Onoratoabded112016-02-08 16:49:39 -08008997 public static class Sensor extends BatteryStats.Uid.Sensor {
8998 /**
8999 * BatteryStatsImpl that we are associated with.
9000 */
9001 protected BatteryStatsImpl mBsi;
9002
9003 /**
Bookatz867c0d72017-03-07 18:23:42 -08009004 * Uid that we are associated with.
Joe Onoratoabded112016-02-08 16:49:39 -08009005 */
9006 protected Uid mUid;
9007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009008 final int mHandle;
Bookatz867c0d72017-03-07 18:23:42 -08009009 DualTimer mTimer;
Amith Yamasaniab9ad192016-12-06 12:46:59 -08009010
Joe Onoratoabded112016-02-08 16:49:39 -08009011 public Sensor(BatteryStatsImpl bsi, Uid uid, int handle) {
9012 mBsi = bsi;
9013 mUid = uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009014 mHandle = handle;
9015 }
9016
Bookatz867c0d72017-03-07 18:23:42 -08009017 private DualTimer readTimersFromParcel(
9018 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009019 if (in.readInt() == 0) {
9020 return null;
9021 }
9022
Joe Onoratoabded112016-02-08 16:49:39 -08009023 ArrayList<StopwatchTimer> pool = mBsi.mSensorTimers.get(mHandle);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009024 if (pool == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07009025 pool = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08009026 mBsi.mSensorTimers.put(mHandle, pool);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009027 }
Bookatz867c0d72017-03-07 18:23:42 -08009028 return new DualTimer(mBsi.mClocks, mUid, 0, pool, timeBase, bgTimeBase, in);
Amith Yamasaniab9ad192016-12-06 12:46:59 -08009029 }
9030
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009031 boolean reset() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009032 if (mTimer.reset(true)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009033 mTimer = null;
9034 return true;
9035 }
9036 return false;
9037 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009038
Bookatz867c0d72017-03-07 18:23:42 -08009039 void readFromParcelLocked(TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
9040 mTimer = readTimersFromParcel(timeBase, bgTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009041 }
9042
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009043 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07009044 Timer.writeTimerToParcel(out, mTimer, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009045 }
9046
9047 @Override
9048 public Timer getSensorTime() {
Bookatzaa4594a2017-03-24 12:39:56 -07009049 return mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009050 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009051
9052 @Override
Bookatz867c0d72017-03-07 18:23:42 -08009053 public Timer getSensorBackgroundTime() {
9054 if (mTimer == null) {
9055 return null;
9056 }
9057 return mTimer.getSubTimer();
Amith Yamasaniab9ad192016-12-06 12:46:59 -08009058 }
9059
9060 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009061 public int getHandle() {
9062 return mHandle;
9063 }
9064 }
9065
9066 /**
9067 * The statistics associated with a particular process.
9068 */
Joe Onoratoabded112016-02-08 16:49:39 -08009069 public static class Proc extends BatteryStats.Uid.Proc implements TimeBaseObs {
9070 /**
9071 * BatteryStatsImpl that we are associated with.
9072 */
9073 protected BatteryStatsImpl mBsi;
9074
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009075 /**
Dianne Hackborncd0e3352014-08-07 17:08:09 -07009076 * The name of this process.
9077 */
9078 final String mName;
9079
9080 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -08009081 * Remains true until removed from the stats.
9082 */
9083 boolean mActive = true;
9084
9085 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07009086 * Total time (in ms) spent executing in user code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009087 */
9088 long mUserTime;
9089
9090 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07009091 * Total time (in ms) spent executing in kernel code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009092 */
9093 long mSystemTime;
9094
9095 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07009096 * Amount of time (in ms) the process was running in the foreground.
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009097 */
9098 long mForegroundTime;
9099
9100 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009101 * Number of times the process has been started.
9102 */
9103 int mStarts;
9104
9105 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009106 * Number of times the process has crashed.
9107 */
9108 int mNumCrashes;
9109
9110 /**
9111 * Number of times the process has had an ANR.
9112 */
9113 int mNumAnrs;
9114
9115 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009116 * The amount of user time loaded from a previous save.
9117 */
9118 long mLoadedUserTime;
9119
9120 /**
9121 * The amount of system time loaded from a previous save.
9122 */
9123 long mLoadedSystemTime;
9124
9125 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009126 * The amount of foreground time loaded from a previous save.
9127 */
9128 long mLoadedForegroundTime;
9129
9130 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009131 * The number of times the process has started from a previous save.
9132 */
9133 int mLoadedStarts;
9134
9135 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009136 * Number of times the process has crashed from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009137 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009138 int mLoadedNumCrashes;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009139
9140 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009141 * Number of times the process has had an ANR from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009142 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009143 int mLoadedNumAnrs;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009144
9145 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009146 * The amount of user time when last unplugged.
9147 */
9148 long mUnpluggedUserTime;
9149
9150 /**
9151 * The amount of system time when last unplugged.
9152 */
9153 long mUnpluggedSystemTime;
9154
9155 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009156 * The amount of foreground time since unplugged.
9157 */
9158 long mUnpluggedForegroundTime;
9159
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009160 /**
9161 * The number of times the process has started before unplugged.
9162 */
9163 int mUnpluggedStarts;
9164
Dianne Hackborn61659e52014-07-09 16:13:01 -07009165 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009166 * Number of times the process has crashed before unplugged.
9167 */
9168 int mUnpluggedNumCrashes;
9169
9170 /**
9171 * Number of times the process has had an ANR before unplugged.
9172 */
9173 int mUnpluggedNumAnrs;
9174
Dianne Hackborn287952c2010-09-22 22:34:31 -07009175 ArrayList<ExcessivePower> mExcessivePower;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009176
Joe Onoratoabded112016-02-08 16:49:39 -08009177 public Proc(BatteryStatsImpl bsi, String name) {
9178 mBsi = bsi;
Dianne Hackborncd0e3352014-08-07 17:08:09 -07009179 mName = name;
Joe Onoratoabded112016-02-08 16:49:39 -08009180 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009181 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07009182
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009183 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009184 mUnpluggedUserTime = mUserTime;
9185 mUnpluggedSystemTime = mSystemTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009186 mUnpluggedForegroundTime = mForegroundTime;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009187 mUnpluggedStarts = mStarts;
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009188 mUnpluggedNumCrashes = mNumCrashes;
9189 mUnpluggedNumAnrs = mNumAnrs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009190 }
9191
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009192 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009193 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009194
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009195 void detach() {
Dianne Hackborn099bc622014-01-22 13:39:16 -08009196 mActive = false;
Joe Onoratoabded112016-02-08 16:49:39 -08009197 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009198 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009199
Dianne Hackborn287952c2010-09-22 22:34:31 -07009200 public int countExcessivePowers() {
9201 return mExcessivePower != null ? mExcessivePower.size() : 0;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009202 }
9203
Dianne Hackborn287952c2010-09-22 22:34:31 -07009204 public ExcessivePower getExcessivePower(int i) {
9205 if (mExcessivePower != null) {
9206 return mExcessivePower.get(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009207 }
9208 return null;
9209 }
9210
Dianne Hackborn287952c2010-09-22 22:34:31 -07009211 public void addExcessiveCpu(long overTime, long usedTime) {
9212 if (mExcessivePower == null) {
9213 mExcessivePower = new ArrayList<ExcessivePower>();
9214 }
9215 ExcessivePower ew = new ExcessivePower();
9216 ew.type = ExcessivePower.TYPE_CPU;
9217 ew.overTime = overTime;
9218 ew.usedTime = usedTime;
9219 mExcessivePower.add(ew);
9220 }
9221
9222 void writeExcessivePowerToParcelLocked(Parcel out) {
9223 if (mExcessivePower == null) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009224 out.writeInt(0);
9225 return;
9226 }
9227
Dianne Hackborn287952c2010-09-22 22:34:31 -07009228 final int N = mExcessivePower.size();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009229 out.writeInt(N);
9230 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009231 ExcessivePower ew = mExcessivePower.get(i);
9232 out.writeInt(ew.type);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009233 out.writeLong(ew.overTime);
9234 out.writeLong(ew.usedTime);
9235 }
9236 }
9237
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009238 void readExcessivePowerFromParcelLocked(Parcel in) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009239 final int N = in.readInt();
9240 if (N == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009241 mExcessivePower = null;
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009242 return;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009243 }
9244
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08009245 if (N > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009246 throw new ParcelFormatException(
9247 "File corrupt: too many excessive power entries " + N);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08009248 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009249
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009250 mExcessivePower = new ArrayList<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009251 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009252 ExcessivePower ew = new ExcessivePower();
9253 ew.type = in.readInt();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009254 ew.overTime = in.readLong();
9255 ew.usedTime = in.readLong();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009256 mExcessivePower.add(ew);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009257 }
9258 }
9259
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009260 void writeToParcelLocked(Parcel out) {
9261 out.writeLong(mUserTime);
9262 out.writeLong(mSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009263 out.writeLong(mForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009264 out.writeInt(mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009265 out.writeInt(mNumCrashes);
9266 out.writeInt(mNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009267 out.writeLong(mLoadedUserTime);
9268 out.writeLong(mLoadedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009269 out.writeLong(mLoadedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009270 out.writeInt(mLoadedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009271 out.writeInt(mLoadedNumCrashes);
9272 out.writeInt(mLoadedNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009273 out.writeLong(mUnpluggedUserTime);
9274 out.writeLong(mUnpluggedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009275 out.writeLong(mUnpluggedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009276 out.writeInt(mUnpluggedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009277 out.writeInt(mUnpluggedNumCrashes);
9278 out.writeInt(mUnpluggedNumAnrs);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009279 writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009280 }
9281
9282 void readFromParcelLocked(Parcel in) {
9283 mUserTime = in.readLong();
9284 mSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009285 mForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009286 mStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009287 mNumCrashes = in.readInt();
9288 mNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009289 mLoadedUserTime = in.readLong();
9290 mLoadedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009291 mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009292 mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009293 mLoadedNumCrashes = in.readInt();
9294 mLoadedNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009295 mUnpluggedUserTime = in.readLong();
9296 mUnpluggedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009297 mUnpluggedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009298 mUnpluggedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009299 mUnpluggedNumCrashes = in.readInt();
9300 mUnpluggedNumAnrs = in.readInt();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009301 readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009302 }
9303
Adam Lesinski06af1fa2015-05-05 17:35:35 -07009304 public void addCpuTimeLocked(int utime, int stime) {
Sudheer Shankac57729a2018-02-09 15:44:42 -08009305 addCpuTimeLocked(utime, stime, mBsi.mOnBatteryTimeBase.isRunning());
9306 }
9307
9308 public void addCpuTimeLocked(int utime, int stime, boolean isRunning) {
9309 if (isRunning) {
9310 mUserTime += utime;
9311 mSystemTime += stime;
9312 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009313 }
9314
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009315 public void addForegroundTimeLocked(long ttime) {
9316 mForegroundTime += ttime;
9317 }
9318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009319 public void incStartsLocked() {
9320 mStarts++;
9321 }
9322
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009323 public void incNumCrashesLocked() {
9324 mNumCrashes++;
9325 }
9326
9327 public void incNumAnrsLocked() {
9328 mNumAnrs++;
9329 }
9330
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009331 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -08009332 public boolean isActive() {
9333 return mActive;
9334 }
9335
9336 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009337 public long getUserTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009338 long val = mUserTime;
9339 if (which == STATS_CURRENT) {
9340 val -= mLoadedUserTime;
9341 } else if (which == STATS_SINCE_UNPLUGGED) {
9342 val -= mUnpluggedUserTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009343 }
9344 return val;
9345 }
9346
9347 @Override
9348 public long getSystemTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009349 long val = mSystemTime;
9350 if (which == STATS_CURRENT) {
9351 val -= mLoadedSystemTime;
9352 } else if (which == STATS_SINCE_UNPLUGGED) {
9353 val -= mUnpluggedSystemTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009354 }
9355 return val;
9356 }
9357
9358 @Override
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009359 public long getForegroundTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009360 long val = mForegroundTime;
9361 if (which == STATS_CURRENT) {
9362 val -= mLoadedForegroundTime;
9363 } else if (which == STATS_SINCE_UNPLUGGED) {
9364 val -= mUnpluggedForegroundTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009365 }
9366 return val;
9367 }
9368
9369 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009370 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009371 int val = mStarts;
9372 if (which == STATS_CURRENT) {
9373 val -= mLoadedStarts;
9374 } else if (which == STATS_SINCE_UNPLUGGED) {
9375 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009376 }
9377 return val;
9378 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07009379
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009380 @Override
9381 public int getNumCrashes(int which) {
9382 int val = mNumCrashes;
9383 if (which == STATS_CURRENT) {
9384 val -= mLoadedNumCrashes;
9385 } else if (which == STATS_SINCE_UNPLUGGED) {
9386 val -= mUnpluggedNumCrashes;
9387 }
9388 return val;
9389 }
9390
9391 @Override
9392 public int getNumAnrs(int which) {
9393 int val = mNumAnrs;
9394 if (which == STATS_CURRENT) {
9395 val -= mLoadedNumAnrs;
9396 } else if (which == STATS_SINCE_UNPLUGGED) {
9397 val -= mUnpluggedNumAnrs;
9398 }
9399 return val;
9400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009401 }
9402
9403 /**
9404 * The statistics associated with a particular package.
9405 */
Joe Onoratoabded112016-02-08 16:49:39 -08009406 public static class Pkg extends BatteryStats.Uid.Pkg implements TimeBaseObs {
9407 /**
9408 * BatteryStatsImpl that we are associated with.
9409 */
9410 protected BatteryStatsImpl mBsi;
9411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009412 /**
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009413 * Number of times wakeup alarms have occurred for this app.
Bookatz98d4d5c2017-08-01 19:07:54 -07009414 * On screen-off timebase starting in report v25.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009415 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009416 ArrayMap<String, Counter> mWakeupAlarms = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009417
9418 /**
9419 * The statics we have collected for this package's services.
9420 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009421 final ArrayMap<String, Serv> mServiceStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009422
Joe Onoratoabded112016-02-08 16:49:39 -08009423 public Pkg(BatteryStatsImpl bsi) {
9424 mBsi = bsi;
9425 mBsi.mOnBatteryScreenOffTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009426 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009427
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009428 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009429 }
9430
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009431 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009432 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009433
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009434 void detach() {
Joe Onoratoabded112016-02-08 16:49:39 -08009435 mBsi.mOnBatteryScreenOffTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009436 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009437
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009438 void readFromParcelLocked(Parcel in) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009439 int numWA = in.readInt();
9440 mWakeupAlarms.clear();
9441 for (int i=0; i<numWA; i++) {
9442 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -07009443 mWakeupAlarms.put(tag, new Counter(mBsi.mOnBatteryScreenOffTimeBase, in));
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009444 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009445
9446 int numServs = in.readInt();
9447 mServiceStats.clear();
9448 for (int m = 0; m < numServs; m++) {
9449 String serviceName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08009450 Uid.Pkg.Serv serv = new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009451 mServiceStats.put(serviceName, serv);
9452
9453 serv.readFromParcelLocked(in);
9454 }
9455 }
9456
9457 void writeToParcelLocked(Parcel out) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009458 int numWA = mWakeupAlarms.size();
9459 out.writeInt(numWA);
9460 for (int i=0; i<numWA; i++) {
9461 out.writeString(mWakeupAlarms.keyAt(i));
9462 mWakeupAlarms.valueAt(i).writeToParcel(out);
9463 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009464
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009465 final int NS = mServiceStats.size();
9466 out.writeInt(NS);
9467 for (int i=0; i<NS; i++) {
9468 out.writeString(mServiceStats.keyAt(i));
9469 Uid.Pkg.Serv serv = mServiceStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009470 serv.writeToParcelLocked(out);
9471 }
9472 }
9473
9474 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009475 public ArrayMap<String, ? extends BatteryStats.Counter> getWakeupAlarmStats() {
9476 return mWakeupAlarms;
9477 }
9478
9479 public void noteWakeupAlarmLocked(String tag) {
9480 Counter c = mWakeupAlarms.get(tag);
9481 if (c == null) {
Bookatz98d4d5c2017-08-01 19:07:54 -07009482 c = new Counter(mBsi.mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009483 mWakeupAlarms.put(tag, c);
9484 }
9485 c.stepAtomic();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009486 }
9487
9488 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009489 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg.Serv> getServiceStats() {
9490 return mServiceStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009491 }
9492
9493 /**
9494 * The statistics associated with a particular service.
9495 */
Joe Onoratoabded112016-02-08 16:49:39 -08009496 public static class Serv extends BatteryStats.Uid.Pkg.Serv implements TimeBaseObs {
9497 /**
9498 * BatteryStatsImpl that we are associated with.
9499 */
9500 protected BatteryStatsImpl mBsi;
9501
9502 /**
9503 * The android package in which this service resides.
9504 */
9505 protected Pkg mPkg;
9506
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009507 /**
9508 * Total time (ms in battery uptime) the service has been left started.
9509 */
Joe Onoratoabded112016-02-08 16:49:39 -08009510 protected long mStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009511
9512 /**
9513 * If service has been started and not yet stopped, this is
9514 * when it was started.
9515 */
Joe Onoratoabded112016-02-08 16:49:39 -08009516 protected long mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009517
9518 /**
9519 * True if we are currently running.
9520 */
Joe Onoratoabded112016-02-08 16:49:39 -08009521 protected boolean mRunning;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009522
9523 /**
9524 * Total number of times startService() has been called.
9525 */
Joe Onoratoabded112016-02-08 16:49:39 -08009526 protected int mStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009527
9528 /**
9529 * Total time (ms in battery uptime) the service has been left launched.
9530 */
Joe Onoratoabded112016-02-08 16:49:39 -08009531 protected long mLaunchedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009532
9533 /**
9534 * If service has been launched and not yet exited, this is
9535 * when it was launched (ms in battery uptime).
9536 */
Joe Onoratoabded112016-02-08 16:49:39 -08009537 protected long mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009538
9539 /**
9540 * True if we are currently launched.
9541 */
Joe Onoratoabded112016-02-08 16:49:39 -08009542 protected boolean mLaunched;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009543
9544 /**
9545 * Total number times the service has been launched.
9546 */
Joe Onoratoabded112016-02-08 16:49:39 -08009547 protected int mLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009548
9549 /**
9550 * The amount of time spent started loaded from a previous save
9551 * (ms in battery uptime).
9552 */
Joe Onoratoabded112016-02-08 16:49:39 -08009553 protected long mLoadedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009554
9555 /**
9556 * The number of starts loaded from a previous save.
9557 */
Joe Onoratoabded112016-02-08 16:49:39 -08009558 protected int mLoadedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009559
9560 /**
9561 * The number of launches loaded from a previous save.
9562 */
Joe Onoratoabded112016-02-08 16:49:39 -08009563 protected int mLoadedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009564
9565 /**
9566 * The amount of time spent started as of the last run (ms
9567 * in battery uptime).
9568 */
Joe Onoratoabded112016-02-08 16:49:39 -08009569 protected long mLastStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009570
9571 /**
9572 * The number of starts as of the last run.
9573 */
Joe Onoratoabded112016-02-08 16:49:39 -08009574 protected int mLastStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009575
9576 /**
9577 * The number of launches as of the last run.
9578 */
Joe Onoratoabded112016-02-08 16:49:39 -08009579 protected int mLastLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009580
9581 /**
9582 * The amount of time spent started when last unplugged (ms
9583 * in battery uptime).
9584 */
Joe Onoratoabded112016-02-08 16:49:39 -08009585 protected long mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009586
9587 /**
9588 * The number of starts when last unplugged.
9589 */
Joe Onoratoabded112016-02-08 16:49:39 -08009590 protected int mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009591
9592 /**
9593 * The number of launches when last unplugged.
9594 */
Joe Onoratoabded112016-02-08 16:49:39 -08009595 protected int mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009596
Joe Onoratoabded112016-02-08 16:49:39 -08009597 /**
9598 * Construct a Serv. Also adds it to the on-battery time base as a listener.
9599 */
9600 public Serv(BatteryStatsImpl bsi) {
9601 mBsi = bsi;
9602 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009603 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009604
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009605 public void onTimeStarted(long elapsedRealtime, long baseUptime,
9606 long baseRealtime) {
9607 mUnpluggedStartTime = getStartTimeToNowLocked(baseUptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009608 mUnpluggedStarts = mStarts;
9609 mUnpluggedLaunches = mLaunches;
9610 }
9611
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009612 public void onTimeStopped(long elapsedRealtime, long baseUptime,
9613 long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009614 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009615
Joe Onoratoabded112016-02-08 16:49:39 -08009616 /**
9617 * Remove this Serv as a listener from the time base.
9618 */
9619 public void detach() {
9620 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009621 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009622
Joe Onoratoabded112016-02-08 16:49:39 -08009623 public void readFromParcelLocked(Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009624 mStartTime = in.readLong();
9625 mRunningSince = in.readLong();
9626 mRunning = in.readInt() != 0;
9627 mStarts = in.readInt();
9628 mLaunchedTime = in.readLong();
9629 mLaunchedSince = in.readLong();
9630 mLaunched = in.readInt() != 0;
9631 mLaunches = in.readInt();
9632 mLoadedStartTime = in.readLong();
9633 mLoadedStarts = in.readInt();
9634 mLoadedLaunches = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07009635 mLastStartTime = 0;
9636 mLastStarts = 0;
9637 mLastLaunches = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009638 mUnpluggedStartTime = in.readLong();
9639 mUnpluggedStarts = in.readInt();
9640 mUnpluggedLaunches = in.readInt();
9641 }
9642
Joe Onoratoabded112016-02-08 16:49:39 -08009643 public void writeToParcelLocked(Parcel out) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009644 out.writeLong(mStartTime);
9645 out.writeLong(mRunningSince);
9646 out.writeInt(mRunning ? 1 : 0);
9647 out.writeInt(mStarts);
9648 out.writeLong(mLaunchedTime);
9649 out.writeLong(mLaunchedSince);
9650 out.writeInt(mLaunched ? 1 : 0);
9651 out.writeInt(mLaunches);
9652 out.writeLong(mLoadedStartTime);
9653 out.writeInt(mLoadedStarts);
9654 out.writeInt(mLoadedLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009655 out.writeLong(mUnpluggedStartTime);
9656 out.writeInt(mUnpluggedStarts);
9657 out.writeInt(mUnpluggedLaunches);
9658 }
9659
Joe Onoratoabded112016-02-08 16:49:39 -08009660 public long getLaunchTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009661 if (!mLaunched) return mLaunchedTime;
9662 return mLaunchedTime + batteryUptime - mLaunchedSince;
9663 }
9664
Joe Onoratoabded112016-02-08 16:49:39 -08009665 public long getStartTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009666 if (!mRunning) return mStartTime;
9667 return mStartTime + batteryUptime - mRunningSince;
9668 }
9669
9670 public void startLaunchedLocked() {
9671 if (!mLaunched) {
9672 mLaunches++;
Joe Onoratoabded112016-02-08 16:49:39 -08009673 mLaunchedSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009674 mLaunched = true;
9675 }
9676 }
9677
9678 public void stopLaunchedLocked() {
9679 if (mLaunched) {
Joe Onoratoabded112016-02-08 16:49:39 -08009680 long time = mBsi.getBatteryUptimeLocked() - mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009681 if (time > 0) {
9682 mLaunchedTime += time;
9683 } else {
9684 mLaunches--;
9685 }
9686 mLaunched = false;
9687 }
9688 }
9689
9690 public void startRunningLocked() {
9691 if (!mRunning) {
9692 mStarts++;
Joe Onoratoabded112016-02-08 16:49:39 -08009693 mRunningSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009694 mRunning = true;
9695 }
9696 }
9697
9698 public void stopRunningLocked() {
9699 if (mRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08009700 long time = mBsi.getBatteryUptimeLocked() - mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009701 if (time > 0) {
9702 mStartTime += time;
9703 } else {
9704 mStarts--;
9705 }
9706 mRunning = false;
9707 }
9708 }
9709
9710 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -08009711 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009712 }
9713
9714 @Override
9715 public int getLaunches(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009716 int val = mLaunches;
9717 if (which == STATS_CURRENT) {
9718 val -= mLoadedLaunches;
9719 } else if (which == STATS_SINCE_UNPLUGGED) {
9720 val -= mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009721 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009722 return val;
9723 }
9724
9725 @Override
9726 public long getStartTime(long now, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009727 long val = getStartTimeToNowLocked(now);
9728 if (which == STATS_CURRENT) {
9729 val -= mLoadedStartTime;
9730 } else if (which == STATS_SINCE_UNPLUGGED) {
9731 val -= mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009732 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009733 return val;
9734 }
9735
9736 @Override
9737 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009738 int val = mStarts;
9739 if (which == STATS_CURRENT) {
9740 val -= mLoadedStarts;
9741 } else if (which == STATS_SINCE_UNPLUGGED) {
9742 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009743 }
9744
9745 return val;
9746 }
9747 }
9748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009749 final Serv newServiceStatsLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08009750 return new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009751 }
9752 }
9753
9754 /**
9755 * Retrieve the statistics object for a particular process, creating
9756 * if needed.
9757 */
9758 public Proc getProcessStatsLocked(String name) {
9759 Proc ps = mProcessStats.get(name);
9760 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08009761 ps = new Proc(mBsi, name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009762 mProcessStats.put(name, ps);
9763 }
9764
9765 return ps;
9766 }
9767
Andreas Gampe3f24e692018-02-05 13:24:28 -08009768 @GuardedBy("mBsi")
Dianne Hackborna8d10942015-11-19 17:55:19 -08009769 public void updateUidProcessStateLocked(int procState) {
9770 int uidRunningState;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009771 // Make special note of Foreground Services
9772 final boolean userAwareService =
9773 (procState == ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009774 uidRunningState = BatteryStats.mapToInternalProcessState(procState);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009775
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009776 if (mProcessState == uidRunningState && userAwareService == mInForegroundService) {
9777 return;
9778 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08009779
Bookatz867c0d72017-03-07 18:23:42 -08009780 final long elapsedRealtimeMs = mBsi.mClocks.elapsedRealtime();
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009781 if (mProcessState != uidRunningState) {
9782 final long uptimeMs = mBsi.mClocks.uptimeMillis();
Dianne Hackborna8d10942015-11-19 17:55:19 -08009783
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009784 if (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
9785 mProcessStateTimer[mProcessState].stopRunningLocked(elapsedRealtimeMs);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009786
Sudheer Shanka5c19b892018-01-05 17:25:46 -08009787 if (mBsi.trackPerProcStateCpuTimes()) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009788 if (mBsi.mPendingUids.size() == 0) {
Sudheer Shankae544d162017-12-28 17:06:20 -08009789 mBsi.mExternalSync.scheduleReadProcStateCpuTimes(
9790 mBsi.mOnBatteryTimeBase.isRunning(),
Sudheer Shankac20379e2018-02-15 00:06:21 -08009791 mBsi.mOnBatteryScreenOffTimeBase.isRunning(),
9792 mBsi.mConstants.PROC_STATE_CPU_TIMES_READ_DELAY_MS);
Mike Ma234d1822018-03-13 18:53:21 -07009793 mBsi.mNumSingleUidCpuTimeReads++;
Sudheer Shankac20379e2018-02-15 00:06:21 -08009794 } else {
Mike Ma234d1822018-03-13 18:53:21 -07009795 mBsi.mNumBatchedSingleUidCpuTimeReads++;
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009796 }
9797 if (mBsi.mPendingUids.indexOfKey(mUid) < 0
9798 || ArrayUtils.contains(CRITICAL_PROC_STATES, mProcessState)) {
9799 mBsi.mPendingUids.put(mUid, mProcessState);
9800 }
9801 } else {
9802 mBsi.mPendingUids.clear();
9803 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07009804 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009805 mProcessState = uidRunningState;
9806 if (uidRunningState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
9807 if (mProcessStateTimer[uidRunningState] == null) {
9808 makeProcessState(uidRunningState, null);
9809 }
9810 mProcessStateTimer[uidRunningState].startRunningLocked(elapsedRealtimeMs);
9811 }
9812
9813 updateOnBatteryBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
9814 updateOnBatteryScreenOffBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009815 }
Bookatz867c0d72017-03-07 18:23:42 -08009816
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009817 if (userAwareService != mInForegroundService) {
9818 if (userAwareService) {
9819 noteForegroundServiceResumedLocked(elapsedRealtimeMs);
9820 } else {
9821 noteForegroundServicePausedLocked(elapsedRealtimeMs);
9822 }
9823 mInForegroundService = userAwareService;
9824 }
Bookatz867c0d72017-03-07 18:23:42 -08009825 }
9826
Bookatzc8c44962017-05-11 12:12:54 -07009827 /** Whether to consider Uid to be in the background for background timebase purposes. */
9828 public boolean isInBackground() {
Bookatz867c0d72017-03-07 18:23:42 -08009829 // Note that PROCESS_STATE_CACHED and ActivityManager.PROCESS_STATE_NONEXISTENT is
9830 // also considered to be 'background' for our purposes, because it's not foreground.
Bookatzc8c44962017-05-11 12:12:54 -07009831 return mProcessState >= PROCESS_STATE_BACKGROUND;
9832 }
9833
9834 public boolean updateOnBatteryBgTimeBase(long uptimeUs, long realtimeUs) {
9835 boolean on = mBsi.mOnBatteryTimeBase.isRunning() && isInBackground();
9836 return mOnBatteryBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
9837 }
9838
9839 public boolean updateOnBatteryScreenOffBgTimeBase(long uptimeUs, long realtimeUs) {
9840 boolean on = mBsi.mOnBatteryScreenOffTimeBase.isRunning() && isInBackground();
9841 return mOnBatteryScreenOffBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009842 }
9843
Dianne Hackbornb5e31652010-09-07 12:13:55 -07009844 public SparseArray<? extends Pid> getPidStats() {
9845 return mPids;
9846 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009847
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009848 public Pid getPidStatsLocked(int pid) {
9849 Pid p = mPids.get(pid);
9850 if (p == null) {
9851 p = new Pid();
9852 mPids.put(pid, p);
9853 }
9854 return p;
9855 }
9856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009857 /**
9858 * Retrieve the statistics object for a particular service, creating
9859 * if needed.
9860 */
9861 public Pkg getPackageStatsLocked(String name) {
9862 Pkg ps = mPackageStats.get(name);
9863 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08009864 ps = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009865 mPackageStats.put(name, ps);
9866 }
9867
9868 return ps;
9869 }
9870
9871 /**
9872 * Retrieve the statistics object for a particular service, creating
9873 * if needed.
9874 */
9875 public Pkg.Serv getServiceStatsLocked(String pkg, String serv) {
9876 Pkg ps = getPackageStatsLocked(pkg);
9877 Pkg.Serv ss = ps.mServiceStats.get(serv);
9878 if (ss == null) {
9879 ss = ps.newServiceStatsLocked();
9880 ps.mServiceStats.put(serv, ss);
9881 }
9882
9883 return ss;
9884 }
9885
Dianne Hackbornd953c532014-08-16 18:17:38 -07009886 public void readSyncSummaryFromParcelLocked(String name, Parcel in) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009887 DualTimer timer = mSyncStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07009888 timer.readSummaryFromParcelLocked(in);
9889 mSyncStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009890 }
9891
Dianne Hackbornd953c532014-08-16 18:17:38 -07009892 public void readJobSummaryFromParcelLocked(String name, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07009893 DualTimer timer = mJobStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07009894 timer.readSummaryFromParcelLocked(in);
9895 mJobStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009896 }
9897
Dianne Hackbornd953c532014-08-16 18:17:38 -07009898 public void readWakeSummaryFromParcelLocked(String wlName, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08009899 Wakelock wl = new Wakelock(mBsi, this);
Dianne Hackbornd953c532014-08-16 18:17:38 -07009900 mWakelockStats.add(wlName, wl);
9901 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009902 getWakelockTimerLocked(wl, WAKE_TYPE_FULL).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009903 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07009904 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009905 getWakelockTimerLocked(wl, WAKE_TYPE_PARTIAL).readSummaryFromParcelLocked(in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07009906 }
9907 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009908 getWakelockTimerLocked(wl, WAKE_TYPE_WINDOW).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009909 }
Adam Lesinski9425fe22015-06-19 12:02:13 -07009910 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009911 getWakelockTimerLocked(wl, WAKE_TYPE_DRAW).readSummaryFromParcelLocked(in);
Adam Lesinski9425fe22015-06-19 12:02:13 -07009912 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009913 }
9914
Bookatz867c0d72017-03-07 18:23:42 -08009915 public DualTimer getSensorTimerLocked(int sensor, boolean create) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009916 Sensor se = mSensorStats.get(sensor);
9917 if (se == null) {
9918 if (!create) {
9919 return null;
9920 }
Joe Onoratoabded112016-02-08 16:49:39 -08009921 se = new Sensor(mBsi, this, sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009922 mSensorStats.put(sensor, se);
9923 }
Bookatz867c0d72017-03-07 18:23:42 -08009924 DualTimer t = se.mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009925 if (t != null) {
9926 return t;
9927 }
Joe Onoratoabded112016-02-08 16:49:39 -08009928 ArrayList<StopwatchTimer> timers = mBsi.mSensorTimers.get(sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009929 if (timers == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07009930 timers = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08009931 mBsi.mSensorTimers.put(sensor, timers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009932 }
Bookatz867c0d72017-03-07 18:23:42 -08009933 t = new DualTimer(mBsi.mClocks, this, BatteryStats.SENSOR, timers,
9934 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009935 se.mTimer = t;
9936 return t;
9937 }
9938
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009939 public void noteStartSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009940 DualTimer t = mSyncStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009941 if (t != null) {
9942 t.startRunningLocked(elapsedRealtimeMs);
9943 }
9944 }
9945
9946 public void noteStopSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009947 DualTimer t = mSyncStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009948 if (t != null) {
9949 t.stopRunningLocked(elapsedRealtimeMs);
9950 }
9951 }
9952
9953 public void noteStartJobLocked(String name, long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07009954 DualTimer t = mJobStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009955 if (t != null) {
9956 t.startRunningLocked(elapsedRealtimeMs);
9957 }
9958 }
9959
Dianne Hackborn94326cb2017-06-28 16:17:20 -07009960 public void noteStopJobLocked(String name, long elapsedRealtimeMs, int stopReason) {
Bookatzaa4594a2017-03-24 12:39:56 -07009961 DualTimer t = mJobStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009962 if (t != null) {
9963 t.stopRunningLocked(elapsedRealtimeMs);
9964 }
Dianne Hackborn94326cb2017-06-28 16:17:20 -07009965 if (mBsi.mOnBatteryTimeBase.isRunning()) {
9966 SparseIntArray types = mJobCompletions.get(name);
9967 if (types == null) {
9968 types = new SparseIntArray();
9969 mJobCompletions.put(name, types);
9970 }
9971 int last = types.get(stopReason, 0);
9972 types.put(stopReason, last + 1);
9973 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009974 }
9975
Bookatz5b5ec322017-05-26 09:40:38 -07009976 public StopwatchTimer getWakelockTimerLocked(Wakelock wl, int type) {
9977 if (wl == null) {
9978 return null;
9979 }
9980 switch (type) {
9981 case WAKE_TYPE_PARTIAL: {
9982 DualTimer t = wl.mTimerPartial;
9983 if (t == null) {
9984 t = new DualTimer(mBsi.mClocks, this, WAKE_TYPE_PARTIAL,
9985 mBsi.mPartialTimers, mBsi.mOnBatteryScreenOffTimeBase,
9986 mOnBatteryScreenOffBackgroundTimeBase);
9987 wl.mTimerPartial = t;
9988 }
9989 return t;
9990 }
9991 case WAKE_TYPE_FULL: {
9992 StopwatchTimer t = wl.mTimerFull;
9993 if (t == null) {
9994 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_FULL,
9995 mBsi.mFullTimers, mBsi.mOnBatteryTimeBase);
9996 wl.mTimerFull = t;
9997 }
9998 return t;
9999 }
10000 case WAKE_TYPE_WINDOW: {
10001 StopwatchTimer t = wl.mTimerWindow;
10002 if (t == null) {
10003 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_WINDOW,
10004 mBsi.mWindowTimers, mBsi.mOnBatteryTimeBase);
10005 wl.mTimerWindow = t;
10006 }
10007 return t;
10008 }
10009 case WAKE_TYPE_DRAW: {
10010 StopwatchTimer t = wl.mTimerDraw;
10011 if (t == null) {
10012 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_DRAW,
10013 mBsi.mDrawTimers, mBsi.mOnBatteryTimeBase);
10014 wl.mTimerDraw = t;
10015 }
10016 return t;
10017 }
10018 default:
10019 throw new IllegalArgumentException("type=" + type);
10020 }
10021 }
10022
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010023 public void noteStartWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070010024 Wakelock wl = mWakelockStats.startObject(name);
10025 if (wl != null) {
Bookatz5b5ec322017-05-26 09:40:38 -070010026 getWakelockTimerLocked(wl, type).startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010027 }
Bookatzc8c44962017-05-11 12:12:54 -070010028 if (type == WAKE_TYPE_PARTIAL) {
10029 createAggregatedPartialWakelockTimerLocked().startRunningLocked(elapsedRealtimeMs);
10030 if (pid >= 0) {
10031 Pid p = getPidStatsLocked(pid);
10032 if (p.mWakeNesting++ == 0) {
10033 p.mWakeStartMs = elapsedRealtimeMs;
10034 }
Dianne Hackbornb8071d792010-09-09 16:45:15 -070010035 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010036 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010037 }
10038
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010039 public void noteStopWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070010040 Wakelock wl = mWakelockStats.stopObject(name);
10041 if (wl != null) {
Bookatzd6746242017-10-24 18:39:35 -070010042 StopwatchTimer wlt = getWakelockTimerLocked(wl, type);
10043 wlt.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010044 }
Bookatzc8c44962017-05-11 12:12:54 -070010045 if (type == WAKE_TYPE_PARTIAL) {
10046 if (mAggregatedPartialWakelockTimer != null) {
10047 mAggregatedPartialWakelockTimer.stopRunningLocked(elapsedRealtimeMs);
10048 }
10049 if (pid >= 0) {
10050 Pid p = mPids.get(pid);
10051 if (p != null && p.mWakeNesting > 0) {
10052 if (p.mWakeNesting-- == 1) {
10053 p.mWakeSumMs += elapsedRealtimeMs - p.mWakeStartMs;
10054 p.mWakeStartMs = 0;
10055 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -080010056 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010057 }
10058 }
10059 }
10060
Dianne Hackborn287952c2010-09-22 22:34:31 -070010061 public void reportExcessiveCpuLocked(String proc, long overTime, long usedTime) {
10062 Proc p = getProcessStatsLocked(proc);
10063 if (p != null) {
10064 p.addExcessiveCpu(overTime, usedTime);
10065 }
10066 }
10067
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010068 public void noteStartSensor(int sensor, long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -080010069 DualTimer t = getSensorTimerLocked(sensor, /* create= */ true);
Amith Yamasani154d1242017-02-16 10:01:48 -080010070 t.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010071 }
10072
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010073 public void noteStopSensor(int sensor, long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010074 // Don't create a timer if one doesn't already exist
Bookatz867c0d72017-03-07 18:23:42 -080010075 DualTimer t = getSensorTimerLocked(sensor, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010076 if (t != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010077 t.stopRunningLocked(elapsedRealtimeMs);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010078 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010079 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010080
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010081 public void noteStartGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -080010082 noteStartSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010083 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010084
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010085 public void noteStopGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -080010086 noteStopSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010087 }
10088
10089 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -080010090 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010091 }
10092 }
10093
Sudheer Shanka9b735c52017-05-09 18:26:18 -070010094 public long[] getCpuFreqs() {
10095 return mCpuFreqs;
10096 }
10097
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010098 public BatteryStatsImpl(File systemDir, Handler handler, PlatformIdleStateCallback cb,
10099 UserInfoProvider userInfoProvider) {
10100 this(new SystemClocks(), systemDir, handler, cb, userInfoProvider);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010101 }
10102
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010103 private BatteryStatsImpl(Clocks clocks, File systemDir, Handler handler,
10104 PlatformIdleStateCallback cb,
10105 UserInfoProvider userInfoProvider) {
Joe Onoratoabded112016-02-08 16:49:39 -080010106 init(clocks);
10107
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010108 if (systemDir != null) {
10109 mFile = new JournaledFile(new File(systemDir, "batterystats.bin"),
10110 new File(systemDir, "batterystats.bin.tmp"));
10111 } else {
10112 mFile = null;
10113 }
10114 mCheckinFile = new AtomicFile(new File(systemDir, "batterystats-checkin.bin"));
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010115 mDailyFile = new AtomicFile(new File(systemDir, "batterystats-daily.xml"));
Jeff Brown6f357d32014-01-15 20:40:55 -080010116 mHandler = new MyHandler(handler.getLooper());
Sudheer Shanka5c19b892018-01-05 17:25:46 -080010117 mConstants = new Constants(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010118 mStartCount++;
Joe Onoratoabded112016-02-08 16:49:39 -080010119 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -070010120 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -070010121 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010122 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010123 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010124 }
Joe Onoratoabded112016-02-08 16:49:39 -080010125 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase);
10126 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
10127 mOnBatteryTimeBase);
10128 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -11, null,
10129 mOnBatteryTimeBase);
10130 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
10131 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null, mOnBatteryTimeBase);
10132 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase);
10133 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase);
10134 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
10135 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i, null,
10136 mOnBatteryTimeBase);
10137 }
10138 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
10139 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010140 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010141 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010142 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010143 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010144 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010145 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
10146 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010147 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010148 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase, NUM_WIFI_TX_LEVELS);
10149 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
10150 NUM_BT_TX_LEVELS);
10151 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
10152 ModemActivityInfo.TX_POWER_LEVELS);
Joe Onoratoabded112016-02-08 16:49:39 -080010153 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null, mOnBatteryTimeBase);
10154 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
10155 mOnBatteryTimeBase);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010156 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010157 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase);
10158 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080010159 mWifiMulticastWakelockTimer = new StopwatchTimer(mClocks, null,
10160 WIFI_AGGREGATE_MULTICAST_ENABLED, null, mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -080010161 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase);
10162 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null, mOnBatteryTimeBase);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010163 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010164 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i, null,
Dianne Hackborn3251b902014-06-20 14:40:53 -070010165 mOnBatteryTimeBase);
10166 }
Joe Onoratoabded112016-02-08 16:49:39 -080010167 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
10168 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i, null,
10169 mOnBatteryTimeBase);
10170 }
10171 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
10172 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i, null,
10173 mOnBatteryTimeBase);
10174 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080010175 mWifiActiveTimer = new StopwatchTimer(mClocks, null, -900, null, mOnBatteryTimeBase);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080010176 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
10177 mGpsSignalQualityTimer[i] = new StopwatchTimer(mClocks, null, -1000-i, null,
10178 mOnBatteryTimeBase);
10179 }
Joe Onoratoabded112016-02-08 16:49:39 -080010180 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
10181 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
10182 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase);
10183 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase);
10184 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010185 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -070010186 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Mike Ma15313c92017-11-15 17:58:21 -080010187 mDischargeLightDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
10188 mDischargeDeepDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010189 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010190 mOnBattery = mOnBatteryInternal = false;
Joe Onoratoabded112016-02-08 16:49:39 -080010191 long uptime = mClocks.uptimeMillis() * 1000;
10192 long realtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010193 initTimes(uptime, realtime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070010194 mStartPlatformVersion = mEndPlatformVersion = Build.ID;
Evan Millar633a1742009-04-02 16:36:33 -070010195 mDischargeStartLevel = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010196 mDischargeUnplugLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010197 mDischargePlugLevel = -1;
Evan Millar633a1742009-04-02 16:36:33 -070010198 mDischargeCurrentLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010199 mCurrentBatteryLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010200 initDischarge();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010201 clearHistoryLocked();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010202 updateDailyDeadlineLocked();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010203 mPlatformIdleStateCallback = cb;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010204 mUserInfoProvider = userInfoProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010205 }
10206
10207 public BatteryStatsImpl(Parcel p) {
Joe Onoratoabded112016-02-08 16:49:39 -080010208 this(new SystemClocks(), p);
10209 }
10210
10211 public BatteryStatsImpl(Clocks clocks, Parcel p) {
10212 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070010213 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010214 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010215 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -070010216 mHandler = null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010217 mExternalSync = null;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080010218 mConstants = new Constants(mHandler);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010219 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010220 readFromParcel(p);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010221 mPlatformIdleStateCallback = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010222 }
10223
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010224 public void setPowerProfileLocked(PowerProfile profile) {
10225 mPowerProfile = profile;
Adam Lesinski6832f392015-09-05 18:05:40 -070010226
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010227 // We need to initialize the KernelCpuSpeedReaders to read from
10228 // the first cpu of each core. Once we have the PowerProfile, we have access to this
10229 // information.
10230 final int numClusters = mPowerProfile.getNumCpuClusters();
10231 mKernelCpuSpeedReaders = new KernelCpuSpeedReader[numClusters];
10232 int firstCpuOfCluster = 0;
10233 for (int i = 0; i < numClusters; i++) {
10234 final int numSpeedSteps = mPowerProfile.getNumSpeedStepsInCpuCluster(i);
10235 mKernelCpuSpeedReaders[i] = new KernelCpuSpeedReader(firstCpuOfCluster,
10236 numSpeedSteps);
10237 firstCpuOfCluster += mPowerProfile.getNumCoresInCpuCluster(i);
10238 }
Adam Lesinskif9b20a92016-06-17 17:30:01 -070010239
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010240 if (mEstimatedBatteryCapacity == -1) {
10241 // Initialize the estimated battery capacity to a known preset one.
10242 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
Adam Lesinskie08af192015-03-25 16:42:59 -070010243 }
10244 }
10245
Dianne Hackborn0d903a82010-09-07 23:51:03 -070010246 public void setCallback(BatteryCallback cb) {
10247 mCallback = cb;
10248 }
10249
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010250 public void setRadioScanningTimeoutLocked(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -070010251 if (mPhoneSignalScanningTimer != null) {
10252 mPhoneSignalScanningTimer.setTimeout(timeout);
10253 }
10254 }
10255
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070010256 public void setExternalStatsSyncLocked(ExternalStatsSync sync) {
10257 mExternalSync = sync;
10258 }
10259
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010260 public void updateDailyDeadlineLocked() {
10261 // Get the current time.
10262 long currentTime = mDailyStartTime = System.currentTimeMillis();
10263 Calendar calDeadline = Calendar.getInstance();
10264 calDeadline.setTimeInMillis(currentTime);
10265
10266 // Move time up to the next day, ranging from 1am to 3pm.
10267 calDeadline.set(Calendar.DAY_OF_YEAR, calDeadline.get(Calendar.DAY_OF_YEAR) + 1);
10268 calDeadline.set(Calendar.MILLISECOND, 0);
10269 calDeadline.set(Calendar.SECOND, 0);
10270 calDeadline.set(Calendar.MINUTE, 0);
10271 calDeadline.set(Calendar.HOUR_OF_DAY, 1);
10272 mNextMinDailyDeadline = calDeadline.getTimeInMillis();
10273 calDeadline.set(Calendar.HOUR_OF_DAY, 3);
10274 mNextMaxDailyDeadline = calDeadline.getTimeInMillis();
10275 }
10276
10277 public void recordDailyStatsIfNeededLocked(boolean settled) {
10278 long currentTime = System.currentTimeMillis();
10279 if (currentTime >= mNextMaxDailyDeadline) {
10280 recordDailyStatsLocked();
10281 } else if (settled && currentTime >= mNextMinDailyDeadline) {
10282 recordDailyStatsLocked();
10283 } else if (currentTime < (mDailyStartTime-(1000*60*60*24))) {
10284 recordDailyStatsLocked();
10285 }
10286 }
10287
10288 public void recordDailyStatsLocked() {
10289 DailyItem item = new DailyItem();
10290 item.mStartTime = mDailyStartTime;
10291 item.mEndTime = System.currentTimeMillis();
10292 boolean hasData = false;
10293 if (mDailyDischargeStepTracker.mNumStepDurations > 0) {
10294 hasData = true;
10295 item.mDischargeSteps = new LevelStepTracker(
10296 mDailyDischargeStepTracker.mNumStepDurations,
10297 mDailyDischargeStepTracker.mStepDurations);
10298 }
10299 if (mDailyChargeStepTracker.mNumStepDurations > 0) {
10300 hasData = true;
10301 item.mChargeSteps = new LevelStepTracker(
10302 mDailyChargeStepTracker.mNumStepDurations,
10303 mDailyChargeStepTracker.mStepDurations);
10304 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010305 if (mDailyPackageChanges != null) {
10306 hasData = true;
10307 item.mPackageChanges = mDailyPackageChanges;
10308 mDailyPackageChanges = null;
10309 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010310 mDailyDischargeStepTracker.init();
10311 mDailyChargeStepTracker.init();
10312 updateDailyDeadlineLocked();
10313
10314 if (hasData) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080010315 final long startTime = SystemClock.uptimeMillis();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010316 mDailyItems.add(item);
10317 while (mDailyItems.size() > MAX_DAILY_ITEMS) {
10318 mDailyItems.remove(0);
10319 }
10320 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
10321 try {
10322 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010010323 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010324 writeDailyItemsLocked(out);
Dianne Hackborne17b4452018-01-10 13:15:40 -080010325 final long initialTime = SystemClock.uptimeMillis() - startTime;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010326 BackgroundThread.getHandler().post(new Runnable() {
10327 @Override
10328 public void run() {
10329 synchronized (mCheckinFile) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080010330 final long startTime2 = SystemClock.uptimeMillis();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010331 FileOutputStream stream = null;
10332 try {
10333 stream = mDailyFile.startWrite();
10334 memStream.writeTo(stream);
10335 stream.flush();
10336 FileUtils.sync(stream);
10337 stream.close();
10338 mDailyFile.finishWrite(stream);
Dianne Hackborne17b4452018-01-10 13:15:40 -080010339 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
10340 "batterystats-daily",
10341 initialTime + SystemClock.uptimeMillis() - startTime2);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010342 } catch (IOException e) {
10343 Slog.w("BatteryStats",
10344 "Error writing battery daily items", e);
10345 mDailyFile.failWrite(stream);
10346 }
10347 }
10348 }
10349 });
10350 } catch (IOException e) {
10351 }
10352 }
10353 }
10354
10355 private void writeDailyItemsLocked(XmlSerializer out) throws IOException {
10356 StringBuilder sb = new StringBuilder(64);
10357 out.startDocument(null, true);
10358 out.startTag(null, "daily-items");
10359 for (int i=0; i<mDailyItems.size(); i++) {
10360 final DailyItem dit = mDailyItems.get(i);
10361 out.startTag(null, "item");
10362 out.attribute(null, "start", Long.toString(dit.mStartTime));
10363 out.attribute(null, "end", Long.toString(dit.mEndTime));
10364 writeDailyLevelSteps(out, "dis", dit.mDischargeSteps, sb);
10365 writeDailyLevelSteps(out, "chg", dit.mChargeSteps, sb);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010366 if (dit.mPackageChanges != null) {
10367 for (int j=0; j<dit.mPackageChanges.size(); j++) {
10368 PackageChange pc = dit.mPackageChanges.get(j);
10369 if (pc.mUpdate) {
10370 out.startTag(null, "upd");
10371 out.attribute(null, "pkg", pc.mPackageName);
Dianne Hackborn3accca02013-09-20 09:32:11 -070010372 out.attribute(null, "ver", Long.toString(pc.mVersionCode));
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010373 out.endTag(null, "upd");
10374 } else {
10375 out.startTag(null, "rem");
10376 out.attribute(null, "pkg", pc.mPackageName);
10377 out.endTag(null, "rem");
10378 }
10379 }
10380 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010381 out.endTag(null, "item");
10382 }
10383 out.endTag(null, "daily-items");
10384 out.endDocument();
10385 }
10386
10387 private void writeDailyLevelSteps(XmlSerializer out, String tag, LevelStepTracker steps,
10388 StringBuilder tmpBuilder) throws IOException {
10389 if (steps != null) {
10390 out.startTag(null, tag);
10391 out.attribute(null, "n", Integer.toString(steps.mNumStepDurations));
10392 for (int i=0; i<steps.mNumStepDurations; i++) {
10393 out.startTag(null, "s");
10394 tmpBuilder.setLength(0);
10395 steps.encodeEntryAt(i, tmpBuilder);
10396 out.attribute(null, "v", tmpBuilder.toString());
10397 out.endTag(null, "s");
10398 }
10399 out.endTag(null, tag);
10400 }
10401 }
10402
10403 public void readDailyStatsLocked() {
10404 Slog.d(TAG, "Reading daily items from " + mDailyFile.getBaseFile());
10405 mDailyItems.clear();
10406 FileInputStream stream;
10407 try {
10408 stream = mDailyFile.openRead();
10409 } catch (FileNotFoundException e) {
10410 return;
10411 }
10412 try {
10413 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010010414 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010415 readDailyItemsLocked(parser);
10416 } catch (XmlPullParserException e) {
10417 } finally {
10418 try {
10419 stream.close();
10420 } catch (IOException e) {
10421 }
10422 }
10423 }
10424
10425 private void readDailyItemsLocked(XmlPullParser parser) {
10426 try {
10427 int type;
10428 while ((type = parser.next()) != XmlPullParser.START_TAG
10429 && type != XmlPullParser.END_DOCUMENT) {
10430 ;
10431 }
10432
10433 if (type != XmlPullParser.START_TAG) {
10434 throw new IllegalStateException("no start tag found");
10435 }
10436
10437 int outerDepth = parser.getDepth();
10438 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10439 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10440 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10441 continue;
10442 }
10443
10444 String tagName = parser.getName();
10445 if (tagName.equals("item")) {
10446 readDailyItemTagLocked(parser);
10447 } else {
10448 Slog.w(TAG, "Unknown element under <daily-items>: "
10449 + parser.getName());
10450 XmlUtils.skipCurrentTag(parser);
10451 }
10452 }
10453
10454 } catch (IllegalStateException e) {
10455 Slog.w(TAG, "Failed parsing daily " + e);
10456 } catch (NullPointerException e) {
10457 Slog.w(TAG, "Failed parsing daily " + e);
10458 } catch (NumberFormatException e) {
10459 Slog.w(TAG, "Failed parsing daily " + e);
10460 } catch (XmlPullParserException e) {
10461 Slog.w(TAG, "Failed parsing daily " + e);
10462 } catch (IOException e) {
10463 Slog.w(TAG, "Failed parsing daily " + e);
10464 } catch (IndexOutOfBoundsException e) {
10465 Slog.w(TAG, "Failed parsing daily " + e);
10466 }
10467 }
10468
10469 void readDailyItemTagLocked(XmlPullParser parser) throws NumberFormatException,
10470 XmlPullParserException, IOException {
10471 DailyItem dit = new DailyItem();
10472 String attr = parser.getAttributeValue(null, "start");
10473 if (attr != null) {
10474 dit.mStartTime = Long.parseLong(attr);
10475 }
10476 attr = parser.getAttributeValue(null, "end");
10477 if (attr != null) {
10478 dit.mEndTime = Long.parseLong(attr);
10479 }
10480 int outerDepth = parser.getDepth();
10481 int type;
10482 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10483 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10484 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10485 continue;
10486 }
10487
10488 String tagName = parser.getName();
10489 if (tagName.equals("dis")) {
10490 readDailyItemTagDetailsLocked(parser, dit, false, "dis");
10491 } else if (tagName.equals("chg")) {
10492 readDailyItemTagDetailsLocked(parser, dit, true, "chg");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010493 } else if (tagName.equals("upd")) {
10494 if (dit.mPackageChanges == null) {
10495 dit.mPackageChanges = new ArrayList<>();
10496 }
10497 PackageChange pc = new PackageChange();
10498 pc.mUpdate = true;
10499 pc.mPackageName = parser.getAttributeValue(null, "pkg");
10500 String verStr = parser.getAttributeValue(null, "ver");
Dianne Hackborn3accca02013-09-20 09:32:11 -070010501 pc.mVersionCode = verStr != null ? Long.parseLong(verStr) : 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010502 dit.mPackageChanges.add(pc);
10503 XmlUtils.skipCurrentTag(parser);
10504 } else if (tagName.equals("rem")) {
10505 if (dit.mPackageChanges == null) {
10506 dit.mPackageChanges = new ArrayList<>();
10507 }
10508 PackageChange pc = new PackageChange();
10509 pc.mUpdate = false;
10510 pc.mPackageName = parser.getAttributeValue(null, "pkg");
10511 dit.mPackageChanges.add(pc);
10512 XmlUtils.skipCurrentTag(parser);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010513 } else {
10514 Slog.w(TAG, "Unknown element under <item>: "
10515 + parser.getName());
10516 XmlUtils.skipCurrentTag(parser);
10517 }
10518 }
10519 mDailyItems.add(dit);
10520 }
10521
10522 void readDailyItemTagDetailsLocked(XmlPullParser parser, DailyItem dit, boolean isCharge,
10523 String tag)
10524 throws NumberFormatException, XmlPullParserException, IOException {
10525 final String numAttr = parser.getAttributeValue(null, "n");
10526 if (numAttr == null) {
10527 Slog.w(TAG, "Missing 'n' attribute at " + parser.getPositionDescription());
10528 XmlUtils.skipCurrentTag(parser);
10529 return;
10530 }
10531 final int num = Integer.parseInt(numAttr);
10532 LevelStepTracker steps = new LevelStepTracker(num);
10533 if (isCharge) {
10534 dit.mChargeSteps = steps;
10535 } else {
10536 dit.mDischargeSteps = steps;
10537 }
10538 int i = 0;
10539 int outerDepth = parser.getDepth();
10540 int type;
10541 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10542 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10543 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10544 continue;
10545 }
10546
10547 String tagName = parser.getName();
10548 if ("s".equals(tagName)) {
10549 if (i < num) {
10550 String valueAttr = parser.getAttributeValue(null, "v");
10551 if (valueAttr != null) {
10552 steps.decodeEntryAt(i, valueAttr);
10553 i++;
10554 }
10555 }
10556 } else {
10557 Slog.w(TAG, "Unknown element under <" + tag + ">: "
10558 + parser.getName());
10559 XmlUtils.skipCurrentTag(parser);
10560 }
10561 }
10562 steps.mNumStepDurations = i;
10563 }
10564
10565 @Override
10566 public DailyItem getDailyItemLocked(int daysAgo) {
10567 int index = mDailyItems.size()-1-daysAgo;
10568 return index >= 0 ? mDailyItems.get(index) : null;
10569 }
10570
10571 @Override
10572 public long getCurrentDailyStartTime() {
10573 return mDailyStartTime;
10574 }
10575
10576 @Override
10577 public long getNextMinDailyDeadline() {
10578 return mNextMinDailyDeadline;
10579 }
10580
10581 @Override
10582 public long getNextMaxDailyDeadline() {
10583 return mNextMaxDailyDeadline;
10584 }
10585
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010586 @Override
10587 public boolean startIteratingOldHistoryLocked() {
10588 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
10589 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010590 if ((mHistoryIterator = mHistory) == null) {
10591 return false;
10592 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010593 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010594 mHistoryReadTmp.clear();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010595 mReadOverflow = false;
10596 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010597 return true;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010598 }
10599
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010600 @Override
10601 public boolean getNextOldHistoryLocked(HistoryItem out) {
10602 boolean end = mHistoryBuffer.dataPosition() >= mHistoryBuffer.dataSize();
10603 if (!end) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010604 readHistoryDelta(mHistoryBuffer, mHistoryReadTmp);
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010605 mReadOverflow |= mHistoryReadTmp.cmd == HistoryItem.CMD_OVERFLOW;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010606 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010607 HistoryItem cur = mHistoryIterator;
10608 if (cur == null) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010609 if (!mReadOverflow && !end) {
10610 Slog.w(TAG, "Old history ends before new history!");
10611 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010612 return false;
10613 }
10614 out.setTo(cur);
10615 mHistoryIterator = cur.next;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010616 if (!mReadOverflow) {
10617 if (end) {
10618 Slog.w(TAG, "New history ends before old history!");
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010619 } else if (!out.same(mHistoryReadTmp)) {
Dianne Hackborn8c841092013-06-24 13:46:13 -070010620 PrintWriter pw = new FastPrintWriter(new LogWriter(android.util.Log.WARN, TAG));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010621 pw.println("Histories differ!");
10622 pw.println("Old history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010623 (new HistoryPrinter()).printNextItem(pw, out, 0, false, true);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010624 pw.println("New history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010625 (new HistoryPrinter()).printNextItem(pw, mHistoryReadTmp, 0, false,
10626 true);
Dianne Hackborn8c841092013-06-24 13:46:13 -070010627 pw.flush();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010628 }
10629 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010630 return true;
10631 }
10632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010633 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010634 public void finishIteratingOldHistoryLocked() {
10635 mIteratingHistory = false;
10636 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010637 mHistoryIterator = null;
10638 }
10639
10640 public int getHistoryTotalSize() {
10641 return MAX_HISTORY_BUFFER;
10642 }
10643
10644 public int getHistoryUsedSize() {
10645 return mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010646 }
10647
10648 @Override
10649 public boolean startIteratingHistoryLocked() {
10650 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
10651 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010652 if (mHistoryBuffer.dataSize() <= 0) {
10653 return false;
10654 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010655 mHistoryBuffer.setDataPosition(0);
10656 mReadOverflow = false;
10657 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010658 mReadHistoryStrings = new String[mHistoryTagPool.size()];
10659 mReadHistoryUids = new int[mHistoryTagPool.size()];
10660 mReadHistoryChars = 0;
10661 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
10662 final HistoryTag tag = ent.getKey();
10663 final int idx = ent.getValue();
10664 mReadHistoryStrings[idx] = tag.string;
10665 mReadHistoryUids[idx] = tag.uid;
10666 mReadHistoryChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080010667 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010668 return true;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010669 }
10670
10671 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -080010672 public int getHistoryStringPoolSize() {
10673 return mReadHistoryStrings.length;
10674 }
10675
10676 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010677 public int getHistoryStringPoolBytes() {
10678 // Each entry is a fixed 12 bytes: 4 for index, 4 for uid, 4 for string size
10679 // Each string character is 2 bytes.
10680 return (mReadHistoryStrings.length * 12) + (mReadHistoryChars * 2);
10681 }
10682
10683 @Override
10684 public String getHistoryTagPoolString(int index) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080010685 return mReadHistoryStrings[index];
10686 }
10687
10688 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010689 public int getHistoryTagPoolUid(int index) {
10690 return mReadHistoryUids[index];
10691 }
10692
10693 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010694 public boolean getNextHistoryLocked(HistoryItem out) {
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010695 final int pos = mHistoryBuffer.dataPosition();
10696 if (pos == 0) {
10697 out.clear();
10698 }
10699 boolean end = pos >= mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010700 if (end) {
10701 return false;
10702 }
10703
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010704 final long lastRealtime = out.time;
10705 final long lastWalltime = out.currentTime;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010706 readHistoryDelta(mHistoryBuffer, out);
Dianne Hackborn37de0982014-05-09 09:32:18 -070010707 if (out.cmd != HistoryItem.CMD_CURRENT_TIME
10708 && out.cmd != HistoryItem.CMD_RESET && lastWalltime != 0) {
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010709 out.currentTime = lastWalltime + (out.time - lastRealtime);
10710 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010711 return true;
10712 }
10713
10714 @Override
10715 public void finishIteratingHistoryLocked() {
10716 mIteratingHistory = false;
10717 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn099bc622014-01-22 13:39:16 -080010718 mReadHistoryStrings = null;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010719 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010720
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010721 @Override
Dianne Hackbornb5e31652010-09-07 12:13:55 -070010722 public long getHistoryBaseTime() {
10723 return mHistoryBaseTime;
10724 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010725
Dianne Hackbornb5e31652010-09-07 12:13:55 -070010726 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010727 public int getStartCount() {
10728 return mStartCount;
10729 }
10730
10731 public boolean isOnBattery() {
10732 return mOnBattery;
10733 }
10734
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010735 public boolean isCharging() {
10736 return mCharging;
10737 }
10738
Mike Mac2f518a2017-09-19 16:06:03 -070010739 public boolean isScreenOn(int state) {
Chris Phoenix10a4a642017-09-25 13:21:00 -070010740 return state == Display.STATE_ON || state == Display.STATE_VR
10741 || state == Display.STATE_ON_SUSPEND;
Mike Mac2f518a2017-09-19 16:06:03 -070010742 }
10743
10744 public boolean isScreenOff(int state) {
10745 return state == Display.STATE_OFF;
10746 }
10747
10748 public boolean isScreenDoze(int state) {
10749 return state == Display.STATE_DOZE || state == Display.STATE_DOZE_SUSPEND;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010750 }
10751
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010752 void initTimes(long uptime, long realtime) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080010753 mStartClockTime = System.currentTimeMillis();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010754 mOnBatteryTimeBase.init(uptime, realtime);
10755 mOnBatteryScreenOffTimeBase.init(uptime, realtime);
Dianne Hackborn4590e522014-03-24 13:36:46 -070010756 mRealtime = 0;
10757 mUptime = 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010758 mRealtimeStart = realtime;
Dianne Hackborn4590e522014-03-24 13:36:46 -070010759 mUptimeStart = uptime;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010760 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010761
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010762 void initDischarge() {
10763 mLowDischargeAmountSinceCharge = 0;
10764 mHighDischargeAmountSinceCharge = 0;
10765 mDischargeAmountScreenOn = 0;
10766 mDischargeAmountScreenOnSinceCharge = 0;
10767 mDischargeAmountScreenOff = 0;
10768 mDischargeAmountScreenOffSinceCharge = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010769 mDischargeAmountScreenDoze = 0;
10770 mDischargeAmountScreenDozeSinceCharge = 0;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010771 mDischargeStepTracker.init();
10772 mChargeStepTracker.init();
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010773 mDischargeScreenOffCounter.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -070010774 mDischargeScreenDozeCounter.reset(false);
Mike Ma15313c92017-11-15 17:58:21 -080010775 mDischargeLightDozeCounter.reset(false);
10776 mDischargeDeepDozeCounter.reset(false);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010777 mDischargeCounter.reset(false);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010778 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010779
10780 public void resetAllStatsCmdLocked() {
10781 resetAllStatsLocked();
Joe Onoratoabded112016-02-08 16:49:39 -080010782 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -070010783 long uptime = mSecUptime * 1000;
Joe Onoratoabded112016-02-08 16:49:39 -080010784 long mSecRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010785 long realtime = mSecRealtime * 1000;
10786 mDischargeStartLevel = mHistoryCur.batteryLevel;
10787 pullPendingStateUpdatesLocked();
Dianne Hackborn40c87252014-03-19 16:55:40 -070010788 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010789 mDischargeCurrentLevel = mDischargeUnplugLevel = mDischargePlugLevel
10790 = mCurrentBatteryLevel = mHistoryCur.batteryLevel;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010791 mOnBatteryTimeBase.reset(uptime, realtime);
10792 mOnBatteryScreenOffTimeBase.reset(uptime, realtime);
10793 if ((mHistoryCur.states&HistoryItem.STATE_BATTERY_PLUGGED_FLAG) == 0) {
Mike Mac2f518a2017-09-19 16:06:03 -070010794 if (isScreenOn(mScreenState)) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010795 mDischargeScreenOnUnplugLevel = mHistoryCur.batteryLevel;
Mike Mac2f518a2017-09-19 16:06:03 -070010796 mDischargeScreenDozeUnplugLevel = 0;
10797 mDischargeScreenOffUnplugLevel = 0;
10798 } else if (isScreenDoze(mScreenState)) {
10799 mDischargeScreenOnUnplugLevel = 0;
10800 mDischargeScreenDozeUnplugLevel = mHistoryCur.batteryLevel;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010801 mDischargeScreenOffUnplugLevel = 0;
10802 } else {
10803 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010804 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010805 mDischargeScreenOffUnplugLevel = mHistoryCur.batteryLevel;
10806 }
10807 mDischargeAmountScreenOn = 0;
10808 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010809 mDischargeAmountScreenDoze = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010810 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070010811 initActiveHistoryEventsLocked(mSecRealtime, mSecUptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010812 }
10813
10814 private void resetAllStatsLocked() {
Adam Lesinski8ce36942016-05-26 16:05:35 -070010815 final long uptimeMillis = mClocks.uptimeMillis();
10816 final long elapsedRealtimeMillis = mClocks.elapsedRealtime();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010817 mStartCount = 0;
Adam Lesinski8ce36942016-05-26 16:05:35 -070010818 initTimes(uptimeMillis * 1000, elapsedRealtimeMillis * 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010819 mScreenOnTimer.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -070010820 mScreenDozeTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010821 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010822 mScreenBrightnessTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010823 }
Adam Lesinski1a76a622016-06-22 10:28:47 -070010824
10825 if (mPowerProfile != null) {
10826 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
10827 } else {
10828 mEstimatedBatteryCapacity = -1;
10829 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070010830 mMinLearnedBatteryCapacity = -1;
10831 mMaxLearnedBatteryCapacity = -1;
Jeff Browne95c3cd2014-05-02 16:59:26 -070010832 mInteractiveTimer.reset(false);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070010833 mPowerSaveModeEnabledTimer.reset(false);
Adam Lesinski8ce36942016-05-26 16:05:35 -070010834 mLastIdleTimeStart = elapsedRealtimeMillis;
Dianne Hackborn08c47a52015-10-15 12:38:14 -070010835 mLongestLightIdleTime = 0;
10836 mLongestFullIdleTime = 0;
10837 mDeviceIdleModeLightTimer.reset(false);
10838 mDeviceIdleModeFullTimer.reset(false);
10839 mDeviceLightIdlingTimer.reset(false);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010840 mDeviceIdlingTimer.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010841 mPhoneOnTimer.reset(false);
10842 mAudioOnTimer.reset(false);
10843 mVideoOnTimer.reset(false);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070010844 mFlashlightOnTimer.reset(false);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070010845 mCameraOnTimer.reset(false);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010846 mBluetoothScanTimer.reset(false);
Wink Saville52840902011-02-18 12:40:47 -080010847 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010848 mPhoneSignalStrengthsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010849 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010850 mPhoneSignalScanningTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010851 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010852 mPhoneDataConnectionsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010853 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010854 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010855 mNetworkByteActivityCounters[i].reset(false);
10856 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010857 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010858 mMobileRadioActiveTimer.reset(false);
10859 mMobileRadioActivePerAppTimer.reset(false);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010860 mMobileRadioActiveAdjustedTime.reset(false);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080010861 mMobileRadioActiveUnknownTime.reset(false);
10862 mMobileRadioActiveUnknownCount.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010863 mWifiOnTimer.reset(false);
10864 mGlobalWifiRunningTimer.reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010865 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010866 mWifiStateTimer[i].reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010867 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070010868 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
10869 mWifiSupplStateTimer[i].reset(false);
10870 }
10871 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
10872 mWifiSignalStrengthsTimer[i].reset(false);
10873 }
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080010874 mWifiMulticastWakelockTimer.reset(false);
Siddharth Rayb50a6842017-12-14 15:15:28 -080010875 mWifiActiveTimer.reset(false);
10876 mWifiActivity.reset(false);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080010877 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
10878 mGpsSignalQualityTimer[i].reset(false);
10879 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010880 mBluetoothActivity.reset(false);
10881 mModemActivity.reset(false);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080010882 mNumConnectivityChange = mLoadedNumConnectivityChange = mUnpluggedNumConnectivityChange = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010883
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010884 for (int i=0; i<mUidStats.size(); i++) {
Bookatz993a0be2017-07-21 09:03:23 -070010885 if (mUidStats.valueAt(i).reset(uptimeMillis * 1000, elapsedRealtimeMillis * 1000)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010886 mUidStats.remove(mUidStats.keyAt(i));
10887 i--;
10888 }
10889 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010890
Bookatz50df7112017-08-04 14:53:26 -070010891 if (mRpmStats.size() > 0) {
10892 for (SamplingTimer timer : mRpmStats.values()) {
10893 mOnBatteryTimeBase.remove(timer);
10894 }
10895 mRpmStats.clear();
10896 }
10897 if (mScreenOffRpmStats.size() > 0) {
10898 for (SamplingTimer timer : mScreenOffRpmStats.values()) {
10899 mOnBatteryScreenOffTimeBase.remove(timer);
10900 }
10901 mScreenOffRpmStats.clear();
10902 }
10903
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010904 if (mKernelWakelockStats.size() > 0) {
10905 for (SamplingTimer timer : mKernelWakelockStats.values()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010906 mOnBatteryScreenOffTimeBase.remove(timer);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010907 }
10908 mKernelWakelockStats.clear();
10909 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010910
James Carr3a226052016-07-01 14:49:52 -070010911 if (mKernelMemoryStats.size() > 0) {
10912 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
10913 mOnBatteryTimeBase.remove(mKernelMemoryStats.valueAt(i));
10914 }
10915 mKernelMemoryStats.clear();
10916 }
10917
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010918 if (mWakeupReasonStats.size() > 0) {
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070010919 for (SamplingTimer timer : mWakeupReasonStats.values()) {
10920 mOnBatteryTimeBase.remove(timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010921 }
10922 mWakeupReasonStats.clear();
10923 }
10924
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080010925 mLastHistoryStepDetails = null;
10926 mLastStepCpuUserTime = mLastStepCpuSystemTime = 0;
10927 mCurStepCpuUserTime = mCurStepCpuSystemTime = 0;
10928 mLastStepCpuUserTime = mCurStepCpuUserTime = 0;
10929 mLastStepCpuSystemTime = mCurStepCpuSystemTime = 0;
10930 mLastStepStatUserTime = mCurStepStatUserTime = 0;
10931 mLastStepStatSystemTime = mCurStepStatSystemTime = 0;
10932 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime = 0;
10933 mLastStepStatIrqTime = mCurStepStatIrqTime = 0;
10934 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime = 0;
10935 mLastStepStatIdleTime = mCurStepStatIdleTime = 0;
10936
Mike Ma234d1822018-03-13 18:53:21 -070010937 mNumAllUidCpuTimeReads = 0;
10938 mNumUidsRemoved = 0;
10939
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010940 initDischarge();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010941
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010942 clearHistoryLocked();
10943 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010944
Dianne Hackborn40c87252014-03-19 16:55:40 -070010945 private void initActiveHistoryEventsLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010946 for (int i=0; i<HistoryItem.EVENT_COUNT; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010947 if (!mRecordAllHistory && i == HistoryItem.EVENT_PROC) {
10948 // Not recording process starts/stops.
10949 continue;
10950 }
Dianne Hackborn37de0982014-05-09 09:32:18 -070010951 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(i);
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010952 if (active == null) {
10953 continue;
10954 }
Dianne Hackborn37de0982014-05-09 09:32:18 -070010955 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
10956 SparseIntArray uids = ent.getValue();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010957 for (int j=0; j<uids.size(); j++) {
Dianne Hackborn37de0982014-05-09 09:32:18 -070010958 addHistoryEventLocked(elapsedRealtimeMs, uptimeMs, i, ent.getKey(),
10959 uids.keyAt(j));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010960 }
10961 }
10962 }
10963 }
10964
Mike Mac2f518a2017-09-19 16:06:03 -070010965 void updateDischargeScreenLevelsLocked(int oldState, int newState) {
10966 updateOldDischargeScreenLevelLocked(oldState);
10967 updateNewDischargeScreenLevelLocked(newState);
10968 }
10969
10970 private void updateOldDischargeScreenLevelLocked(int state) {
10971 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010972 int diff = mDischargeScreenOnUnplugLevel - mDischargeCurrentLevel;
10973 if (diff > 0) {
10974 mDischargeAmountScreenOn += diff;
10975 mDischargeAmountScreenOnSinceCharge += diff;
10976 }
Mike Mac2f518a2017-09-19 16:06:03 -070010977 } else if (isScreenDoze(state)) {
10978 int diff = mDischargeScreenDozeUnplugLevel - mDischargeCurrentLevel;
10979 if (diff > 0) {
10980 mDischargeAmountScreenDoze += diff;
10981 mDischargeAmountScreenDozeSinceCharge += diff;
10982 }
10983 } else if (isScreenOff(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010984 int diff = mDischargeScreenOffUnplugLevel - mDischargeCurrentLevel;
10985 if (diff > 0) {
10986 mDischargeAmountScreenOff += diff;
10987 mDischargeAmountScreenOffSinceCharge += diff;
10988 }
10989 }
Mike Mac2f518a2017-09-19 16:06:03 -070010990 }
10991
10992 private void updateNewDischargeScreenLevelLocked(int state) {
10993 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010994 mDischargeScreenOnUnplugLevel = mDischargeCurrentLevel;
10995 mDischargeScreenOffUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010996 mDischargeScreenDozeUnplugLevel = 0;
10997 } else if (isScreenDoze(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010998 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010999 mDischargeScreenDozeUnplugLevel = mDischargeCurrentLevel;
11000 mDischargeScreenOffUnplugLevel = 0;
11001 } else if (isScreenOff(state)) {
11002 mDischargeScreenOnUnplugLevel = 0;
11003 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011004 mDischargeScreenOffUnplugLevel = mDischargeCurrentLevel;
11005 }
11006 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011007
Dianne Hackborna7c837f2014-01-15 16:20:44 -080011008 public void pullPendingStateUpdatesLocked() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -080011009 if (mOnBatteryInternal) {
Mike Mac2f518a2017-09-19 16:06:03 -070011010 updateDischargeScreenLevelsLocked(mScreenState, mScreenState);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080011011 }
Dianne Hackborna7c837f2014-01-15 16:20:44 -080011012 }
11013
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011014 private final NetworkStatsFactory mNetworkStatsFactory = new NetworkStatsFactory();
11015 private final Pools.Pool<NetworkStats> mNetworkStatsPool = new Pools.SynchronizedPool<>(6);
11016
11017 private final Object mWifiNetworkLock = new Object();
11018
11019 @GuardedBy("mWifiNetworkLock")
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011020 private String[] mWifiIfaces = EmptyArray.STRING;
11021
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011022 @GuardedBy("mWifiNetworkLock")
11023 private NetworkStats mLastWifiNetworkStats = new NetworkStats(0, -1);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011024
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011025 private final Object mModemNetworkLock = new Object();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011026
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011027 @GuardedBy("mModemNetworkLock")
11028 private String[] mModemIfaces = EmptyArray.STRING;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011029
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011030 @GuardedBy("mModemNetworkLock")
11031 private NetworkStats mLastModemNetworkStats = new NetworkStats(0, -1);
11032
11033 private NetworkStats readNetworkStatsLocked(String[] ifaces) {
11034 try {
11035 if (!ArrayUtils.isEmpty(ifaces)) {
11036 return mNetworkStatsFactory.readNetworkStatsDetail(NetworkStats.UID_ALL, ifaces,
11037 NetworkStats.TAG_NONE, mNetworkStatsPool.acquire());
11038 }
11039 } catch (IOException e) {
11040 Slog.e(TAG, "failed to read network stats for ifaces: " + Arrays.toString(ifaces));
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011041 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011042 return null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011043 }
11044
Chenjie Yu89083392018-01-11 14:53:31 -080011045 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011046 * Distribute WiFi energy info and network traffic to apps.
11047 * @param info The energy information from the WiFi controller.
11048 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011049 public void updateWifiState(@Nullable final WifiActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011050 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011051 Slog.d(TAG, "Updating wifi stats: " + Arrays.toString(mWifiIfaces));
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011052 }
11053
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011054 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070011055 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011056 synchronized (mWifiNetworkLock) {
11057 final NetworkStats latestStats = readNetworkStatsLocked(mWifiIfaces);
11058 if (latestStats != null) {
11059 delta = NetworkStats.subtract(latestStats, mLastWifiNetworkStats, null, null,
11060 mNetworkStatsPool.acquire());
11061 mNetworkStatsPool.release(mLastWifiNetworkStats);
11062 mLastWifiNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070011063 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011064 }
11065
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011066 synchronized (this) {
11067 if (!mOnBatteryInternal) {
11068 if (delta != null) {
11069 mNetworkStatsPool.release(delta);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011070 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011071 return;
11072 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011073
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011074 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
11075 SparseLongArray rxPackets = new SparseLongArray();
11076 SparseLongArray txPackets = new SparseLongArray();
11077 long totalTxPackets = 0;
11078 long totalRxPackets = 0;
11079 if (delta != null) {
11080 NetworkStats.Entry entry = new NetworkStats.Entry();
11081 final int size = delta.size();
11082 for (int i = 0; i < size; i++) {
11083 entry = delta.getValues(i, entry);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011084
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011085 if (DEBUG_ENERGY) {
11086 Slog.d(TAG, "Wifi uid " + entry.uid + ": delta rx=" + entry.rxBytes
11087 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
11088 + " txPackets=" + entry.txPackets);
11089 }
11090
11091 if (entry.rxBytes == 0 && entry.txBytes == 0) {
11092 // Skip the lookup below since there is no work to do.
11093 continue;
11094 }
11095
11096 final Uid u = getUidStatsLocked(mapUid(entry.uid));
11097 if (entry.rxBytes != 0) {
11098 u.noteNetworkActivityLocked(NETWORK_WIFI_RX_DATA, entry.rxBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -080011099 entry.rxPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011100 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11101 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_RX_DATA, entry.rxBytes,
11102 entry.rxPackets);
11103 }
11104 mNetworkByteActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
11105 entry.rxBytes);
11106 mNetworkPacketActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
11107 entry.rxPackets);
11108
11109 rxPackets.put(u.getUid(), entry.rxPackets);
11110
11111 // Sum the total number of packets so that the Rx Power can
11112 // be evenly distributed amongst the apps.
11113 totalRxPackets += entry.rxPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -080011114 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011115
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011116 if (entry.txBytes != 0) {
11117 u.noteNetworkActivityLocked(NETWORK_WIFI_TX_DATA, entry.txBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -080011118 entry.txPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011119 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11120 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_TX_DATA, entry.txBytes,
11121 entry.txPackets);
11122 }
11123 mNetworkByteActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
11124 entry.txBytes);
11125 mNetworkPacketActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
11126 entry.txPackets);
11127
11128 txPackets.put(u.getUid(), entry.txPackets);
11129
11130 // Sum the total number of packets so that the Tx Power can
11131 // be evenly distributed amongst the apps.
11132 totalTxPackets += entry.txPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -080011133 }
Adam Lesinskiba88e682015-12-08 12:06:55 -080011134 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011135 mNetworkStatsPool.release(delta);
11136 delta = null;
Adam Lesinskie08af192015-03-25 16:42:59 -070011137 }
11138
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011139 if (info != null) {
11140 mHasWifiReporting = true;
Adam Lesinskie08af192015-03-25 16:42:59 -070011141
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011142 // Measured in mAms
11143 final long txTimeMs = info.getControllerTxTimeMillis();
11144 final long rxTimeMs = info.getControllerRxTimeMillis();
Siddharth Rayb50a6842017-12-14 15:15:28 -080011145 final long scanTimeMs = info.getControllerScanTimeMillis();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011146 final long idleTimeMs = info.getControllerIdleTimeMillis();
11147 final long totalTimeMs = txTimeMs + rxTimeMs + idleTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -070011148
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011149 long leftOverRxTimeMs = rxTimeMs;
11150 long leftOverTxTimeMs = txTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -070011151
Adam Lesinskie08af192015-03-25 16:42:59 -070011152 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011153 Slog.d(TAG, "------ BEGIN WiFi power blaming ------");
11154 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
11155 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
11156 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms");
11157 Slog.d(TAG, " Total Time: " + totalTimeMs + " ms");
Siddharth Rayb50a6842017-12-14 15:15:28 -080011158 Slog.d(TAG, " Scan Time: " + scanTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070011159 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011160
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011161 long totalWifiLockTimeMs = 0;
11162 long totalScanTimeMs = 0;
11163
11164 // On the first pass, collect some totals so that we can normalize power
11165 // calculations if we need to.
11166 final int uidStatsSize = mUidStats.size();
11167 for (int i = 0; i < uidStatsSize; i++) {
11168 final Uid uid = mUidStats.valueAt(i);
11169
11170 // Sum the total scan power for all apps.
11171 totalScanTimeMs += uid.mWifiScanTimer.getTimeSinceMarkLocked(
11172 elapsedRealtimeMs * 1000) / 1000;
11173
11174 // Sum the total time holding wifi lock for all apps.
11175 totalWifiLockTimeMs += uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
11176 elapsedRealtimeMs * 1000) / 1000;
11177 }
11178
11179 if (DEBUG_ENERGY && totalScanTimeMs > rxTimeMs) {
11180 Slog.d(TAG,
11181 " !Estimated scan time > Actual rx time (" + totalScanTimeMs + " ms > "
11182 + rxTimeMs + " ms). Normalizing scan time.");
11183 }
11184 if (DEBUG_ENERGY && totalScanTimeMs > txTimeMs) {
11185 Slog.d(TAG,
11186 " !Estimated scan time > Actual tx time (" + totalScanTimeMs + " ms > "
11187 + txTimeMs + " ms). Normalizing scan time.");
11188 }
11189
11190 // Actually assign and distribute power usage to apps.
11191 for (int i = 0; i < uidStatsSize; i++) {
11192 final Uid uid = mUidStats.valueAt(i);
11193
11194 long scanTimeSinceMarkMs = uid.mWifiScanTimer.getTimeSinceMarkLocked(
11195 elapsedRealtimeMs * 1000) / 1000;
11196 if (scanTimeSinceMarkMs > 0) {
11197 // Set the new mark so that next time we get new data since this point.
11198 uid.mWifiScanTimer.setMark(elapsedRealtimeMs);
11199
11200 long scanRxTimeSinceMarkMs = scanTimeSinceMarkMs;
11201 long scanTxTimeSinceMarkMs = scanTimeSinceMarkMs;
11202
11203 // Our total scan time is more than the reported Tx/Rx time.
11204 // This is possible because the cost of a scan is approximate.
11205 // Let's normalize the result so that we evenly blame each app
11206 // scanning.
11207 //
11208 // This means that we may have apps that transmitted/received packets not be
11209 // blamed for this, but this is fine as scans are relatively more expensive.
11210 if (totalScanTimeMs > rxTimeMs) {
11211 scanRxTimeSinceMarkMs = (rxTimeMs * scanRxTimeSinceMarkMs) /
11212 totalScanTimeMs;
11213 }
11214 if (totalScanTimeMs > txTimeMs) {
11215 scanTxTimeSinceMarkMs = (txTimeMs * scanTxTimeSinceMarkMs) /
11216 totalScanTimeMs;
11217 }
11218
11219 if (DEBUG_ENERGY) {
11220 Slog.d(TAG, " ScanTime for UID " + uid.getUid() + ": Rx:"
11221 + scanRxTimeSinceMarkMs + " ms Tx:"
11222 + scanTxTimeSinceMarkMs + " ms)");
11223 }
11224
11225 ControllerActivityCounterImpl activityCounter =
11226 uid.getOrCreateWifiControllerActivityLocked();
11227 activityCounter.getRxTimeCounter().addCountLocked(scanRxTimeSinceMarkMs);
11228 activityCounter.getTxTimeCounters()[0].addCountLocked(
11229 scanTxTimeSinceMarkMs);
11230 leftOverRxTimeMs -= scanRxTimeSinceMarkMs;
11231 leftOverTxTimeMs -= scanTxTimeSinceMarkMs;
11232 }
11233
11234 // Distribute evenly the power consumed while Idle to each app holding a WiFi
11235 // lock.
11236 final long wifiLockTimeSinceMarkMs =
11237 uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
11238 elapsedRealtimeMs * 1000) / 1000;
11239 if (wifiLockTimeSinceMarkMs > 0) {
11240 // Set the new mark so that next time we get new data since this point.
11241 uid.mFullWifiLockTimer.setMark(elapsedRealtimeMs);
11242
11243 final long myIdleTimeMs = (wifiLockTimeSinceMarkMs * idleTimeMs)
11244 / totalWifiLockTimeMs;
11245 if (DEBUG_ENERGY) {
11246 Slog.d(TAG, " IdleTime for UID " + uid.getUid() + ": "
11247 + myIdleTimeMs + " ms");
11248 }
11249 uid.getOrCreateWifiControllerActivityLocked().getIdleTimeCounter()
11250 .addCountLocked(myIdleTimeMs);
11251 }
11252 }
11253
Adam Lesinskie08af192015-03-25 16:42:59 -070011254 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011255 Slog.d(TAG, " New RxPower: " + leftOverRxTimeMs + " ms");
11256 Slog.d(TAG, " New TxPower: " + leftOverTxTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070011257 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011258
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011259 // Distribute the remaining Tx power appropriately between all apps that transmitted
11260 // packets.
11261 for (int i = 0; i < txPackets.size(); i++) {
11262 final Uid uid = getUidStatsLocked(txPackets.keyAt(i));
11263 final long myTxTimeMs = (txPackets.valueAt(i) * leftOverTxTimeMs)
11264 / totalTxPackets;
11265 if (DEBUG_ENERGY) {
11266 Slog.d(TAG, " TxTime for UID " + uid.getUid() + ": " + myTxTimeMs + " ms");
11267 }
11268 uid.getOrCreateWifiControllerActivityLocked().getTxTimeCounters()[0]
11269 .addCountLocked(myTxTimeMs);
11270 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011271
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011272 // Distribute the remaining Rx power appropriately between all apps that received
11273 // packets.
11274 for (int i = 0; i < rxPackets.size(); i++) {
11275 final Uid uid = getUidStatsLocked(rxPackets.keyAt(i));
11276 final long myRxTimeMs = (rxPackets.valueAt(i) * leftOverRxTimeMs)
11277 / totalRxPackets;
11278 if (DEBUG_ENERGY) {
11279 Slog.d(TAG, " RxTime for UID " + uid.getUid() + ": " + myRxTimeMs + " ms");
11280 }
11281 uid.getOrCreateWifiControllerActivityLocked().getRxTimeCounter()
11282 .addCountLocked(myRxTimeMs);
11283 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011284
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011285 // Any left over power use will be picked up by the WiFi category in BatteryStatsHelper.
11286
11287
11288 // Update WiFi controller stats.
11289 mWifiActivity.getRxTimeCounter().addCountLocked(info.getControllerRxTimeMillis());
11290 mWifiActivity.getTxTimeCounters()[0].addCountLocked(
11291 info.getControllerTxTimeMillis());
Siddharth Rayb50a6842017-12-14 15:15:28 -080011292 mWifiActivity.getScanTimeCounter().addCountLocked(
11293 info.getControllerScanTimeMillis());
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011294 mWifiActivity.getIdleTimeCounter().addCountLocked(
11295 info.getControllerIdleTimeMillis());
11296
11297 // POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11298 final double opVolt = mPowerProfile.getAveragePower(
11299 PowerProfile.POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11300 if (opVolt != 0) {
11301 // We store the power drain as mAms.
11302 mWifiActivity.getPowerCounter().addCountLocked(
11303 (long) (info.getControllerEnergyUsed() / opVolt));
11304 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011305 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011306 }
11307 }
11308
Chenjie Yu89083392018-01-11 14:53:31 -080011309 private ModemActivityInfo mLastModemActivityInfo =
11310 new ModemActivityInfo(0, 0, 0, new int[0], 0, 0);
11311
Chenjie Yua54e54d2018-02-14 20:12:52 -080011312 private ModemActivityInfo getDeltaModemActivityInfo(ModemActivityInfo activityInfo) {
11313 if (activityInfo == null) {
11314 return null;
11315 }
11316 int[] txTimeMs = new int[ModemActivityInfo.TX_POWER_LEVELS];
11317 for (int i = 0; i < ModemActivityInfo.TX_POWER_LEVELS; i++) {
11318 txTimeMs[i] = activityInfo.getTxTimeMillis()[i]
11319 - mLastModemActivityInfo.getTxTimeMillis()[i];
11320 }
11321 ModemActivityInfo deltaInfo = new ModemActivityInfo(activityInfo.getTimestamp(),
11322 activityInfo.getSleepTimeMillis() - mLastModemActivityInfo.getSleepTimeMillis(),
11323 activityInfo.getIdleTimeMillis() - mLastModemActivityInfo.getIdleTimeMillis(),
11324 txTimeMs,
11325 activityInfo.getRxTimeMillis() - mLastModemActivityInfo.getRxTimeMillis(),
11326 activityInfo.getEnergyUsed() - mLastModemActivityInfo.getEnergyUsed());
11327 mLastModemActivityInfo = activityInfo;
11328 return deltaInfo;
11329 }
11330
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011331 /**
11332 * Distribute Cell radio energy info and network traffic to apps.
11333 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011334 public void updateMobileRadioState(@Nullable final ModemActivityInfo activityInfo) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011335 if (DEBUG_ENERGY) {
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011336 Slog.d(TAG, "Updating mobile radio stats with " + activityInfo);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011337 }
Chenjie Yua54e54d2018-02-14 20:12:52 -080011338 ModemActivityInfo deltaInfo = getDeltaModemActivityInfo(activityInfo);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011339
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011340 // Add modem tx power to history.
Chenjie Yua54e54d2018-02-14 20:12:52 -080011341 addModemTxPowerToHistory(deltaInfo);
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011342
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011343 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070011344 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011345 synchronized (mModemNetworkLock) {
11346 final NetworkStats latestStats = readNetworkStatsLocked(mModemIfaces);
11347 if (latestStats != null) {
11348 delta = NetworkStats.subtract(latestStats, mLastModemNetworkStats, null, null,
11349 mNetworkStatsPool.acquire());
11350 mNetworkStatsPool.release(mLastModemNetworkStats);
11351 mLastModemNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070011352 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011353 }
11354
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011355 synchronized (this) {
11356 if (!mOnBatteryInternal) {
11357 if (delta != null) {
11358 mNetworkStatsPool.release(delta);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011359 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011360 return;
Adam Lesinskie08af192015-03-25 16:42:59 -070011361 }
11362
Chenjie Yua54e54d2018-02-14 20:12:52 -080011363 if (deltaInfo != null) {
Siddharth Ray2038af82018-01-17 17:40:26 -080011364 mHasModemReporting = true;
11365 mModemActivity.getIdleTimeCounter().addCountLocked(
Chenjie Yua54e54d2018-02-14 20:12:52 -080011366 deltaInfo.getIdleTimeMillis());
Siddharth Rayed754702018-02-15 12:44:37 -080011367 mModemActivity.getSleepTimeCounter().addCountLocked(
11368 deltaInfo.getSleepTimeMillis());
Chenjie Yua54e54d2018-02-14 20:12:52 -080011369 mModemActivity.getRxTimeCounter().addCountLocked(deltaInfo.getRxTimeMillis());
Siddharth Ray2038af82018-01-17 17:40:26 -080011370 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
11371 mModemActivity.getTxTimeCounters()[lvl]
Chenjie Yua54e54d2018-02-14 20:12:52 -080011372 .addCountLocked(deltaInfo.getTxTimeMillis()[lvl]);
Siddharth Ray2038af82018-01-17 17:40:26 -080011373 }
11374
11375 // POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11376 final double opVolt = mPowerProfile.getAveragePower(
11377 PowerProfile.POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11378 if (opVolt != 0) {
11379 double energyUsed =
Chenjie Yua54e54d2018-02-14 20:12:52 -080011380 deltaInfo.getSleepTimeMillis() *
Siddharth Ray2038af82018-01-17 17:40:26 -080011381 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_SLEEP)
Chenjie Yua54e54d2018-02-14 20:12:52 -080011382 + deltaInfo.getIdleTimeMillis() *
Siddharth Ray2038af82018-01-17 17:40:26 -080011383 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_IDLE)
Chenjie Yua54e54d2018-02-14 20:12:52 -080011384 + deltaInfo.getRxTimeMillis() *
Siddharth Ray2038af82018-01-17 17:40:26 -080011385 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_RX);
Chenjie Yua54e54d2018-02-14 20:12:52 -080011386 int[] txTimeMs = deltaInfo.getTxTimeMillis();
Chenjie Yu89083392018-01-11 14:53:31 -080011387 for (int i = 0; i < Math.min(txTimeMs.length,
Chenjie Yua54e54d2018-02-14 20:12:52 -080011388 SignalStrength.NUM_SIGNAL_STRENGTH_BINS); i++) {
Chenjie Yu89083392018-01-11 14:53:31 -080011389 energyUsed += txTimeMs[i] * mPowerProfile.getAveragePower(
Chenjie Yua54e54d2018-02-14 20:12:52 -080011390 PowerProfile.POWER_MODEM_CONTROLLER_TX, i);
Siddharth Ray2038af82018-01-17 17:40:26 -080011391 }
11392
11393 // We store the power drain as mAms.
11394 mModemActivity.getPowerCounter().addCountLocked((long) energyUsed);
11395 }
11396 }
11397
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070011398 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011399 long radioTime = mMobileRadioActivePerAppTimer.getTimeSinceMarkLocked(
11400 elapsedRealtimeMs * 1000);
11401 mMobileRadioActivePerAppTimer.setMark(elapsedRealtimeMs);
11402
11403 long totalRxPackets = 0;
11404 long totalTxPackets = 0;
11405 if (delta != null) {
11406 NetworkStats.Entry entry = new NetworkStats.Entry();
11407 final int size = delta.size();
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011408 for (int i = 0; i < size; i++) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011409 entry = delta.getValues(i, entry);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011410 if (entry.rxPackets == 0 && entry.txPackets == 0) {
11411 continue;
11412 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011413
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011414 if (DEBUG_ENERGY) {
11415 Slog.d(TAG, "Mobile uid " + entry.uid + ": delta rx=" + entry.rxBytes
11416 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
11417 + " txPackets=" + entry.txPackets);
11418 }
11419
11420 totalRxPackets += entry.rxPackets;
11421 totalTxPackets += entry.txPackets;
11422
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011423 final Uid u = getUidStatsLocked(mapUid(entry.uid));
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011424 u.noteNetworkActivityLocked(NETWORK_MOBILE_RX_DATA, entry.rxBytes,
11425 entry.rxPackets);
11426 u.noteNetworkActivityLocked(NETWORK_MOBILE_TX_DATA, entry.txBytes,
11427 entry.txPackets);
11428 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11429 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_RX_DATA,
11430 entry.rxBytes, entry.rxPackets);
11431 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_TX_DATA,
11432 entry.txBytes, entry.txPackets);
11433 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011434
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011435 mNetworkByteActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
11436 entry.rxBytes);
11437 mNetworkByteActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
11438 entry.txBytes);
11439 mNetworkPacketActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
11440 entry.rxPackets);
11441 mNetworkPacketActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
11442 entry.txPackets);
11443 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011444
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011445 // Now distribute proportional blame to the apps that did networking.
11446 long totalPackets = totalRxPackets + totalTxPackets;
11447 if (totalPackets > 0) {
11448 for (int i = 0; i < size; i++) {
11449 entry = delta.getValues(i, entry);
11450 if (entry.rxPackets == 0 && entry.txPackets == 0) {
11451 continue;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011452 }
11453
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011454 final Uid u = getUidStatsLocked(mapUid(entry.uid));
11455
11456 // Distribute total radio active time in to this app.
11457 final long appPackets = entry.rxPackets + entry.txPackets;
11458 final long appRadioTime = (radioTime * appPackets) / totalPackets;
11459 u.noteMobileRadioActiveTimeLocked(appRadioTime);
11460
11461 // Remove this app from the totals, so that we don't lose any time
11462 // due to rounding.
11463 radioTime -= appRadioTime;
11464 totalPackets -= appPackets;
11465
Chenjie Yua54e54d2018-02-14 20:12:52 -080011466 if (deltaInfo != null) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011467 ControllerActivityCounterImpl activityCounter =
11468 u.getOrCreateModemControllerActivityLocked();
11469 if (totalRxPackets > 0 && entry.rxPackets > 0) {
Chenjie Yua54e54d2018-02-14 20:12:52 -080011470 final long rxMs = (entry.rxPackets * deltaInfo.getRxTimeMillis())
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011471 / totalRxPackets;
11472 activityCounter.getRxTimeCounter().addCountLocked(rxMs);
11473 }
11474
11475 if (totalTxPackets > 0 && entry.txPackets > 0) {
11476 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
11477 long txMs =
Chenjie Yua54e54d2018-02-14 20:12:52 -080011478 entry.txPackets * deltaInfo.getTxTimeMillis()[lvl];
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011479 txMs /= totalTxPackets;
11480 activityCounter.getTxTimeCounters()[lvl].addCountLocked(txMs);
11481 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011482 }
11483 }
11484 }
11485 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011486
11487 if (radioTime > 0) {
11488 // Whoops, there is some radio time we can't blame on an app!
11489 mMobileRadioActiveUnknownTime.addCountLocked(radioTime);
11490 mMobileRadioActiveUnknownCount.addCountLocked(1);
11491 }
11492
11493 mNetworkStatsPool.release(delta);
11494 delta = null;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011495 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011496 }
11497 }
11498
11499 /**
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011500 * Add modem tx power to history
11501 * Device is said to be in high cellular transmit power when it has spent most of the transmit
11502 * time at the highest power level.
11503 * @param activityInfo
11504 */
Siddharth Raya67fb562018-02-28 13:46:16 -080011505 private synchronized void addModemTxPowerToHistory(final ModemActivityInfo activityInfo) {
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011506 if (activityInfo == null) {
11507 return;
11508 }
11509 int[] txTimeMs = activityInfo.getTxTimeMillis();
11510 if (txTimeMs == null || txTimeMs.length != ModemActivityInfo.TX_POWER_LEVELS) {
11511 return;
11512 }
11513 final long elapsedRealtime = mClocks.elapsedRealtime();
11514 final long uptime = mClocks.uptimeMillis();
11515 int levelMaxTimeSpent = 0;
11516 for (int i = 1; i < txTimeMs.length; i++) {
11517 if (txTimeMs[i] > txTimeMs[levelMaxTimeSpent]) {
11518 levelMaxTimeSpent = i;
11519 }
11520 }
11521 if (levelMaxTimeSpent == ModemActivityInfo.TX_POWER_LEVELS - 1) {
11522 if (!mIsCellularTxPowerHigh) {
11523 mHistoryCur.states2 |= HistoryItem.STATE2_CELLULAR_HIGH_TX_POWER_FLAG;
11524 addHistoryRecordLocked(elapsedRealtime, uptime);
11525 mIsCellularTxPowerHigh = true;
11526 }
11527 return;
11528 }
11529 if (mIsCellularTxPowerHigh) {
11530 mHistoryCur.states2 &= ~HistoryItem.STATE2_CELLULAR_HIGH_TX_POWER_FLAG;
11531 addHistoryRecordLocked(elapsedRealtime, uptime);
11532 mIsCellularTxPowerHigh = false;
11533 }
11534 return;
11535 }
11536
Mike Ma561a8d92018-03-20 18:24:05 -070011537 private final class BluetoothActivityInfoCache {
11538 long idleTimeMs;
11539 long rxTimeMs;
11540 long txTimeMs;
11541 long energy;
11542
11543 SparseLongArray uidRxBytes = new SparseLongArray();
11544 SparseLongArray uidTxBytes = new SparseLongArray();
11545
11546 void set(BluetoothActivityEnergyInfo info) {
11547 idleTimeMs = info.getControllerIdleTimeMillis();
11548 rxTimeMs = info.getControllerRxTimeMillis();
11549 txTimeMs = info.getControllerTxTimeMillis();
11550 energy = info.getControllerEnergyUsed();
11551 if (info.getUidTraffic() != null) {
11552 for (UidTraffic traffic : info.getUidTraffic()) {
11553 uidRxBytes.put(traffic.getUid(), traffic.getRxBytes());
11554 uidTxBytes.put(traffic.getUid(), traffic.getTxBytes());
11555 }
11556 }
11557 }
11558 }
11559
11560 private final BluetoothActivityInfoCache mLastBluetoothActivityInfo
11561 = new BluetoothActivityInfoCache();
11562
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011563 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011564 * Distribute Bluetooth energy info and network traffic to apps.
Mike Ma561a8d92018-03-20 18:24:05 -070011565 *
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011566 * @param info The energy information from the bluetooth controller.
11567 */
11568 public void updateBluetoothStateLocked(@Nullable final BluetoothActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011569 if (DEBUG_ENERGY) {
Adam Lesinski50e47602015-12-04 17:04:54 -080011570 Slog.d(TAG, "Updating bluetooth stats: " + info);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011571 }
11572
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011573 if (info == null || !mOnBatteryInternal) {
11574 return;
11575 }
Adam Lesinskie283d332015-04-16 12:29:25 -070011576
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011577 mHasBluetoothReporting = true;
11578
Bookatz867c0d72017-03-07 18:23:42 -080011579 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Mike Ma561a8d92018-03-20 18:24:05 -070011580 final long rxTimeMs =
11581 info.getControllerRxTimeMillis() - mLastBluetoothActivityInfo.rxTimeMs;
11582 final long txTimeMs =
11583 info.getControllerTxTimeMillis() - mLastBluetoothActivityInfo.txTimeMs;
11584 final long idleTimeMs =
11585 info.getControllerIdleTimeMillis() - mLastBluetoothActivityInfo.idleTimeMs;
11586
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011587 if (DEBUG_ENERGY) {
11588 Slog.d(TAG, "------ BEGIN BLE power blaming ------");
11589 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
11590 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
Chenjie Yu89083392018-01-11 14:53:31 -080011591 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms");
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011592 }
11593
11594 long totalScanTimeMs = 0;
11595
11596 final int uidCount = mUidStats.size();
11597 for (int i = 0; i < uidCount; i++) {
11598 final Uid u = mUidStats.valueAt(i);
11599 if (u.mBluetoothScanTimer == null) {
11600 continue;
Adam Lesinskie283d332015-04-16 12:29:25 -070011601 }
Adam Lesinski50e47602015-12-04 17:04:54 -080011602
Bookatzaa4594a2017-03-24 12:39:56 -070011603 totalScanTimeMs += u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011604 elapsedRealtimeMs * 1000) / 1000;
11605 }
11606
11607 final boolean normalizeScanRxTime = (totalScanTimeMs > rxTimeMs);
11608 final boolean normalizeScanTxTime = (totalScanTimeMs > txTimeMs);
11609
11610 if (DEBUG_ENERGY) {
11611 Slog.d(TAG, "Normalizing scan power for RX=" + normalizeScanRxTime
11612 + " TX=" + normalizeScanTxTime);
11613 }
11614
11615 long leftOverRxTimeMs = rxTimeMs;
11616 long leftOverTxTimeMs = txTimeMs;
11617
11618 for (int i = 0; i < uidCount; i++) {
11619 final Uid u = mUidStats.valueAt(i);
11620 if (u.mBluetoothScanTimer == null) {
11621 continue;
11622 }
11623
Bookatzaa4594a2017-03-24 12:39:56 -070011624 long scanTimeSinceMarkMs = u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011625 elapsedRealtimeMs * 1000) / 1000;
11626 if (scanTimeSinceMarkMs > 0) {
11627 // Set the new mark so that next time we get new data since this point.
11628 u.mBluetoothScanTimer.setMark(elapsedRealtimeMs);
11629
11630 long scanTimeRxSinceMarkMs = scanTimeSinceMarkMs;
11631 long scanTimeTxSinceMarkMs = scanTimeSinceMarkMs;
11632
11633 if (normalizeScanRxTime) {
11634 // Scan time is longer than the total rx time in the controller,
11635 // so distribute the scan time proportionately. This means regular traffic
11636 // will not blamed, but scans are more expensive anyways.
11637 scanTimeRxSinceMarkMs = (rxTimeMs * scanTimeRxSinceMarkMs) / totalScanTimeMs;
11638 }
11639
11640 if (normalizeScanTxTime) {
11641 // Scan time is longer than the total tx time in the controller,
11642 // so distribute the scan time proportionately. This means regular traffic
11643 // will not blamed, but scans are more expensive anyways.
11644 scanTimeTxSinceMarkMs = (txTimeMs * scanTimeTxSinceMarkMs) / totalScanTimeMs;
11645 }
11646
11647 final ControllerActivityCounterImpl counter =
11648 u.getOrCreateBluetoothControllerActivityLocked();
11649 counter.getRxTimeCounter().addCountLocked(scanTimeRxSinceMarkMs);
11650 counter.getTxTimeCounters()[0].addCountLocked(scanTimeTxSinceMarkMs);
11651
11652 leftOverRxTimeMs -= scanTimeRxSinceMarkMs;
11653 leftOverTxTimeMs -= scanTimeTxSinceMarkMs;
11654 }
11655 }
11656
11657 if (DEBUG_ENERGY) {
Mike Ma561a8d92018-03-20 18:24:05 -070011658 Slog.d(TAG, "Left over time for traffic RX=" + leftOverRxTimeMs + " TX="
11659 + leftOverTxTimeMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011660 }
11661
11662 //
11663 // Now distribute blame to apps that did bluetooth traffic.
11664 //
11665
11666 long totalTxBytes = 0;
11667 long totalRxBytes = 0;
11668
11669 final UidTraffic[] uidTraffic = info.getUidTraffic();
Mike Ma561a8d92018-03-20 18:24:05 -070011670 final int numUids = uidTraffic != null ? uidTraffic.length : 0;
11671 for (int i = 0; i < numUids; i++) {
11672 final UidTraffic traffic = uidTraffic[i];
11673 final long rxBytes = traffic.getRxBytes() - mLastBluetoothActivityInfo.uidRxBytes.get(
11674 traffic.getUid());
11675 final long txBytes = traffic.getTxBytes() - mLastBluetoothActivityInfo.uidTxBytes.get(
11676 traffic.getUid());
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011677
11678 // Add to the global counters.
Mike Ma561a8d92018-03-20 18:24:05 -070011679 mNetworkByteActivityCounters[NETWORK_BT_RX_DATA].addCountLocked(rxBytes);
11680 mNetworkByteActivityCounters[NETWORK_BT_TX_DATA].addCountLocked(txBytes);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011681
11682 // Add to the UID counters.
11683 final Uid u = getUidStatsLocked(mapUid(traffic.getUid()));
Mike Ma561a8d92018-03-20 18:24:05 -070011684 u.noteNetworkActivityLocked(NETWORK_BT_RX_DATA, rxBytes, 0);
11685 u.noteNetworkActivityLocked(NETWORK_BT_TX_DATA, txBytes, 0);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011686
11687 // Calculate the total traffic.
Mike Ma561a8d92018-03-20 18:24:05 -070011688 totalRxBytes += rxBytes;
11689 totalTxBytes += txBytes;
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011690 }
11691
Mike Ma561a8d92018-03-20 18:24:05 -070011692 if ((totalTxBytes != 0 || totalRxBytes != 0) && (leftOverRxTimeMs != 0
11693 || leftOverTxTimeMs != 0)) {
11694 for (int i = 0; i < numUids; i++) {
11695 final UidTraffic traffic = uidTraffic[i];
11696 final int uid = traffic.getUid();
11697 final long rxBytes =
11698 traffic.getRxBytes() - mLastBluetoothActivityInfo.uidRxBytes.get(uid);
11699 final long txBytes =
11700 traffic.getTxBytes() - mLastBluetoothActivityInfo.uidTxBytes.get(uid);
Adam Lesinski50e47602015-12-04 17:04:54 -080011701
Mike Ma561a8d92018-03-20 18:24:05 -070011702 final Uid u = getUidStatsLocked(mapUid(uid));
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011703 final ControllerActivityCounterImpl counter =
11704 u.getOrCreateBluetoothControllerActivityLocked();
11705
Mike Ma561a8d92018-03-20 18:24:05 -070011706 if (totalRxBytes > 0 && rxBytes > 0) {
11707 final long timeRxMs = (leftOverRxTimeMs * rxBytes) / totalRxBytes;
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011708 if (DEBUG_ENERGY) {
Mike Ma561a8d92018-03-20 18:24:05 -070011709 Slog.d(TAG, "UID=" + uid + " rx_bytes=" + rxBytes + " rx_time=" + timeRxMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011710 }
11711 counter.getRxTimeCounter().addCountLocked(timeRxMs);
11712 leftOverRxTimeMs -= timeRxMs;
11713 }
11714
Mike Ma561a8d92018-03-20 18:24:05 -070011715 if (totalTxBytes > 0 && txBytes > 0) {
11716 final long timeTxMs = (leftOverTxTimeMs * txBytes) / totalTxBytes;
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011717 if (DEBUG_ENERGY) {
Mike Ma561a8d92018-03-20 18:24:05 -070011718 Slog.d(TAG, "UID=" + uid + " tx_bytes=" + txBytes + " tx_time=" + timeTxMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011719 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011720 counter.getTxTimeCounters()[0].addCountLocked(timeTxMs);
11721 leftOverTxTimeMs -= timeTxMs;
11722 }
Adam Lesinski50e47602015-12-04 17:04:54 -080011723 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011724 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011725
Chenjie Yu89083392018-01-11 14:53:31 -080011726 mBluetoothActivity.getRxTimeCounter().addCountLocked(rxTimeMs);
11727 mBluetoothActivity.getTxTimeCounters()[0].addCountLocked(txTimeMs);
11728 mBluetoothActivity.getIdleTimeCounter().addCountLocked(idleTimeMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011729
11730 // POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11731 final double opVolt = mPowerProfile.getAveragePower(
11732 PowerProfile.POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11733 if (opVolt != 0) {
11734 // We store the power drain as mAms.
11735 mBluetoothActivity.getPowerCounter().addCountLocked(
Mike Ma561a8d92018-03-20 18:24:05 -070011736 (long) ((info.getControllerEnergyUsed() - mLastBluetoothActivityInfo.energy)
11737 / opVolt));
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011738 }
Mike Ma561a8d92018-03-20 18:24:05 -070011739 mLastBluetoothActivityInfo.set(info);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011740 }
11741
11742 /**
Bookatz0b8a0502017-09-13 11:51:52 -070011743 * Read and record Resource Power Manager (RPM) state and voter times.
11744 * If RPM stats were fetched more recently than RPM_STATS_UPDATE_FREQ_MS ago, uses the old data
11745 * instead of fetching it anew.
Bookatz50df7112017-08-04 14:53:26 -070011746 */
11747 public void updateRpmStatsLocked() {
11748 if (mPlatformIdleStateCallback == null) return;
Bookatz0b8a0502017-09-13 11:51:52 -070011749 long now = SystemClock.elapsedRealtime();
11750 if (now - mLastRpmStatsUpdateTimeMs >= RPM_STATS_UPDATE_FREQ_MS) {
11751 mPlatformIdleStateCallback.fillLowPowerStats(mTmpRpmStats);
11752 mLastRpmStatsUpdateTimeMs = now;
11753 }
Bookatz50df7112017-08-04 14:53:26 -070011754
11755 for (Map.Entry<String, RpmStats.PowerStatePlatformSleepState> pstate
11756 : mTmpRpmStats.mPlatformLowPowerStats.entrySet()) {
11757
11758 // Update values for this platform state.
11759 final String pName = pstate.getKey();
11760 final long pTimeUs = pstate.getValue().mTimeMs * 1000;
11761 final int pCount = pstate.getValue().mCount;
11762 getRpmTimerLocked(pName).update(pTimeUs, pCount);
Bookatz82b341172017-09-07 19:06:08 -070011763 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11764 getScreenOffRpmTimerLocked(pName).update(pTimeUs, pCount);
11765 }
Bookatz50df7112017-08-04 14:53:26 -070011766
11767 // Update values for each voter of this platform state.
11768 for (Map.Entry<String, RpmStats.PowerStateElement> voter
11769 : pstate.getValue().mVoters.entrySet()) {
11770 final String vName = pName + "." + voter.getKey();
11771 final long vTimeUs = voter.getValue().mTimeMs * 1000;
11772 final int vCount = voter.getValue().mCount;
11773 getRpmTimerLocked(vName).update(vTimeUs, vCount);
Bookatz82b341172017-09-07 19:06:08 -070011774 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11775 getScreenOffRpmTimerLocked(vName).update(vTimeUs, vCount);
11776 }
Bookatz50df7112017-08-04 14:53:26 -070011777 }
11778 }
11779
11780 for (Map.Entry<String, RpmStats.PowerStateSubsystem> subsys
11781 : mTmpRpmStats.mSubsystemLowPowerStats.entrySet()) {
11782
11783 final String subsysName = subsys.getKey();
11784 for (Map.Entry<String, RpmStats.PowerStateElement> sstate
11785 : subsys.getValue().mStates.entrySet()) {
11786 final String name = subsysName + "." + sstate.getKey();
11787 final long timeUs = sstate.getValue().mTimeMs * 1000;
11788 final int count = sstate.getValue().mCount;
11789 getRpmTimerLocked(name).update(timeUs, count);
Bookatz82b341172017-09-07 19:06:08 -070011790 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11791 getScreenOffRpmTimerLocked(name).update(timeUs, count);
11792 }
Bookatz50df7112017-08-04 14:53:26 -070011793 }
11794 }
11795 }
11796
11797 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011798 * Read and distribute kernel wake lock use across apps.
11799 */
11800 public void updateKernelWakelocksLocked() {
11801 final KernelWakelockStats wakelockStats = mKernelWakelockReader.readKernelWakelockStats(
11802 mTmpWakelockStats);
11803 if (wakelockStats == null) {
11804 // Not crashing might make board bringup easier.
11805 Slog.w(TAG, "Couldn't get kernel wake lock stats");
11806 return;
11807 }
11808
11809 for (Map.Entry<String, KernelWakelockStats.Entry> ent : wakelockStats.entrySet()) {
11810 String name = ent.getKey();
11811 KernelWakelockStats.Entry kws = ent.getValue();
11812
11813 SamplingTimer kwlt = mKernelWakelockStats.get(name);
11814 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -070011815 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011816 mKernelWakelockStats.put(name, kwlt);
11817 }
Adam Lesinskid84ad302016-05-17 18:31:02 -070011818
Adam Lesinski757c6ea2016-04-21 09:55:41 -070011819 kwlt.update(kws.mTotalTime, kws.mCount);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011820 kwlt.setUpdateVersion(kws.mVersion);
11821 }
11822
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011823 int numWakelocksSetStale = 0;
Adam Lesinskid84ad302016-05-17 18:31:02 -070011824 // Set timers to stale if they didn't appear in /d/wakeup_sources (or /proc/wakelocks)
11825 // this time.
11826 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
11827 SamplingTimer st = ent.getValue();
11828 if (st.getUpdateVersion() != wakelockStats.kernelWakelockVersion) {
11829 st.endSample();
11830 numWakelocksSetStale++;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011831 }
11832 }
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011833
Adam Lesinskid84ad302016-05-17 18:31:02 -070011834 // Record whether we've seen a non-zero time (for debugging b/22716723).
11835 if (wakelockStats.isEmpty()) {
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011836 Slog.wtf(TAG, "All kernel wakelocks had time of zero");
11837 }
11838
11839 if (numWakelocksSetStale == mKernelWakelockStats.size()) {
11840 Slog.wtf(TAG, "All kernel wakelocks were set stale. new version=" +
11841 wakelockStats.kernelWakelockVersion);
11842 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011843 }
11844
Adam Lesinski72478f02015-06-17 15:39:43 -070011845 // We use an anonymous class to access these variables,
11846 // so they can't live on the stack or they'd have to be
11847 // final MutableLong objects (more allocations).
11848 // Used in updateCpuTimeLocked().
11849 long mTempTotalCpuUserTimeUs;
11850 long mTempTotalCpuSystemTimeUs;
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011851 long[][] mWakeLockAllocationsUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070011852
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011853 /**
James Carr3a226052016-07-01 14:49:52 -070011854 * Reads the newest memory stats from the kernel.
11855 */
11856 public void updateKernelMemoryBandwidthLocked() {
11857 mKernelMemoryBandwidthStats.updateStats();
11858 LongSparseLongArray bandwidthEntries = mKernelMemoryBandwidthStats.getBandwidthEntries();
11859 final int bandwidthEntryCount = bandwidthEntries.size();
11860 int index;
11861 for (int i = 0; i < bandwidthEntryCount; i++) {
11862 SamplingTimer timer;
11863 if ((index = mKernelMemoryStats.indexOfKey(bandwidthEntries.keyAt(i))) >= 0) {
11864 timer = mKernelMemoryStats.valueAt(index);
11865 } else {
11866 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
11867 mKernelMemoryStats.put(bandwidthEntries.keyAt(i), timer);
11868 }
11869 timer.update(bandwidthEntries.valueAt(i), 1);
11870 if (DEBUG_MEMORY) {
11871 Slog.d(TAG, String.format("Added entry %d and updated timer to: "
11872 + "mUnpluggedReportedTotalTime %d size %d", bandwidthEntries.keyAt(i),
11873 mKernelMemoryStats.get(
11874 bandwidthEntries.keyAt(i)).mUnpluggedReportedTotalTime,
11875 mKernelMemoryStats.size()));
11876 }
11877 }
11878 }
11879
Sudheer Shankac57729a2018-02-09 15:44:42 -080011880 public boolean isOnBatteryLocked() {
11881 return mOnBatteryTimeBase.isRunning();
11882 }
11883
11884 public boolean isOnBatteryScreenOffLocked() {
11885 return mOnBatteryScreenOffTimeBase.isRunning();
11886 }
11887
James Carr3a226052016-07-01 14:49:52 -070011888 /**
Adam Lesinski72478f02015-06-17 15:39:43 -070011889 * Read and distribute CPU usage across apps. If their are partial wakelocks being held
11890 * and we are on battery with screen off, we give more of the cpu time to those apps holding
11891 * wakelocks. If the screen is on, we just assign the actual cpu time an app used.
Sudheer Shankac57729a2018-02-09 15:44:42 -080011892 * It's possible this will be invoked after the internal battery/screen states are updated, so
11893 * passing the appropriate battery/screen states to try attribute the cpu times to correct
11894 * buckets.
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011895 */
Andreas Gampe3f24e692018-02-05 13:24:28 -080011896 @GuardedBy("this")
Sudheer Shankac57729a2018-02-09 15:44:42 -080011897 public void updateCpuTimeLocked(boolean onBattery, boolean onBatteryScreenOff) {
Adam Lesinski52290c9c2015-09-21 16:54:52 -070011898 if (mPowerProfile == null) {
11899 return;
11900 }
11901
Adam Lesinski72478f02015-06-17 15:39:43 -070011902 if (DEBUG_ENERGY_CPU) {
11903 Slog.d(TAG, "!Cpu updating!");
11904 }
11905
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011906 if (mCpuFreqs == null) {
11907 mCpuFreqs = mKernelUidCpuFreqTimeReader.readFreqs(mPowerProfile);
11908 }
11909
Sudheer Shanka38383232017-07-25 09:55:03 -070011910 // Calculate the wakelocks we have to distribute amongst. The system is excluded as it is
11911 // usually holding the wakelock on behalf of an app.
11912 // And Only distribute cpu power to wakelocks if the screen is off and we're on battery.
11913 ArrayList<StopwatchTimer> partialTimersToConsider = null;
Sudheer Shankac57729a2018-02-09 15:44:42 -080011914 if (onBatteryScreenOff) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011915 partialTimersToConsider = new ArrayList<>();
11916 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070011917 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070011918 // Since the collection and blaming of wakelocks can be scheduled to run after
11919 // some delay, the mPartialTimers list may have new entries. We can't blame
11920 // the newly added timer for past cpu time, so we only consider timers that
11921 // were present for one round of collection. Once a timer has gone through
11922 // a round of collection, its mInList field is set to true.
Adam Lesinski72478f02015-06-17 15:39:43 -070011923 if (timer.mInList && timer.mUid != null && timer.mUid.mUid != Process.SYSTEM_UID) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011924 partialTimersToConsider.add(timer);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011925 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011926 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011927 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011928 markPartialTimersAsEligible();
Adam Lesinski72478f02015-06-17 15:39:43 -070011929
Sudheer Shanka38383232017-07-25 09:55:03 -070011930 // When the battery is not on, we don't attribute the cpu times to any timers but we still
11931 // need to take the snapshots.
Sudheer Shankac57729a2018-02-09 15:44:42 -080011932 if (!onBattery) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011933 mKernelUidCpuTimeReader.readDelta(null);
11934 mKernelUidCpuFreqTimeReader.readDelta(null);
Mike Ma234d1822018-03-13 18:53:21 -070011935 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080011936 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
11937 mKernelUidCpuActiveTimeReader.readDelta(null);
11938 mKernelUidCpuClusterTimeReader.readDelta(null);
Mike Ma234d1822018-03-13 18:53:21 -070011939 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080011940 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011941 for (int cluster = mKernelCpuSpeedReaders.length - 1; cluster >= 0; --cluster) {
11942 mKernelCpuSpeedReaders[cluster].readDelta();
11943 }
11944 return;
11945 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011946
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070011947 mUserInfoProvider.refreshUserIds();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011948 final SparseLongArray updatedUids = mKernelUidCpuFreqTimeReader.perClusterTimesAvailable()
11949 ? null : new SparseLongArray();
Sudheer Shankac57729a2018-02-09 15:44:42 -080011950 readKernelUidCpuTimesLocked(partialTimersToConsider, updatedUids, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011951 // updatedUids=null means /proc/uid_time_in_state provides snapshots of per-cluster cpu
11952 // freqs, so no need to approximate these values.
11953 if (updatedUids != null) {
Sudheer Shankac57729a2018-02-09 15:44:42 -080011954 updateClusterSpeedTimes(updatedUids, onBattery);
Sudheer Shanka671985f2017-05-19 11:33:42 -070011955 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080011956 readKernelUidCpuFreqTimesLocked(partialTimersToConsider, onBattery, onBatteryScreenOff);
Mike Ma234d1822018-03-13 18:53:21 -070011957 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080011958 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
Sudheer Shankac57729a2018-02-09 15:44:42 -080011959 readKernelUidCpuActiveTimesLocked(onBattery);
11960 readKernelUidCpuClusterTimesLocked(onBattery);
Mike Ma234d1822018-03-13 18:53:21 -070011961 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080011962 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011963 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070011964
Sudheer Shanka38383232017-07-25 09:55:03 -070011965 /**
11966 * Mark the current partial timers as gone through a collection so that they will be
11967 * considered in the next cpu times distribution to wakelock holders.
11968 */
11969 @VisibleForTesting
11970 public void markPartialTimersAsEligible() {
11971 if (ArrayUtils.referenceEquals(mPartialTimers, mLastPartialTimers)) {
11972 // No difference, so each timer is now considered for the next collection.
11973 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
11974 mPartialTimers.get(i).mInList = true;
11975 }
11976 } else {
11977 // The lists are different, meaning we added (or removed a timer) since the last
11978 // collection.
11979 for (int i = mLastPartialTimers.size() - 1; i >= 0; --i) {
11980 mLastPartialTimers.get(i).mInList = false;
11981 }
11982 mLastPartialTimers.clear();
Adam Lesinski72478f02015-06-17 15:39:43 -070011983
Sudheer Shanka38383232017-07-25 09:55:03 -070011984 // Mark the current timers as gone through a collection.
11985 final int numPartialTimers = mPartialTimers.size();
11986 for (int i = 0; i < numPartialTimers; ++i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070011987 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070011988 timer.mInList = true;
11989 mLastPartialTimers.add(timer);
Adam Lesinski72478f02015-06-17 15:39:43 -070011990 }
11991 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011992 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011993
Sudheer Shanka38383232017-07-25 09:55:03 -070011994 /**
11995 * Take snapshot of cpu times (aggregated over all uids) at different frequencies and
11996 * calculate cpu times spent by each uid at different frequencies.
11997 *
11998 * @param updatedUids The uids for which times spent at different frequencies are calculated.
11999 */
12000 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012001 public void updateClusterSpeedTimes(@NonNull SparseLongArray updatedUids, boolean onBattery) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070012002 long totalCpuClustersTimeMs = 0;
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012003 // Read the time spent for each cluster at various cpu frequencies.
Sudheer Shankaaf857412017-07-21 00:14:24 -070012004 final long[][] clusterSpeedTimesMs = new long[mKernelCpuSpeedReaders.length][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012005 for (int cluster = 0; cluster < mKernelCpuSpeedReaders.length; cluster++) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070012006 clusterSpeedTimesMs[cluster] = mKernelCpuSpeedReaders[cluster].readDelta();
12007 if (clusterSpeedTimesMs[cluster] != null) {
12008 for (int speed = clusterSpeedTimesMs[cluster].length - 1; speed >= 0; --speed) {
12009 totalCpuClustersTimeMs += clusterSpeedTimesMs[cluster][speed];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012010 }
12011 }
12012 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070012013 if (totalCpuClustersTimeMs != 0) {
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012014 // We have cpu times per freq aggregated over all uids but we need the times per uid.
12015 // So, we distribute total time spent by an uid to different cpu freqs based on the
12016 // amount of time cpu was running at that freq.
12017 final int updatedUidsCount = updatedUids.size();
12018 for (int i = 0; i < updatedUidsCount; ++i) {
12019 final Uid u = getUidStatsLocked(updatedUids.keyAt(i));
Sudheer Shankaaf857412017-07-21 00:14:24 -070012020 final long appCpuTimeUs = updatedUids.valueAt(i);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012021 // Add the cpu speeds to this UID.
12022 final int numClusters = mPowerProfile.getNumCpuClusters();
Sudheer Shanka38383232017-07-25 09:55:03 -070012023 if (u.mCpuClusterSpeedTimesUs == null ||
12024 u.mCpuClusterSpeedTimesUs.length != numClusters) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070012025 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012026 }
12027
Sudheer Shankaaf857412017-07-21 00:14:24 -070012028 for (int cluster = 0; cluster < clusterSpeedTimesMs.length; cluster++) {
12029 final int speedsInCluster = clusterSpeedTimesMs[cluster].length;
12030 if (u.mCpuClusterSpeedTimesUs[cluster] == null || speedsInCluster !=
12031 u.mCpuClusterSpeedTimesUs[cluster].length) {
12032 u.mCpuClusterSpeedTimesUs[cluster]
12033 = new LongSamplingCounter[speedsInCluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012034 }
12035
Sudheer Shankaaf857412017-07-21 00:14:24 -070012036 final LongSamplingCounter[] cpuSpeeds = u.mCpuClusterSpeedTimesUs[cluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012037 for (int speed = 0; speed < speedsInCluster; speed++) {
12038 if (cpuSpeeds[speed] == null) {
12039 cpuSpeeds[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
12040 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070012041 cpuSpeeds[speed].addCountLocked(appCpuTimeUs
12042 * clusterSpeedTimesMs[cluster][speed]
Sudheer Shankac57729a2018-02-09 15:44:42 -080012043 / totalCpuClustersTimeMs, onBattery);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012044 }
12045 }
12046 }
12047 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012048 }
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012049
Sudheer Shanka38383232017-07-25 09:55:03 -070012050 /**
12051 * Take a snapshot of the cpu times spent by each uid and update the corresponding counters.
12052 * If {@param partialTimers} is not null and empty, then we assign a portion of cpu times to
12053 * wakelock holders.
12054 *
12055 * @param partialTimers The wakelock holders among which the cpu times will be distributed.
12056 * @param updatedUids If not null, then the uids found in the snapshot will be added to this.
12057 */
12058 @VisibleForTesting
12059 public void readKernelUidCpuTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers,
Sudheer Shankac57729a2018-02-09 15:44:42 -080012060 @Nullable SparseLongArray updatedUids, boolean onBattery) {
Sudheer Shanka38383232017-07-25 09:55:03 -070012061 mTempTotalCpuUserTimeUs = mTempTotalCpuSystemTimeUs = 0;
12062 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
12063 final long startTimeMs = mClocks.uptimeMillis();
Adam Lesinski72478f02015-06-17 15:39:43 -070012064
Sudheer Shanka38383232017-07-25 09:55:03 -070012065 mKernelUidCpuTimeReader.readDelta((uid, userTimeUs, systemTimeUs) -> {
12066 uid = mapUid(uid);
12067 if (Process.isIsolated(uid)) {
12068 // This could happen if the isolated uid mapping was removed before that process
12069 // was actually killed.
12070 mKernelUidCpuTimeReader.removeUid(uid);
12071 Slog.d(TAG, "Got readings for an isolated uid with no mapping: " + uid);
12072 return;
12073 }
12074 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12075 Slog.d(TAG, "Got readings for an invalid user's uid " + uid);
12076 mKernelUidCpuTimeReader.removeUid(uid);
12077 return;
12078 }
12079 final Uid u = getUidStatsLocked(uid);
12080
12081 // Accumulate the total system and user time.
12082 mTempTotalCpuUserTimeUs += userTimeUs;
12083 mTempTotalCpuSystemTimeUs += systemTimeUs;
12084
12085 StringBuilder sb = null;
12086 if (DEBUG_ENERGY_CPU) {
12087 sb = new StringBuilder();
12088 sb.append(" got time for uid=").append(u.mUid).append(": u=");
12089 TimeUtils.formatDuration(userTimeUs / 1000, sb);
12090 sb.append(" s=");
12091 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
12092 sb.append("\n");
12093 }
12094
12095 if (numWakelocks > 0) {
12096 // We have wakelocks being held, so only give a portion of the
12097 // time to the process. The rest will be distributed among wakelock
12098 // holders.
12099 userTimeUs = (userTimeUs * WAKE_LOCK_WEIGHT) / 100;
12100 systemTimeUs = (systemTimeUs * WAKE_LOCK_WEIGHT) / 100;
12101 }
12102
12103 if (sb != null) {
12104 sb.append(" adding to uid=").append(u.mUid).append(": u=");
12105 TimeUtils.formatDuration(userTimeUs / 1000, sb);
12106 sb.append(" s=");
12107 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
12108 Slog.d(TAG, sb.toString());
12109 }
12110
Sudheer Shankac57729a2018-02-09 15:44:42 -080012111 u.mUserCpuTime.addCountLocked(userTimeUs, onBattery);
12112 u.mSystemCpuTime.addCountLocked(systemTimeUs, onBattery);
Sudheer Shanka38383232017-07-25 09:55:03 -070012113 if (updatedUids != null) {
12114 updatedUids.put(u.getUid(), userTimeUs + systemTimeUs);
12115 }
12116 });
12117
12118 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12119 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12120 Slog.d(TAG, "Reading cpu stats took " + elapsedTimeMs + "ms");
12121 }
12122
12123 if (numWakelocks > 0) {
12124 // Distribute a portion of the total cpu time to wakelock holders.
12125 mTempTotalCpuUserTimeUs = (mTempTotalCpuUserTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
12126 mTempTotalCpuSystemTimeUs =
12127 (mTempTotalCpuSystemTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
12128
12129 for (int i = 0; i < numWakelocks; ++i) {
12130 final StopwatchTimer timer = partialTimers.get(i);
12131 final int userTimeUs = (int) (mTempTotalCpuUserTimeUs / (numWakelocks - i));
12132 final int systemTimeUs = (int) (mTempTotalCpuSystemTimeUs / (numWakelocks - i));
12133
12134 if (DEBUG_ENERGY_CPU) {
12135 final StringBuilder sb = new StringBuilder();
12136 sb.append(" Distributing wakelock uid=").append(timer.mUid.mUid)
12137 .append(": u=");
12138 TimeUtils.formatDuration(userTimeUs / 1000, sb);
12139 sb.append(" s=");
12140 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
12141 Slog.d(TAG, sb.toString());
12142 }
12143
Sudheer Shankac57729a2018-02-09 15:44:42 -080012144 timer.mUid.mUserCpuTime.addCountLocked(userTimeUs, onBattery);
12145 timer.mUid.mSystemCpuTime.addCountLocked(systemTimeUs, onBattery);
Sudheer Shanka38383232017-07-25 09:55:03 -070012146 if (updatedUids != null) {
12147 final int uid = timer.mUid.getUid();
12148 updatedUids.put(uid, updatedUids.get(uid, 0) + userTimeUs + systemTimeUs);
12149 }
12150
12151 final Uid.Proc proc = timer.mUid.getProcessStatsLocked("*wakelock*");
Sudheer Shankac57729a2018-02-09 15:44:42 -080012152 proc.addCpuTimeLocked(userTimeUs / 1000, systemTimeUs / 1000, onBattery);
Sudheer Shanka38383232017-07-25 09:55:03 -070012153
12154 mTempTotalCpuUserTimeUs -= userTimeUs;
12155 mTempTotalCpuSystemTimeUs -= systemTimeUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070012156 }
12157 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070012158 }
12159
Sudheer Shanka38383232017-07-25 09:55:03 -070012160 /**
12161 * Take a snapshot of the cpu times spent by each uid in each freq and update the
12162 * corresponding counters.
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012163 *
12164 * @param partialTimers The wakelock holders among which the cpu freq times will be distributed.
Sudheer Shanka38383232017-07-25 09:55:03 -070012165 */
12166 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012167 public void readKernelUidCpuFreqTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers,
12168 boolean onBattery, boolean onBatteryScreenOff) {
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012169 final boolean perClusterTimesAvailable =
12170 mKernelUidCpuFreqTimeReader.perClusterTimesAvailable();
12171 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
12172 final int numClusters = mPowerProfile.getNumCpuClusters();
12173 mWakeLockAllocationsUs = null;
Sudheer Shankaac5b88f2017-12-11 15:36:35 -080012174 final long startTimeMs = mClocks.uptimeMillis();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012175 mKernelUidCpuFreqTimeReader.readDelta((uid, cpuFreqTimeMs) -> {
12176 uid = mapUid(uid);
12177 if (Process.isIsolated(uid)) {
12178 mKernelUidCpuFreqTimeReader.removeUid(uid);
12179 Slog.d(TAG, "Got freq readings for an isolated uid with no mapping: " + uid);
12180 return;
Sudheer Shanka38383232017-07-25 09:55:03 -070012181 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012182 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12183 Slog.d(TAG, "Got freq readings for an invalid user's uid " + uid);
12184 mKernelUidCpuFreqTimeReader.removeUid(uid);
12185 return;
12186 }
12187 final Uid u = getUidStatsLocked(uid);
12188 if (u.mCpuFreqTimeMs == null || u.mCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
12189 u.mCpuFreqTimeMs = new LongSamplingCounterArray(mOnBatteryTimeBase);
12190 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080012191 u.mCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012192 if (u.mScreenOffCpuFreqTimeMs == null ||
12193 u.mScreenOffCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
12194 u.mScreenOffCpuFreqTimeMs = new LongSamplingCounterArray(
12195 mOnBatteryScreenOffTimeBase);
12196 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080012197 u.mScreenOffCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs, onBatteryScreenOff);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012198
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012199 if (perClusterTimesAvailable) {
12200 if (u.mCpuClusterSpeedTimesUs == null ||
12201 u.mCpuClusterSpeedTimesUs.length != numClusters) {
12202 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070012203 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012204 if (numWakelocks > 0 && mWakeLockAllocationsUs == null) {
12205 mWakeLockAllocationsUs = new long[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070012206 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012207
12208 int freqIndex = 0;
12209 for (int cluster = 0; cluster < numClusters; ++cluster) {
12210 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
12211 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
12212 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
12213 u.mCpuClusterSpeedTimesUs[cluster]
12214 = new LongSamplingCounter[speedsInCluster];
12215 }
12216 if (numWakelocks > 0 && mWakeLockAllocationsUs[cluster] == null) {
12217 mWakeLockAllocationsUs[cluster] = new long[speedsInCluster];
12218 }
12219 final LongSamplingCounter[] cpuTimesUs = u.mCpuClusterSpeedTimesUs[cluster];
12220 for (int speed = 0; speed < speedsInCluster; ++speed) {
12221 if (cpuTimesUs[speed] == null) {
12222 cpuTimesUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
12223 }
12224 final long appAllocationUs;
12225 if (mWakeLockAllocationsUs != null) {
12226 appAllocationUs =
12227 (cpuFreqTimeMs[freqIndex] * 1000 * WAKE_LOCK_WEIGHT) / 100;
12228 mWakeLockAllocationsUs[cluster][speed] +=
12229 (cpuFreqTimeMs[freqIndex] * 1000 - appAllocationUs);
12230 } else {
12231 appAllocationUs = cpuFreqTimeMs[freqIndex] * 1000;
12232 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080012233 cpuTimesUs[speed].addCountLocked(appAllocationUs, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012234 freqIndex++;
12235 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012236 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012237 }
12238 });
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012239
Sudheer Shankaac5b88f2017-12-11 15:36:35 -080012240 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12241 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12242 Slog.d(TAG, "Reading cpu freq times took " + elapsedTimeMs + "ms");
12243 }
12244
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012245 if (mWakeLockAllocationsUs != null) {
12246 for (int i = 0; i < numWakelocks; ++i) {
12247 final Uid u = partialTimers.get(i).mUid;
12248 if (u.mCpuClusterSpeedTimesUs == null ||
12249 u.mCpuClusterSpeedTimesUs.length != numClusters) {
12250 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
12251 }
12252
12253 for (int cluster = 0; cluster < numClusters; ++cluster) {
12254 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
12255 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
12256 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
12257 u.mCpuClusterSpeedTimesUs[cluster]
12258 = new LongSamplingCounter[speedsInCluster];
12259 }
12260 final LongSamplingCounter[] cpuTimeUs = u.mCpuClusterSpeedTimesUs[cluster];
12261 for (int speed = 0; speed < speedsInCluster; ++speed) {
12262 if (cpuTimeUs[speed] == null) {
12263 cpuTimeUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
12264 }
12265 final long allocationUs =
12266 mWakeLockAllocationsUs[cluster][speed] / (numWakelocks - i);
Sudheer Shankac57729a2018-02-09 15:44:42 -080012267 cpuTimeUs[speed].addCountLocked(allocationUs, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012268 mWakeLockAllocationsUs[cluster][speed] -= allocationUs;
12269 }
12270 }
12271 }
12272 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012273 }
12274
Mike Ma3d422c32017-10-25 11:08:57 -070012275 /**
12276 * Take a snapshot of the cpu active times spent by each uid and update the corresponding
12277 * counters.
12278 */
12279 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012280 public void readKernelUidCpuActiveTimesLocked(boolean onBattery) {
Mike Ma3d422c32017-10-25 11:08:57 -070012281 final long startTimeMs = mClocks.uptimeMillis();
Mike Ma2ab01442018-02-13 14:22:47 -080012282 mKernelUidCpuActiveTimeReader.readDelta((uid, cpuActiveTimesMs) -> {
Mike Ma3d422c32017-10-25 11:08:57 -070012283 uid = mapUid(uid);
12284 if (Process.isIsolated(uid)) {
12285 mKernelUidCpuActiveTimeReader.removeUid(uid);
12286 Slog.w(TAG, "Got active times for an isolated uid with no mapping: " + uid);
12287 return;
12288 }
12289 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12290 Slog.w(TAG, "Got active times for an invalid user's uid " + uid);
12291 mKernelUidCpuActiveTimeReader.removeUid(uid);
12292 return;
12293 }
12294 final Uid u = getUidStatsLocked(uid);
Mike Ma2ab01442018-02-13 14:22:47 -080012295 u.mCpuActiveTimeMs.addCountLocked(cpuActiveTimesMs, onBattery);
Mike Ma3d422c32017-10-25 11:08:57 -070012296 });
12297
12298 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12299 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12300 Slog.d(TAG, "Reading cpu active times took " + elapsedTimeMs + "ms");
12301 }
12302 }
12303
12304 /**
12305 * Take a snapshot of the cpu cluster times spent by each uid and update the corresponding
12306 * counters.
12307 */
12308 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012309 public void readKernelUidCpuClusterTimesLocked(boolean onBattery) {
Mike Ma3d422c32017-10-25 11:08:57 -070012310 final long startTimeMs = mClocks.uptimeMillis();
Mike Ma2ab01442018-02-13 14:22:47 -080012311 mKernelUidCpuClusterTimeReader.readDelta((uid, cpuClusterTimesMs) -> {
Mike Ma3d422c32017-10-25 11:08:57 -070012312 uid = mapUid(uid);
12313 if (Process.isIsolated(uid)) {
12314 mKernelUidCpuClusterTimeReader.removeUid(uid);
12315 Slog.w(TAG, "Got cluster times for an isolated uid with no mapping: " + uid);
12316 return;
12317 }
12318 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12319 Slog.w(TAG, "Got cluster times for an invalid user's uid " + uid);
12320 mKernelUidCpuClusterTimeReader.removeUid(uid);
12321 return;
12322 }
12323 final Uid u = getUidStatsLocked(uid);
Mike Ma2ab01442018-02-13 14:22:47 -080012324 u.mCpuClusterTimesMs.addCountLocked(cpuClusterTimesMs, onBattery);
Mike Ma3d422c32017-10-25 11:08:57 -070012325 });
12326
12327 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12328 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12329 Slog.d(TAG, "Reading cpu cluster times took " + elapsedTimeMs + "ms");
12330 }
12331 }
12332
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012333 boolean setChargingLocked(boolean charging) {
12334 if (mCharging != charging) {
12335 mCharging = charging;
12336 if (charging) {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012337 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012338 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012339 mHistoryCur.states2 &= ~HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012340 }
12341 mHandler.sendEmptyMessage(MSG_REPORT_CHARGING);
12342 return true;
12343 }
12344 return false;
12345 }
12346
Andreas Gampe3f24e692018-02-05 13:24:28 -080012347 @GuardedBy("this")
Mike Mac2f518a2017-09-19 16:06:03 -070012348 protected void setOnBatteryLocked(final long mSecRealtime, final long mSecUptime,
12349 final boolean onBattery, final int oldStatus, final int level, final int chargeUAh) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012350 boolean doWrite = false;
12351 Message m = mHandler.obtainMessage(MSG_REPORT_POWER_CHANGE);
12352 m.arg1 = onBattery ? 1 : 0;
12353 mHandler.sendMessage(m);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012354
Dianne Hackborn40c87252014-03-19 16:55:40 -070012355 final long uptime = mSecUptime * 1000;
12356 final long realtime = mSecRealtime * 1000;
Mike Mac2f518a2017-09-19 16:06:03 -070012357 final int screenState = mScreenState;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012358 if (onBattery) {
12359 // We will reset our status if we are unplugging after the
12360 // battery was last full, or the level is at 100, or
12361 // we have gone through a significant charge (from a very low
12362 // level to a now very high level).
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080012363 boolean reset = false;
Dianne Hackborn9a755432014-05-15 17:05:22 -070012364 if (!mNoAutoReset && (oldStatus == BatteryManager.BATTERY_STATUS_FULL
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012365 || level >= 90
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070012366 || (mDischargeCurrentLevel < 20 && level >= 80)
12367 || (getHighDischargeAmountSinceCharge() >= 200
12368 && mHistoryBuffer.dataSize() >= MAX_HISTORY_BUFFER))) {
Dianne Hackborn73d6a822014-09-29 10:52:47 -070012369 Slog.i(TAG, "Resetting battery stats: level=" + level + " status=" + oldStatus
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070012370 + " dischargeLevel=" + mDischargeCurrentLevel
Dianne Hackborn73d6a822014-09-29 10:52:47 -070012371 + " lowAmount=" + getLowDischargeAmountSinceCharge()
12372 + " highAmount=" + getHighDischargeAmountSinceCharge());
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012373 // Before we write, collect a snapshot of the final aggregated
12374 // stats to be reported in the next checkin. Only do this if we have
12375 // a sufficient amount of data to make it interesting.
12376 if (getLowDischargeAmountSinceCharge() >= 20) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080012377 final long startTime = SystemClock.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012378 final Parcel parcel = Parcel.obtain();
12379 writeSummaryToParcel(parcel, true);
Dianne Hackborne17b4452018-01-10 13:15:40 -080012380 final long initialTime = SystemClock.uptimeMillis() - startTime;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012381 BackgroundThread.getHandler().post(new Runnable() {
12382 @Override public void run() {
12383 synchronized (mCheckinFile) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080012384 final long startTime2 = SystemClock.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012385 FileOutputStream stream = null;
12386 try {
12387 stream = mCheckinFile.startWrite();
12388 stream.write(parcel.marshall());
12389 stream.flush();
12390 FileUtils.sync(stream);
12391 stream.close();
12392 mCheckinFile.finishWrite(stream);
Dianne Hackborne17b4452018-01-10 13:15:40 -080012393 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
12394 "batterystats-checkin",
12395 initialTime + SystemClock.uptimeMillis() - startTime2);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012396 } catch (IOException e) {
12397 Slog.w("BatteryStats",
12398 "Error writing checkin battery statistics", e);
12399 mCheckinFile.failWrite(stream);
12400 } finally {
12401 parcel.recycle();
12402 }
12403 }
12404 }
12405 });
12406 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012407 doWrite = true;
12408 resetAllStatsLocked();
Ying Wai (Daniel) Fan442ab762017-01-31 22:00:10 -080012409 if (chargeUAh > 0 && level > 0) {
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012410 // Only use the reported coulomb charge value if it is supported and reported.
Ying Wai (Daniel) Fan9238b612017-01-18 15:50:19 -080012411 mEstimatedBatteryCapacity = (int) ((chargeUAh / 1000) / (level / 100.0));
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012412 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012413 mDischargeStartLevel = level;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080012414 reset = true;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012415 mDischargeStepTracker.init();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012416 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012417 if (mCharging) {
12418 setChargingLocked(false);
12419 }
12420 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080012421 mOnBattery = mOnBatteryInternal = true;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012422 mLastDischargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070012423 mMinDischargeStepLevel = level;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012424 mDischargeStepTracker.clearTime();
12425 mDailyDischargeStepTracker.clearTime();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012426 mInitStepMode = mCurStepMode;
12427 mModStepMode = 0;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012428 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012429 mHistoryCur.batteryLevel = (byte)level;
12430 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
12431 if (DEBUG_HISTORY) Slog.v(TAG, "Battery unplugged to: "
12432 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012433 if (reset) {
12434 mRecordingHistory = true;
12435 startRecordingHistory(mSecRealtime, mSecUptime, reset);
12436 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070012437 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012438 mDischargeCurrentLevel = mDischargeUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070012439 if (isScreenOn(screenState)) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012440 mDischargeScreenOnUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070012441 mDischargeScreenDozeUnplugLevel = 0;
12442 mDischargeScreenOffUnplugLevel = 0;
12443 } else if (isScreenDoze(screenState)) {
12444 mDischargeScreenOnUnplugLevel = 0;
12445 mDischargeScreenDozeUnplugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012446 mDischargeScreenOffUnplugLevel = 0;
12447 } else {
12448 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012449 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012450 mDischargeScreenOffUnplugLevel = level;
12451 }
12452 mDischargeAmountScreenOn = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012453 mDischargeAmountScreenDoze = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012454 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012455 updateTimeBasesLocked(true, screenState, uptime, realtime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012456 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012457 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080012458 mOnBattery = mOnBatteryInternal = false;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012459 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012460 mHistoryCur.batteryLevel = (byte)level;
12461 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
12462 if (DEBUG_HISTORY) Slog.v(TAG, "Battery plugged to: "
12463 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -070012464 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012465 mDischargeCurrentLevel = mDischargePlugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012466 if (level < mDischargeUnplugLevel) {
12467 mLowDischargeAmountSinceCharge += mDischargeUnplugLevel-level-1;
12468 mHighDischargeAmountSinceCharge += mDischargeUnplugLevel-level;
12469 }
Mike Mac2f518a2017-09-19 16:06:03 -070012470 updateDischargeScreenLevelsLocked(screenState, screenState);
12471 updateTimeBasesLocked(false, screenState, uptime, realtime);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012472 mChargeStepTracker.init();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012473 mLastChargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070012474 mMaxChargeStepLevel = level;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012475 mInitStepMode = mCurStepMode;
12476 mModStepMode = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012477 }
12478 if (doWrite || (mLastWriteTime + (60 * 1000)) < mSecRealtime) {
12479 if (mFile != null) {
12480 writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012481 }
12482 }
12483 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012484
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012485 private void startRecordingHistory(final long elapsedRealtimeMs, final long uptimeMs,
12486 boolean reset) {
12487 mRecordingHistory = true;
12488 mHistoryCur.currentTime = System.currentTimeMillis();
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012489 addHistoryBufferLocked(elapsedRealtimeMs,
Dianne Hackborn37de0982014-05-09 09:32:18 -070012490 reset ? HistoryItem.CMD_RESET : HistoryItem.CMD_CURRENT_TIME,
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012491 mHistoryCur);
12492 mHistoryCur.currentTime = 0;
12493 if (reset) {
12494 initActiveHistoryEventsLocked(elapsedRealtimeMs, uptimeMs);
12495 }
12496 }
12497
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012498 private void recordCurrentTimeChangeLocked(final long currentTime, final long elapsedRealtimeMs,
12499 final long uptimeMs) {
12500 if (mRecordingHistory) {
12501 mHistoryCur.currentTime = currentTime;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012502 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_CURRENT_TIME, mHistoryCur);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012503 mHistoryCur.currentTime = 0;
12504 }
12505 }
12506
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080012507 private void recordShutdownLocked(final long elapsedRealtimeMs, final long uptimeMs) {
12508 if (mRecordingHistory) {
12509 mHistoryCur.currentTime = System.currentTimeMillis();
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012510 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_SHUTDOWN, mHistoryCur);
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080012511 mHistoryCur.currentTime = 0;
12512 }
12513 }
12514
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012515 private void scheduleSyncExternalStatsLocked(String reason, int updateFlags) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012516 if (mExternalSync != null) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012517 mExternalSync.scheduleSync(reason, updateFlags);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070012518 }
12519 }
12520
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012521 // This should probably be exposed in the API, though it's not critical
Bookatz1a1b0462018-01-12 11:47:03 -080012522 public static final int BATTERY_PLUGGED_NONE = OsProtoEnums.BATTERY_PLUGGED_NONE; // = 0
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012523
Andreas Gampe3f24e692018-02-05 13:24:28 -080012524 @GuardedBy("this")
Bookatz8c6571b2017-10-24 15:04:41 -070012525 public void setBatteryStateLocked(final int status, final int health, final int plugType,
12526 final int level, /* not final */ int temp, final int volt, final int chargeUAh,
12527 final int chargeFullUAh) {
Adam Lesinski29ddfe52017-03-29 19:29:00 -070012528 // Temperature is encoded without the signed bit, so clamp any negative temperatures to 0.
12529 temp = Math.max(0, temp);
12530
Bookatz8c6571b2017-10-24 15:04:41 -070012531 reportChangesToStatsLog(mHaveBatteryLevel ? mHistoryCur : null,
Tej Singh40298312018-02-16 00:15:09 -080012532 status, plugType, level);
Bookatz8c6571b2017-10-24 15:04:41 -070012533
Sudheer Shankac57729a2018-02-09 15:44:42 -080012534 final boolean onBattery = isOnBattery(plugType, status);
Joe Onoratoabded112016-02-08 16:49:39 -080012535 final long uptime = mClocks.uptimeMillis();
12536 final long elapsedRealtime = mClocks.elapsedRealtime();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012537 if (!mHaveBatteryLevel) {
12538 mHaveBatteryLevel = true;
12539 // We start out assuming that the device is plugged in (not
12540 // on battery). If our first report is now that we are indeed
12541 // plugged in, then twiddle our state to correctly reflect that
12542 // since we won't be going through the full setOnBattery().
12543 if (onBattery == mOnBattery) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012544 if (onBattery) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012545 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012546 } else {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012547 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012548 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012549 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012550 // Always start out assuming charging, that will be updated later.
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012551 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012552 mHistoryCur.batteryStatus = (byte)status;
12553 mHistoryCur.batteryLevel = (byte)level;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012554 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012555 mMaxChargeStepLevel = mMinDischargeStepLevel =
12556 mLastChargeStepLevel = mLastDischargeStepLevel = level;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012557 mLastChargingStateLevel = level;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012558 } else if (mCurrentBatteryLevel != level || mOnBattery != onBattery) {
12559 recordDailyStatsIfNeededLocked(level >= 100 && onBattery);
12560 }
12561 int oldStatus = mHistoryCur.batteryStatus;
12562 if (onBattery) {
12563 mDischargeCurrentLevel = level;
12564 if (!mRecordingHistory) {
12565 mRecordingHistory = true;
12566 startRecordingHistory(elapsedRealtime, uptime, true);
12567 }
Todd Poynor1acf06a2017-12-07 19:19:35 -080012568 } else if (level < 96 &&
12569 status != BatteryManager.BATTERY_STATUS_UNKNOWN) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012570 if (!mRecordingHistory) {
12571 mRecordingHistory = true;
12572 startRecordingHistory(elapsedRealtime, uptime, true);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012573 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070012574 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012575 mCurrentBatteryLevel = level;
12576 if (mDischargePlugLevel < 0) {
12577 mDischargePlugLevel = level;
Marco Nelissend8593312009-04-30 14:45:06 -070012578 }
Adam Lesinski926969b2016-04-28 17:31:12 -070012579
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012580 if (onBattery != mOnBattery) {
12581 mHistoryCur.batteryLevel = (byte)level;
12582 mHistoryCur.batteryStatus = (byte)status;
12583 mHistoryCur.batteryHealth = (byte)health;
12584 mHistoryCur.batteryPlugType = (byte)plugType;
12585 mHistoryCur.batteryTemperature = (short)temp;
12586 mHistoryCur.batteryVoltage = (char)volt;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012587 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
12588 // Only record discharges
12589 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
12590 mDischargeCounter.addCountLocked(chargeDiff);
12591 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070012592 if (isScreenDoze(mScreenState)) {
12593 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
12594 }
Mike Ma15313c92017-11-15 17:58:21 -080012595 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
12596 mDischargeLightDozeCounter.addCountLocked(chargeDiff);
12597 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
12598 mDischargeDeepDozeCounter.addCountLocked(chargeDiff);
12599 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012600 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012601 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012602 setOnBatteryLocked(elapsedRealtime, uptime, onBattery, oldStatus, level, chargeUAh);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012603 } else {
12604 boolean changed = false;
12605 if (mHistoryCur.batteryLevel != level) {
12606 mHistoryCur.batteryLevel = (byte)level;
12607 changed = true;
Marco Nelissend8593312009-04-30 14:45:06 -070012608
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012609 // TODO(adamlesinski): Schedule the creation of a HistoryStepDetails record
12610 // which will pull external stats.
Sudheer Shanka0719c6a2018-04-24 11:12:11 -070012611 mExternalSync.scheduleSyncDueToBatteryLevelChange(
12612 mConstants.BATTERY_LEVEL_COLLECTION_DELAY_MS);
Evan Millarc64edde2009-04-18 12:26:32 -070012613 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012614 if (mHistoryCur.batteryStatus != status) {
12615 mHistoryCur.batteryStatus = (byte)status;
12616 changed = true;
12617 }
12618 if (mHistoryCur.batteryHealth != health) {
12619 mHistoryCur.batteryHealth = (byte)health;
12620 changed = true;
12621 }
12622 if (mHistoryCur.batteryPlugType != plugType) {
12623 mHistoryCur.batteryPlugType = (byte)plugType;
12624 changed = true;
12625 }
12626 if (temp >= (mHistoryCur.batteryTemperature+10)
12627 || temp <= (mHistoryCur.batteryTemperature-10)) {
12628 mHistoryCur.batteryTemperature = (short)temp;
12629 changed = true;
12630 }
12631 if (volt > (mHistoryCur.batteryVoltage+20)
12632 || volt < (mHistoryCur.batteryVoltage-20)) {
12633 mHistoryCur.batteryVoltage = (char)volt;
12634 changed = true;
12635 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012636 if (chargeUAh >= (mHistoryCur.batteryChargeUAh+10)
12637 || chargeUAh <= (mHistoryCur.batteryChargeUAh-10)) {
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012638 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
12639 // Only record discharges
12640 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
12641 mDischargeCounter.addCountLocked(chargeDiff);
12642 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070012643 if (isScreenDoze(mScreenState)) {
12644 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
12645 }
Mike Ma15313c92017-11-15 17:58:21 -080012646 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
12647 mDischargeLightDozeCounter.addCountLocked(chargeDiff);
12648 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
12649 mDischargeDeepDozeCounter.addCountLocked(chargeDiff);
12650 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012651 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012652 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski926969b2016-04-28 17:31:12 -070012653 changed = true;
12654 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012655 long modeBits = (((long)mInitStepMode) << STEP_LEVEL_INITIAL_MODE_SHIFT)
12656 | (((long)mModStepMode) << STEP_LEVEL_MODIFIED_MODE_SHIFT)
12657 | (((long)(level&0xff)) << STEP_LEVEL_LEVEL_SHIFT);
12658 if (onBattery) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012659 changed |= setChargingLocked(false);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012660 if (mLastDischargeStepLevel != level && mMinDischargeStepLevel > level) {
12661 mDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
12662 modeBits, elapsedRealtime);
12663 mDailyDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
12664 modeBits, elapsedRealtime);
12665 mLastDischargeStepLevel = level;
12666 mMinDischargeStepLevel = level;
12667 mInitStepMode = mCurStepMode;
12668 mModStepMode = 0;
12669 }
12670 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012671 if (level >= 90) {
12672 // If the battery level is at least 90%, always consider the device to be
12673 // charging even if it happens to go down a level.
12674 changed |= setChargingLocked(true);
12675 mLastChargeStepLevel = level;
12676 } if (!mCharging) {
12677 if (mLastChargeStepLevel < level) {
12678 // We have not reporting that we are charging, but the level has now
12679 // gone up, so consider the state to be charging.
12680 changed |= setChargingLocked(true);
12681 mLastChargeStepLevel = level;
12682 }
12683 } else {
12684 if (mLastChargeStepLevel > level) {
12685 // We had reported that the device was charging, but here we are with
12686 // power connected and the level going down. Looks like the current
12687 // power supplied isn't enough, so consider the device to now be
12688 // discharging.
12689 changed |= setChargingLocked(false);
12690 mLastChargeStepLevel = level;
12691 }
12692 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012693 if (mLastChargeStepLevel != level && mMaxChargeStepLevel < level) {
12694 mChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
12695 modeBits, elapsedRealtime);
12696 mDailyChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
12697 modeBits, elapsedRealtime);
12698 mLastChargeStepLevel = level;
12699 mMaxChargeStepLevel = level;
12700 mInitStepMode = mCurStepMode;
12701 mModStepMode = 0;
Evan Millarc64edde2009-04-18 12:26:32 -070012702 }
12703 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012704 if (changed) {
12705 addHistoryRecordLocked(elapsedRealtime, uptime);
12706 }
Evan Millarc64edde2009-04-18 12:26:32 -070012707 }
Todd Poynor1acf06a2017-12-07 19:19:35 -080012708 if (!onBattery &&
12709 (status == BatteryManager.BATTERY_STATUS_FULL ||
12710 status == BatteryManager.BATTERY_STATUS_UNKNOWN)) {
12711 // We don't record history while we are plugged in and fully charged
12712 // (or when battery is not present). The next time we are
12713 // unplugged, history will be cleared.
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012714 mRecordingHistory = DEBUG;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080012715 }
Adam Lesinski041d9172016-12-12 12:03:56 -080012716
Jocelyn Dangc627d102017-04-14 13:15:14 -070012717 if (mMinLearnedBatteryCapacity == -1) {
12718 mMinLearnedBatteryCapacity = chargeFullUAh;
12719 } else {
12720 Math.min(mMinLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski041d9172016-12-12 12:03:56 -080012721 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070012722 mMaxLearnedBatteryCapacity = Math.max(mMaxLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski33dac552015-03-09 15:24:48 -070012723 }
12724
Sudheer Shankac57729a2018-02-09 15:44:42 -080012725 public static boolean isOnBattery(int plugType, int status) {
12726 return plugType == BATTERY_PLUGGED_NONE && status != BatteryManager.BATTERY_STATUS_UNKNOWN;
12727 }
12728
Bookatz8c6571b2017-10-24 15:04:41 -070012729 // Inform StatsLog of setBatteryState changes.
12730 // If this is the first reporting, pass in recentPast == null.
12731 private void reportChangesToStatsLog(HistoryItem recentPast,
Tej Singh40298312018-02-16 00:15:09 -080012732 final int status, final int plugType, final int level) {
Bookatz8c6571b2017-10-24 15:04:41 -070012733
12734 if (recentPast == null || recentPast.batteryStatus != status) {
12735 StatsLog.write(StatsLog.CHARGING_STATE_CHANGED, status);
12736 }
12737 if (recentPast == null || recentPast.batteryPlugType != plugType) {
12738 StatsLog.write(StatsLog.PLUGGED_STATE_CHANGED, plugType);
12739 }
12740 if (recentPast == null || recentPast.batteryLevel != level) {
12741 StatsLog.write(StatsLog.BATTERY_LEVEL_CHANGED, level);
12742 }
Bookatz8c6571b2017-10-24 15:04:41 -070012743 }
12744
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012745 public long getAwakeTimeBattery() {
12746 return computeBatteryUptime(getBatteryUptimeLocked(), STATS_CURRENT);
12747 }
12748
12749 public long getAwakeTimePlugged() {
Joe Onoratoabded112016-02-08 16:49:39 -080012750 return (mClocks.uptimeMillis() * 1000) - getAwakeTimeBattery();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012751 }
12752
12753 @Override
12754 public long computeUptime(long curTime, int which) {
12755 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012756 case STATS_SINCE_CHARGED: return mUptime + (curTime-mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012757 case STATS_CURRENT: return (curTime-mUptimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070012758 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getUptimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012759 }
12760 return 0;
12761 }
12762
12763 @Override
12764 public long computeRealtime(long curTime, int which) {
12765 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012766 case STATS_SINCE_CHARGED: return mRealtime + (curTime-mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012767 case STATS_CURRENT: return (curTime-mRealtimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070012768 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getRealtimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012769 }
12770 return 0;
12771 }
12772
12773 @Override
12774 public long computeBatteryUptime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012775 return mOnBatteryTimeBase.computeUptime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012776 }
12777
12778 @Override
12779 public long computeBatteryRealtime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012780 return mOnBatteryTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012781 }
12782
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012783 @Override
12784 public long computeBatteryScreenOffUptime(long curTime, int which) {
12785 return mOnBatteryScreenOffTimeBase.computeUptime(curTime, which);
12786 }
12787
12788 @Override
12789 public long computeBatteryScreenOffRealtime(long curTime, int which) {
12790 return mOnBatteryScreenOffTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012791 }
12792
Dianne Hackborn260c5022014-04-29 11:23:16 -070012793 private long computeTimePerLevel(long[] steps, int numSteps) {
12794 // For now we'll do a simple average across all steps.
12795 if (numSteps <= 0) {
12796 return -1;
12797 }
12798 long total = 0;
12799 for (int i=0; i<numSteps; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012800 total += steps[i] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012801 }
12802 return total / numSteps;
12803 /*
12804 long[] buckets = new long[numSteps];
12805 int numBuckets = 0;
12806 int numToAverage = 4;
12807 int i = 0;
12808 while (i < numSteps) {
12809 long totalTime = 0;
12810 int num = 0;
12811 for (int j=0; j<numToAverage && (i+j)<numSteps; j++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012812 totalTime += steps[i+j] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012813 num++;
12814 }
12815 buckets[numBuckets] = totalTime / num;
12816 numBuckets++;
12817 numToAverage *= 2;
12818 i += num;
12819 }
12820 if (numBuckets < 1) {
12821 return -1;
12822 }
12823 long averageTime = buckets[numBuckets-1];
12824 for (i=numBuckets-2; i>=0; i--) {
12825 averageTime = (averageTime + buckets[i]) / 2;
12826 }
12827 return averageTime;
12828 */
12829 }
12830
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012831 @Override
12832 public long computeBatteryTimeRemaining(long curTime) {
12833 if (!mOnBattery) {
12834 return -1;
12835 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070012836 /* Simple implementation just looks at the average discharge per level across the
12837 entire sample period.
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012838 int discharge = (getLowDischargeAmountSinceCharge()+getHighDischargeAmountSinceCharge())/2;
12839 if (discharge < 2) {
12840 return -1;
12841 }
12842 long duration = computeBatteryRealtime(curTime, STATS_SINCE_CHARGED);
12843 if (duration < 1000*1000) {
12844 return -1;
12845 }
12846 long usPerLevel = duration/discharge;
12847 return usPerLevel * mCurrentBatteryLevel;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012848 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012849 if (mDischargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012850 return -1;
12851 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012852 long msPerLevel = mDischargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012853 if (msPerLevel <= 0) {
12854 return -1;
12855 }
12856 return (msPerLevel * mCurrentBatteryLevel) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012857 }
12858
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012859 @Override
12860 public LevelStepTracker getDischargeLevelStepTracker() {
12861 return mDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012862 }
12863
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012864 @Override
12865 public LevelStepTracker getDailyDischargeLevelStepTracker() {
12866 return mDailyDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012867 }
12868
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012869 @Override
12870 public long computeChargeTimeRemaining(long curTime) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012871 if (mOnBattery) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012872 // Not yet working.
12873 return -1;
12874 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070012875 /* Broken
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012876 int curLevel = mCurrentBatteryLevel;
12877 int plugLevel = mDischargePlugLevel;
12878 if (plugLevel < 0 || curLevel < (plugLevel+1)) {
12879 return -1;
12880 }
12881 long duration = computeBatteryRealtime(curTime, STATS_SINCE_UNPLUGGED);
12882 if (duration < 1000*1000) {
12883 return -1;
12884 }
12885 long usPerLevel = duration/(curLevel-plugLevel);
12886 return usPerLevel * (100-curLevel);
Dianne Hackborn260c5022014-04-29 11:23:16 -070012887 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012888 if (mChargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012889 return -1;
12890 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012891 long msPerLevel = mChargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012892 if (msPerLevel <= 0) {
12893 return -1;
12894 }
12895 return (msPerLevel * (100-mCurrentBatteryLevel)) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012896 }
12897
Siddharth Raya1fd0572017-11-13 14:20:47 -080012898 /*@hide */
12899 public CellularBatteryStats getCellularBatteryStats() {
12900 CellularBatteryStats s = new CellularBatteryStats();
12901 final int which = STATS_SINCE_CHARGED;
12902 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12903 final ControllerActivityCounter counter = getModemControllerActivity();
Siddharth Rayed754702018-02-15 12:44:37 -080012904 final long sleepTimeMs = counter.getSleepTimeCounter().getCountLocked(which);
Siddharth Raya1fd0572017-11-13 14:20:47 -080012905 final long idleTimeMs = counter.getIdleTimeCounter().getCountLocked(which);
12906 final long rxTimeMs = counter.getRxTimeCounter().getCountLocked(which);
12907 final long energyConsumedMaMs = counter.getPowerCounter().getCountLocked(which);
12908 long[] timeInRatMs = new long[BatteryStats.NUM_DATA_CONNECTION_TYPES];
12909 for (int i = 0; i < timeInRatMs.length; i++) {
12910 timeInRatMs[i] = getPhoneDataConnectionTime(i, rawRealTime, which) / 1000;
12911 }
12912 long[] timeInRxSignalStrengthLevelMs = new long[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
12913 for (int i = 0; i < timeInRxSignalStrengthLevelMs.length; i++) {
12914 timeInRxSignalStrengthLevelMs[i]
12915 = getPhoneSignalStrengthTime(i, rawRealTime, which) / 1000;
12916 }
12917 long[] txTimeMs = new long[Math.min(ModemActivityInfo.TX_POWER_LEVELS,
12918 counter.getTxTimeCounters().length)];
12919 long totalTxTimeMs = 0;
12920 for (int i = 0; i < txTimeMs.length; i++) {
12921 txTimeMs[i] = counter.getTxTimeCounters()[i].getCountLocked(which);
12922 totalTxTimeMs += txTimeMs[i];
12923 }
Siddharth Raya1fd0572017-11-13 14:20:47 -080012924 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
12925 s.setKernelActiveTimeMs(getMobileRadioActiveTime(rawRealTime, which) / 1000);
12926 s.setNumPacketsTx(getNetworkActivityPackets(NETWORK_MOBILE_TX_DATA, which));
12927 s.setNumBytesTx(getNetworkActivityBytes(NETWORK_MOBILE_TX_DATA, which));
12928 s.setNumPacketsRx(getNetworkActivityPackets(NETWORK_MOBILE_RX_DATA, which));
12929 s.setNumBytesRx(getNetworkActivityBytes(NETWORK_MOBILE_RX_DATA, which));
12930 s.setSleepTimeMs(sleepTimeMs);
12931 s.setIdleTimeMs(idleTimeMs);
12932 s.setRxTimeMs(rxTimeMs);
12933 s.setEnergyConsumedMaMs(energyConsumedMaMs);
12934 s.setTimeInRatMs(timeInRatMs);
12935 s.setTimeInRxSignalStrengthLevelMs(timeInRxSignalStrengthLevelMs);
12936 s.setTxTimeMs(txTimeMs);
12937 return s;
12938 }
12939
Siddharth Rayb50a6842017-12-14 15:15:28 -080012940 /*@hide */
12941 public WifiBatteryStats getWifiBatteryStats() {
12942 WifiBatteryStats s = new WifiBatteryStats();
12943 final int which = STATS_SINCE_CHARGED;
12944 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12945 final ControllerActivityCounter counter = getWifiControllerActivity();
12946 final long idleTimeMs = counter.getIdleTimeCounter().getCountLocked(which);
12947 final long scanTimeMs = counter.getScanTimeCounter().getCountLocked(which);
12948 final long rxTimeMs = counter.getRxTimeCounter().getCountLocked(which);
12949 final long txTimeMs = counter.getTxTimeCounters()[0].getCountLocked(which);
12950 final long totalControllerActivityTimeMs
12951 = computeBatteryRealtime(SystemClock.elapsedRealtime() * 1000, which) / 1000;
12952 final long sleepTimeMs
12953 = totalControllerActivityTimeMs - (idleTimeMs + rxTimeMs + txTimeMs);
12954 final long energyConsumedMaMs = counter.getPowerCounter().getCountLocked(which);
12955 long numAppScanRequest = 0;
12956 for (int i = 0; i < mUidStats.size(); i++) {
12957 numAppScanRequest += mUidStats.valueAt(i).mWifiScanTimer.getCountLocked(which);
12958 }
12959 long[] timeInStateMs = new long[NUM_WIFI_STATES];
12960 for (int i=0; i<NUM_WIFI_STATES; i++) {
12961 timeInStateMs[i] = getWifiStateTime(i, rawRealTime, which) / 1000;
12962 }
12963 long[] timeInSupplStateMs = new long[NUM_WIFI_SUPPL_STATES];
12964 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
12965 timeInSupplStateMs[i] = getWifiSupplStateTime(i, rawRealTime, which) / 1000;
12966 }
12967 long[] timeSignalStrengthTimeMs = new long[NUM_WIFI_SIGNAL_STRENGTH_BINS];
12968 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
12969 timeSignalStrengthTimeMs[i] = getWifiSignalStrengthTime(i, rawRealTime, which) / 1000;
12970 }
12971 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
12972 s.setKernelActiveTimeMs(getWifiActiveTime(rawRealTime, which) / 1000);
12973 s.setNumPacketsTx(getNetworkActivityPackets(NETWORK_WIFI_TX_DATA, which));
12974 s.setNumBytesTx(getNetworkActivityBytes(NETWORK_WIFI_TX_DATA, which));
12975 s.setNumPacketsRx(getNetworkActivityPackets(NETWORK_WIFI_RX_DATA, which));
12976 s.setNumBytesRx(getNetworkActivityBytes(NETWORK_WIFI_RX_DATA, which));
12977 s.setSleepTimeMs(sleepTimeMs);
12978 s.setIdleTimeMs(idleTimeMs);
12979 s.setRxTimeMs(rxTimeMs);
12980 s.setTxTimeMs(txTimeMs);
12981 s.setScanTimeMs(scanTimeMs);
12982 s.setEnergyConsumedMaMs(energyConsumedMaMs);
12983 s.setNumAppScanRequest(numAppScanRequest);
12984 s.setTimeInStateMs(timeInStateMs);
12985 s.setTimeInSupplicantStateMs(timeInSupplStateMs);
12986 s.setTimeInRxSignalStrengthLevelMs(timeSignalStrengthTimeMs);
12987 return s;
12988 }
12989
Siddharth Ray78ccaf52017-12-23 16:16:21 -080012990 /*@hide */
12991 public GpsBatteryStats getGpsBatteryStats() {
12992 GpsBatteryStats s = new GpsBatteryStats();
12993 final int which = STATS_SINCE_CHARGED;
12994 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12995 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
12996 s.setEnergyConsumedMaMs(getGpsBatteryDrainMaMs());
12997 long[] time = new long[GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS];
12998 for (int i=0; i<time.length; i++) {
12999 time[i] = getGpsSignalQualityTime(i, rawRealTime, which) / 1000;
13000 }
13001 s.setTimeInGpsSignalQualityLevel(time);
13002 return s;
13003 }
13004
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013005 @Override
13006 public LevelStepTracker getChargeLevelStepTracker() {
13007 return mChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070013008 }
13009
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013010 @Override
13011 public LevelStepTracker getDailyChargeLevelStepTracker() {
13012 return mDailyChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070013013 }
13014
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013015 @Override
13016 public ArrayList<PackageChange> getDailyPackageChanges() {
13017 return mDailyPackageChanges;
13018 }
13019
Joe Onoratoe1acd632016-02-23 13:25:10 -080013020 protected long getBatteryUptimeLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080013021 return mOnBatteryTimeBase.getUptime(mClocks.uptimeMillis() * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013022 }
13023
13024 @Override
13025 public long getBatteryUptime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013026 return mOnBatteryTimeBase.getUptime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013027 }
13028
13029 @Override
13030 public long getBatteryRealtime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013031 return mOnBatteryTimeBase.getRealtime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013032 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -070013033
The Android Open Source Project10592532009-03-18 17:39:46 -070013034 @Override
Evan Millar633a1742009-04-02 16:36:33 -070013035 public int getDischargeStartLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070013036 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070013037 return getDischargeStartLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070013038 }
13039 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013040
Evan Millar633a1742009-04-02 16:36:33 -070013041 public int getDischargeStartLevelLocked() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013042 return mDischargeUnplugLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070013043 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013044
The Android Open Source Project10592532009-03-18 17:39:46 -070013045 @Override
Evan Millar633a1742009-04-02 16:36:33 -070013046 public int getDischargeCurrentLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070013047 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070013048 return getDischargeCurrentLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070013049 }
13050 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013051
Evan Millar633a1742009-04-02 16:36:33 -070013052 public int getDischargeCurrentLevelLocked() {
Dianne Hackborne4a59512010-12-07 11:08:07 -080013053 return mDischargeCurrentLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070013054 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013055
Amith Yamasanie43530a2009-08-21 13:11:37 -070013056 @Override
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013057 public int getLowDischargeAmountSinceCharge() {
13058 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080013059 int val = mLowDischargeAmountSinceCharge;
13060 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
13061 val += mDischargeUnplugLevel-mDischargeCurrentLevel-1;
13062 }
13063 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013064 }
13065 }
13066
13067 @Override
13068 public int getHighDischargeAmountSinceCharge() {
13069 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080013070 int val = mHighDischargeAmountSinceCharge;
13071 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
13072 val += mDischargeUnplugLevel-mDischargeCurrentLevel;
13073 }
13074 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013075 }
13076 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070013077
13078 @Override
13079 public int getDischargeAmount(int which) {
13080 int dischargeAmount = which == STATS_SINCE_CHARGED
13081 ? getHighDischargeAmountSinceCharge()
13082 : (getDischargeStartLevel() - getDischargeCurrentLevel());
13083 if (dischargeAmount < 0) {
13084 dischargeAmount = 0;
13085 }
13086 return dischargeAmount;
13087 }
13088
Mike Mac2f518a2017-09-19 16:06:03 -070013089 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013090 public int getDischargeAmountScreenOn() {
13091 synchronized(this) {
13092 int val = mDischargeAmountScreenOn;
Mike Mac2f518a2017-09-19 16:06:03 -070013093 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013094 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
13095 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
13096 }
13097 return val;
13098 }
13099 }
13100
Mike Mac2f518a2017-09-19 16:06:03 -070013101 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013102 public int getDischargeAmountScreenOnSinceCharge() {
13103 synchronized(this) {
13104 int val = mDischargeAmountScreenOnSinceCharge;
Mike Mac2f518a2017-09-19 16:06:03 -070013105 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013106 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
13107 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
13108 }
13109 return val;
13110 }
13111 }
13112
Mike Mac2f518a2017-09-19 16:06:03 -070013113 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013114 public int getDischargeAmountScreenOff() {
13115 synchronized(this) {
13116 int val = mDischargeAmountScreenOff;
Mike Mac2f518a2017-09-19 16:06:03 -070013117 if (mOnBattery && isScreenOff(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013118 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
13119 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
13120 }
Mike Mac2f518a2017-09-19 16:06:03 -070013121 // For backward compatibility, doze discharge is counted into screen off.
13122 return val + getDischargeAmountScreenDoze();
13123 }
13124 }
13125
13126 @Override
13127 public int getDischargeAmountScreenOffSinceCharge() {
13128 synchronized(this) {
13129 int val = mDischargeAmountScreenOffSinceCharge;
13130 if (mOnBattery && isScreenOff(mScreenState)
13131 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
13132 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
13133 }
13134 // For backward compatibility, doze discharge is counted into screen off.
13135 return val + getDischargeAmountScreenDozeSinceCharge();
13136 }
13137 }
13138
13139 @Override
13140 public int getDischargeAmountScreenDoze() {
13141 synchronized(this) {
13142 int val = mDischargeAmountScreenDoze;
13143 if (mOnBattery && isScreenDoze(mScreenState)
13144 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
13145 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
13146 }
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013147 return val;
13148 }
13149 }
13150
Mike Mac2f518a2017-09-19 16:06:03 -070013151 @Override
13152 public int getDischargeAmountScreenDozeSinceCharge() {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013153 synchronized(this) {
Mike Mac2f518a2017-09-19 16:06:03 -070013154 int val = mDischargeAmountScreenDozeSinceCharge;
13155 if (mOnBattery && isScreenDoze(mScreenState)
13156 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
13157 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013158 }
13159 return val;
13160 }
13161 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013163 /**
13164 * Retrieve the statistics object for a particular uid, creating if needed.
13165 */
13166 public Uid getUidStatsLocked(int uid) {
13167 Uid u = mUidStats.get(uid);
13168 if (u == null) {
Joe Onoratoabded112016-02-08 16:49:39 -080013169 u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013170 mUidStats.put(uid, u);
13171 }
13172 return u;
13173 }
13174
Sudheer Shankab2f83c12017-11-13 19:25:01 -080013175 /**
13176 * Retrieve the statistics object for a particular uid. Returns null if the object is not
13177 * available.
13178 */
13179 public Uid getAvailableUidStatsLocked(int uid) {
13180 Uid u = mUidStats.get(uid);
13181 return u;
13182 }
13183
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070013184 public void onCleanupUserLocked(int userId) {
13185 final int firstUidForUser = UserHandle.getUid(userId, 0);
13186 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
Mike Ma234d1822018-03-13 18:53:21 -070013187 mPendingRemovedUids.add(
13188 new UidToRemove(firstUidForUser, lastUidForUser, mClocks.elapsedRealtime()));
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070013189 }
13190
13191 public void onUserRemovedLocked(int userId) {
13192 final int firstUidForUser = UserHandle.getUid(userId, 0);
13193 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
13194 mUidStats.put(firstUidForUser, null);
13195 mUidStats.put(lastUidForUser, null);
13196 final int firstIndex = mUidStats.indexOfKey(firstUidForUser);
13197 final int lastIndex = mUidStats.indexOfKey(lastUidForUser);
13198 mUidStats.removeAtRange(firstIndex, lastIndex - firstIndex + 1);
13199 }
13200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013201 /**
13202 * Remove the statistics object for a particular uid.
13203 */
13204 public void removeUidStatsLocked(int uid) {
13205 mUidStats.remove(uid);
Mike Ma234d1822018-03-13 18:53:21 -070013206 mPendingRemovedUids.add(new UidToRemove(uid, mClocks.elapsedRealtime()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013207 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -070013208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013209 /**
13210 * Retrieve the statistics object for a particular process, creating
13211 * if needed.
13212 */
13213 public Uid.Proc getProcessStatsLocked(int uid, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013214 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013215 Uid u = getUidStatsLocked(uid);
13216 return u.getProcessStatsLocked(name);
13217 }
13218
13219 /**
13220 * Retrieve the statistics object for a particular process, creating
13221 * if needed.
13222 */
13223 public Uid.Pkg getPackageStatsLocked(int uid, String pkg) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013224 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013225 Uid u = getUidStatsLocked(uid);
13226 return u.getPackageStatsLocked(pkg);
13227 }
13228
13229 /**
13230 * Retrieve the statistics object for a particular service, creating
13231 * if needed.
13232 */
13233 public Uid.Pkg.Serv getServiceStatsLocked(int uid, String pkg, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013234 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013235 Uid u = getUidStatsLocked(uid);
13236 return u.getServiceStatsLocked(pkg, name);
13237 }
13238
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013239 public void shutdownLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080013240 recordShutdownLocked(mClocks.elapsedRealtime(), mClocks.uptimeMillis());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013241 writeSyncLocked();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013242 mShuttingDown = true;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013243 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013244
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013245 public boolean trackPerProcStateCpuTimes() {
13246 return mConstants.TRACK_CPU_TIMES_BY_PROC_STATE && mPerProcStateCpuTimesAvailable;
13247 }
13248
13249 public void systemServicesReady(Context context) {
13250 mConstants.startObserving(context.getContentResolver());
Mike Mafbc01fc2018-04-02 10:28:28 -070013251 registerUsbStateReceiver(context);
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013252 }
13253
13254 @VisibleForTesting
13255 public final class Constants extends ContentObserver {
13256 public static final String KEY_TRACK_CPU_TIMES_BY_PROC_STATE
13257 = "track_cpu_times_by_proc_state";
Mike Mafae87da2018-01-19 20:07:20 -080013258 public static final String KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME
13259 = "track_cpu_active_cluster_time";
Sudheer Shankac20379e2018-02-15 00:06:21 -080013260 public static final String KEY_PROC_STATE_CPU_TIMES_READ_DELAY_MS
13261 = "proc_state_cpu_times_read_delay_ms";
Mike Ma2ab01442018-02-13 14:22:47 -080013262 public static final String KEY_KERNEL_UID_READERS_THROTTLE_TIME
13263 = "kernel_uid_readers_throttle_time";
Mike Ma234d1822018-03-13 18:53:21 -070013264 public static final String KEY_UID_REMOVE_DELAY_MS
13265 = "uid_remove_delay_ms";
Sudheer Shankae56013a2018-04-23 11:22:15 -070013266 public static final String KEY_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS
13267 = "external_stats_collection_rate_limit_ms";
Sudheer Shanka0719c6a2018-04-24 11:12:11 -070013268 public static final String KEY_BATTERY_LEVEL_COLLECTION_DELAY_MS
13269 = "battery_level_collection_delay_ms";
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013270
13271 private static final boolean DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE = true;
Mike Mafae87da2018-01-19 20:07:20 -080013272 private static final boolean DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME = true;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013273 private static final long DEFAULT_PROC_STATE_CPU_TIMES_READ_DELAY_MS = 5_000;
Mike Ma2ab01442018-02-13 14:22:47 -080013274 private static final long DEFAULT_KERNEL_UID_READERS_THROTTLE_TIME = 10_000;
Mike Ma234d1822018-03-13 18:53:21 -070013275 private static final long DEFAULT_UID_REMOVE_DELAY_MS = 5L * 60L * 1000L;
Sudheer Shankae56013a2018-04-23 11:22:15 -070013276 private static final long DEFAULT_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS = 600_000;
Sudheer Shanka0719c6a2018-04-24 11:12:11 -070013277 private static final long DEFAULT_BATTERY_LEVEL_COLLECTION_DELAY_MS = 300_000;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013278
13279 public boolean TRACK_CPU_TIMES_BY_PROC_STATE = DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE;
Mike Mafae87da2018-01-19 20:07:20 -080013280 public boolean TRACK_CPU_ACTIVE_CLUSTER_TIME = DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013281 public long PROC_STATE_CPU_TIMES_READ_DELAY_MS = DEFAULT_PROC_STATE_CPU_TIMES_READ_DELAY_MS;
Mike Ma2ab01442018-02-13 14:22:47 -080013282 public long KERNEL_UID_READERS_THROTTLE_TIME = DEFAULT_KERNEL_UID_READERS_THROTTLE_TIME;
Mike Ma234d1822018-03-13 18:53:21 -070013283 public long UID_REMOVE_DELAY_MS = DEFAULT_UID_REMOVE_DELAY_MS;
Sudheer Shankae56013a2018-04-23 11:22:15 -070013284 public long EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS
13285 = DEFAULT_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS;
Sudheer Shanka0719c6a2018-04-24 11:12:11 -070013286 public long BATTERY_LEVEL_COLLECTION_DELAY_MS
13287 = DEFAULT_BATTERY_LEVEL_COLLECTION_DELAY_MS;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013288
13289 private ContentResolver mResolver;
13290 private final KeyValueListParser mParser = new KeyValueListParser(',');
13291
13292 public Constants(Handler handler) {
13293 super(handler);
13294 }
13295
13296 public void startObserving(ContentResolver resolver) {
13297 mResolver = resolver;
13298 mResolver.registerContentObserver(
13299 Settings.Global.getUriFor(Settings.Global.BATTERY_STATS_CONSTANTS),
13300 false /* notifyForDescendants */, this);
13301 updateConstants();
13302 }
13303
13304 @Override
13305 public void onChange(boolean selfChange, Uri uri) {
13306 updateConstants();
13307 }
13308
13309 private void updateConstants() {
13310 synchronized (BatteryStatsImpl.this) {
13311 try {
13312 mParser.setString(Settings.Global.getString(mResolver,
13313 Settings.Global.BATTERY_STATS_CONSTANTS));
13314 } catch (IllegalArgumentException e) {
13315 // Failed to parse the settings string, log this and move on
13316 // with defaults.
13317 Slog.e(TAG, "Bad batterystats settings", e);
13318 }
13319
13320 updateTrackCpuTimesByProcStateLocked(TRACK_CPU_TIMES_BY_PROC_STATE,
13321 mParser.getBoolean(KEY_TRACK_CPU_TIMES_BY_PROC_STATE,
13322 DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE));
Mike Mafae87da2018-01-19 20:07:20 -080013323 TRACK_CPU_ACTIVE_CLUSTER_TIME = mParser.getBoolean(
13324 KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME, DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME);
Sudheer Shankac20379e2018-02-15 00:06:21 -080013325 updateProcStateCpuTimesReadDelayMs(PROC_STATE_CPU_TIMES_READ_DELAY_MS,
13326 mParser.getLong(KEY_PROC_STATE_CPU_TIMES_READ_DELAY_MS,
Mike Ma2ab01442018-02-13 14:22:47 -080013327 DEFAULT_PROC_STATE_CPU_TIMES_READ_DELAY_MS));
13328 updateKernelUidReadersThrottleTime(KERNEL_UID_READERS_THROTTLE_TIME,
13329 mParser.getLong(KEY_KERNEL_UID_READERS_THROTTLE_TIME,
13330 DEFAULT_KERNEL_UID_READERS_THROTTLE_TIME));
Mike Ma234d1822018-03-13 18:53:21 -070013331 updateUidRemoveDelay(
13332 mParser.getLong(KEY_UID_REMOVE_DELAY_MS, DEFAULT_UID_REMOVE_DELAY_MS));
Sudheer Shankae56013a2018-04-23 11:22:15 -070013333 EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS = mParser.getLong(
13334 KEY_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS,
13335 DEFAULT_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS);
Sudheer Shanka0719c6a2018-04-24 11:12:11 -070013336 BATTERY_LEVEL_COLLECTION_DELAY_MS = mParser.getLong(
13337 KEY_BATTERY_LEVEL_COLLECTION_DELAY_MS,
13338 DEFAULT_BATTERY_LEVEL_COLLECTION_DELAY_MS);
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013339 }
13340 }
13341
13342 private void updateTrackCpuTimesByProcStateLocked(boolean wasEnabled, boolean isEnabled) {
13343 TRACK_CPU_TIMES_BY_PROC_STATE = isEnabled;
13344 if (isEnabled && !wasEnabled) {
13345 mKernelSingleUidTimeReader.markDataAsStale(true);
13346 mExternalSync.scheduleCpuSyncDueToSettingChange();
Sudheer Shankac20379e2018-02-15 00:06:21 -080013347
Mike Ma234d1822018-03-13 18:53:21 -070013348 mNumSingleUidCpuTimeReads = 0;
13349 mNumBatchedSingleUidCpuTimeReads = 0;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013350 mCpuTimeReadsTrackingStartTime = mClocks.uptimeMillis();
13351 }
13352 }
13353
13354 private void updateProcStateCpuTimesReadDelayMs(long oldDelayMillis, long newDelayMillis) {
13355 PROC_STATE_CPU_TIMES_READ_DELAY_MS = newDelayMillis;
13356 if (oldDelayMillis != newDelayMillis) {
Mike Ma234d1822018-03-13 18:53:21 -070013357 mNumSingleUidCpuTimeReads = 0;
13358 mNumBatchedSingleUidCpuTimeReads = 0;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013359 mCpuTimeReadsTrackingStartTime = mClocks.uptimeMillis();
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013360 }
13361 }
13362
Mike Ma2ab01442018-02-13 14:22:47 -080013363 private void updateKernelUidReadersThrottleTime(long oldTimeMs, long newTimeMs) {
13364 KERNEL_UID_READERS_THROTTLE_TIME = newTimeMs;
13365 if (oldTimeMs != newTimeMs) {
Mike Ma69d8b3e2018-02-23 14:51:26 -080013366 mKernelUidCpuTimeReader.setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
Mike Ma2ab01442018-02-13 14:22:47 -080013367 mKernelUidCpuFreqTimeReader.setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
13368 mKernelUidCpuActiveTimeReader.setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
13369 mKernelUidCpuClusterTimeReader
13370 .setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
13371 }
13372 }
13373
Mike Ma234d1822018-03-13 18:53:21 -070013374 private void updateUidRemoveDelay(long newTimeMs) {
13375 UID_REMOVE_DELAY_MS = newTimeMs;
13376 clearPendingRemovedUids();
13377 }
13378
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013379 public void dumpLocked(PrintWriter pw) {
13380 pw.print(KEY_TRACK_CPU_TIMES_BY_PROC_STATE); pw.print("=");
13381 pw.println(TRACK_CPU_TIMES_BY_PROC_STATE);
Mike Mafae87da2018-01-19 20:07:20 -080013382 pw.print(KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME); pw.print("=");
13383 pw.println(TRACK_CPU_ACTIVE_CLUSTER_TIME);
Sudheer Shankac20379e2018-02-15 00:06:21 -080013384 pw.print(KEY_PROC_STATE_CPU_TIMES_READ_DELAY_MS); pw.print("=");
13385 pw.println(PROC_STATE_CPU_TIMES_READ_DELAY_MS);
Mike Ma2ab01442018-02-13 14:22:47 -080013386 pw.print(KEY_KERNEL_UID_READERS_THROTTLE_TIME); pw.print("=");
13387 pw.println(KERNEL_UID_READERS_THROTTLE_TIME);
Sudheer Shankae56013a2018-04-23 11:22:15 -070013388 pw.print(KEY_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS); pw.print("=");
13389 pw.println(EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS);
Sudheer Shanka0719c6a2018-04-24 11:12:11 -070013390 pw.print(KEY_BATTERY_LEVEL_COLLECTION_DELAY_MS); pw.print("=");
13391 pw.println(BATTERY_LEVEL_COLLECTION_DELAY_MS);
Sudheer Shankae56013a2018-04-23 11:22:15 -070013392 }
13393 }
13394
13395 public long getExternalStatsCollectionRateLimitMs() {
13396 synchronized (this) {
13397 return mConstants.EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013398 }
13399 }
13400
Andreas Gampe3f24e692018-02-05 13:24:28 -080013401 @GuardedBy("this")
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013402 public void dumpConstantsLocked(PrintWriter pw) {
13403 mConstants.dumpLocked(pw);
13404 }
13405
Mike Ma234d1822018-03-13 18:53:21 -070013406 @GuardedBy("this")
13407 public void dumpCpuStatsLocked(PrintWriter pw) {
13408 int size = mUidStats.size();
13409 pw.println("Per UID CPU user & system time in ms:");
13410 for (int i = 0; i < size; i++) {
13411 int u = mUidStats.keyAt(i);
13412 Uid uid = mUidStats.get(u);
13413 pw.print(" "); pw.print(u); pw.print(": ");
13414 pw.print(uid.getUserCpuTimeUs(STATS_SINCE_CHARGED) / 1000); pw.print(" ");
13415 pw.println(uid.getSystemCpuTimeUs(STATS_SINCE_CHARGED) / 1000);
13416 }
13417 pw.println("Per UID CPU active time in ms:");
13418 for (int i = 0; i < size; i++) {
13419 int u = mUidStats.keyAt(i);
13420 Uid uid = mUidStats.get(u);
13421 if (uid.getCpuActiveTime() > 0) {
13422 pw.print(" "); pw.print(u); pw.print(": "); pw.println(uid.getCpuActiveTime());
13423 }
13424 }
13425 pw.println("Per UID CPU cluster time in ms:");
13426 for (int i = 0; i < size; i++) {
13427 int u = mUidStats.keyAt(i);
13428 long[] times = mUidStats.get(u).getCpuClusterTimes();
13429 if (times != null) {
13430 pw.print(" "); pw.print(u); pw.print(": "); pw.println(Arrays.toString(times));
13431 }
13432 }
13433 pw.println("Per UID CPU frequency time in ms:");
13434 for (int i = 0; i < size; i++) {
13435 int u = mUidStats.keyAt(i);
13436 long[] times = mUidStats.get(u).getCpuFreqTimes(STATS_SINCE_CHARGED);
13437 if (times != null) {
13438 pw.print(" "); pw.print(u); pw.print(": "); pw.println(Arrays.toString(times));
13439 }
13440 }
13441 }
13442
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013443 Parcel mPendingWrite = null;
13444 final ReentrantLock mWriteLock = new ReentrantLock();
13445
13446 public void writeAsyncLocked() {
13447 writeLocked(false);
13448 }
13449
13450 public void writeSyncLocked() {
13451 writeLocked(true);
13452 }
13453
13454 void writeLocked(boolean sync) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013455 if (mFile == null) {
13456 Slog.w("BatteryStats", "writeLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013457 return;
13458 }
13459
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013460 if (mShuttingDown) {
13461 return;
13462 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013463
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013464 Parcel out = Parcel.obtain();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013465 writeSummaryToParcel(out, true);
Joe Onoratoabded112016-02-08 16:49:39 -080013466 mLastWriteTime = mClocks.elapsedRealtime();
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013467
13468 if (mPendingWrite != null) {
13469 mPendingWrite.recycle();
13470 }
13471 mPendingWrite = out;
13472
13473 if (sync) {
13474 commitPendingDataToDisk();
13475 } else {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013476 BackgroundThread.getHandler().post(new Runnable() {
13477 @Override public void run() {
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013478 commitPendingDataToDisk();
13479 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013480 });
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013481 }
13482 }
13483
13484 public void commitPendingDataToDisk() {
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070013485 final Parcel next;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013486 synchronized (this) {
13487 next = mPendingWrite;
13488 mPendingWrite = null;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070013489 if (next == null) {
13490 return;
13491 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013492 }
13493
Amith Yamasanid2450862017-02-07 15:58:24 -080013494 mWriteLock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013495 try {
Dianne Hackborne17b4452018-01-10 13:15:40 -080013496 final long startTime = SystemClock.uptimeMillis();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013497 FileOutputStream stream = new FileOutputStream(mFile.chooseForWrite());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013498 stream.write(next.marshall());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013499 stream.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070013500 FileUtils.sync(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013501 stream.close();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013502 mFile.commit();
Dianne Hackborne17b4452018-01-10 13:15:40 -080013503 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
13504 "batterystats", SystemClock.uptimeMillis() - startTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013505 } catch (IOException e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013506 Slog.w("BatteryStats", "Error writing battery statistics", e);
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013507 mFile.rollback();
13508 } finally {
13509 next.recycle();
13510 mWriteLock.unlock();
Suchi Amalapurapu8550f252009-09-29 15:20:32 -070013511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013512 }
13513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013514 public void readLocked() {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013515 if (mDailyFile != null) {
13516 readDailyStatsLocked();
13517 }
13518
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013519 if (mFile == null) {
13520 Slog.w("BatteryStats", "readLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013521 return;
13522 }
13523
13524 mUidStats.clear();
13525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013526 try {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013527 File file = mFile.chooseForRead();
13528 if (!file.exists()) {
13529 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013530 }
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013531 FileInputStream stream = new FileInputStream(file);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013532
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013533 byte[] raw = BatteryStatsHelper.readFully(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013534 Parcel in = Parcel.obtain();
13535 in.unmarshall(raw, 0, raw.length);
13536 in.setDataPosition(0);
13537 stream.close();
13538
13539 readSummaryFromParcel(in);
Dianne Hackborn00e25212014-02-19 10:49:24 -080013540 } catch(Exception e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013541 Slog.e("BatteryStats", "Error reading battery statistics", e);
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013542 resetAllStatsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013543 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013544
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013545 mEndPlatformVersion = Build.ID;
13546
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013547 if (mHistoryBuffer.dataPosition() > 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013548 mRecordingHistory = true;
Joe Onoratoabded112016-02-08 16:49:39 -080013549 final long elapsedRealtime = mClocks.elapsedRealtime();
13550 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013551 if (USE_OLD_HISTORY) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013552 addHistoryRecordLocked(elapsedRealtime, uptime, HistoryItem.CMD_START, mHistoryCur);
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013553 }
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000013554 addHistoryBufferLocked(elapsedRealtime, HistoryItem.CMD_START, mHistoryCur);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013555 startRecordingHistory(elapsedRealtime, uptime, false);
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013556 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013557
13558 recordDailyStatsIfNeededLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013559 }
13560
13561 public int describeContents() {
13562 return 0;
13563 }
13564
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013565 void readHistory(Parcel in, boolean andOldHistory) throws ParcelFormatException {
Dianne Hackbornae384452011-06-28 12:33:48 -070013566 final long historyBaseTime = in.readLong();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013567
13568 mHistoryBuffer.setDataSize(0);
13569 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013570 mHistoryTagPool.clear();
13571 mNextHistoryTagIdx = 0;
13572 mNumHistoryTagChars = 0;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013573
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013574 int numTags = in.readInt();
13575 for (int i=0; i<numTags; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080013576 int idx = in.readInt();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013577 String str = in.readString();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013578 if (str == null) {
13579 throw new ParcelFormatException("null history tag string");
13580 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013581 int uid = in.readInt();
13582 HistoryTag tag = new HistoryTag();
13583 tag.string = str;
13584 tag.uid = uid;
13585 tag.poolIdx = idx;
13586 mHistoryTagPool.put(tag, idx);
13587 if (idx >= mNextHistoryTagIdx) {
13588 mNextHistoryTagIdx = idx+1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013589 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013590 mNumHistoryTagChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013591 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013592
13593 int bufSize = in.readInt();
13594 int curPos = in.dataPosition();
13595 if (bufSize >= (MAX_MAX_HISTORY_BUFFER*3)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013596 throw new ParcelFormatException("File corrupt: history data buffer too large " +
13597 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013598 } else if ((bufSize&~3) != bufSize) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013599 throw new ParcelFormatException("File corrupt: history data buffer not aligned " +
13600 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013601 } else {
13602 if (DEBUG_HISTORY) Slog.i(TAG, "***************** READING NEW HISTORY: " + bufSize
13603 + " bytes at " + curPos);
13604 mHistoryBuffer.appendFrom(in, curPos, bufSize);
13605 in.setDataPosition(curPos + bufSize);
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013606 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013607
Dianne Hackbornae384452011-06-28 12:33:48 -070013608 if (andOldHistory) {
13609 readOldHistory(in);
13610 }
13611
13612 if (DEBUG_HISTORY) {
13613 StringBuilder sb = new StringBuilder(128);
13614 sb.append("****************** OLD mHistoryBaseTime: ");
13615 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13616 Slog.i(TAG, sb.toString());
13617 }
13618 mHistoryBaseTime = historyBaseTime;
13619 if (DEBUG_HISTORY) {
13620 StringBuilder sb = new StringBuilder(128);
13621 sb.append("****************** NEW mHistoryBaseTime: ");
13622 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13623 Slog.i(TAG, sb.toString());
13624 }
13625
13626 // We are just arbitrarily going to insert 1 minute from the sample of
13627 // the last run until samples in this run.
13628 if (mHistoryBaseTime > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -080013629 long oldnow = mClocks.elapsedRealtime();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013630 mHistoryBaseTime = mHistoryBaseTime - oldnow + 1;
Dianne Hackbornae384452011-06-28 12:33:48 -070013631 if (DEBUG_HISTORY) {
13632 StringBuilder sb = new StringBuilder(128);
13633 sb.append("****************** ADJUSTED mHistoryBaseTime: ");
13634 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13635 Slog.i(TAG, sb.toString());
13636 }
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -070013637 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013638 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013639
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013640 void readOldHistory(Parcel in) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013641 if (!USE_OLD_HISTORY) {
13642 return;
13643 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013644 mHistory = mHistoryEnd = mHistoryCache = null;
13645 long time;
Conley Owens5e3357f2011-05-02 09:59:30 -070013646 while (in.dataAvail() > 0 && (time=in.readLong()) >= 0) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013647 HistoryItem rec = new HistoryItem(time, in);
13648 addHistoryRecordLocked(rec);
13649 }
13650 }
13651
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013652 void writeHistory(Parcel out, boolean inclData, boolean andOldHistory) {
Dianne Hackbornae384452011-06-28 12:33:48 -070013653 if (DEBUG_HISTORY) {
13654 StringBuilder sb = new StringBuilder(128);
13655 sb.append("****************** WRITING mHistoryBaseTime: ");
13656 TimeUtils.formatDuration(mHistoryBaseTime, sb);
Dianne Hackborn40c87252014-03-19 16:55:40 -070013657 sb.append(" mLastHistoryElapsedRealtime: ");
13658 TimeUtils.formatDuration(mLastHistoryElapsedRealtime, sb);
Dianne Hackbornae384452011-06-28 12:33:48 -070013659 Slog.i(TAG, sb.toString());
13660 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070013661 out.writeLong(mHistoryBaseTime + mLastHistoryElapsedRealtime);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013662 if (!inclData) {
13663 out.writeInt(0);
13664 out.writeInt(0);
13665 return;
13666 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013667 out.writeInt(mHistoryTagPool.size());
13668 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
13669 HistoryTag tag = ent.getKey();
Dianne Hackborn099bc622014-01-22 13:39:16 -080013670 out.writeInt(ent.getValue());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013671 out.writeString(tag.string);
13672 out.writeInt(tag.uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -080013673 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013674 out.writeInt(mHistoryBuffer.dataSize());
13675 if (DEBUG_HISTORY) Slog.i(TAG, "***************** WRITING HISTORY: "
13676 + mHistoryBuffer.dataSize() + " bytes at " + out.dataPosition());
13677 out.appendFrom(mHistoryBuffer, 0, mHistoryBuffer.dataSize());
Dianne Hackbornae384452011-06-28 12:33:48 -070013678
13679 if (andOldHistory) {
13680 writeOldHistory(out);
13681 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013682 }
13683
13684 void writeOldHistory(Parcel out) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013685 if (!USE_OLD_HISTORY) {
13686 return;
13687 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013688 HistoryItem rec = mHistory;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013689 while (rec != null) {
13690 if (rec.time >= 0) rec.writeToParcel(out, 0);
13691 rec = rec.next;
13692 }
13693 out.writeLong(-1);
13694 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013695
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013696 public void readSummaryFromParcel(Parcel in) throws ParcelFormatException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013697 final int version = in.readInt();
13698 if (version != VERSION) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013699 Slog.w("BatteryStats", "readFromParcel: version got " + version
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013700 + ", expected " + VERSION + "; erasing old stats");
13701 return;
13702 }
13703
Dianne Hackbornae384452011-06-28 12:33:48 -070013704 readHistory(in, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013705
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013706 mStartCount = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013707 mUptime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013708 mRealtime = in.readLong();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080013709 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013710 mStartPlatformVersion = in.readString();
13711 mEndPlatformVersion = in.readString();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013712 mOnBatteryTimeBase.readSummaryFromParcel(in);
13713 mOnBatteryScreenOffTimeBase.readSummaryFromParcel(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013714 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013715 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070013716 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013717 mCurrentBatteryLevel = in.readInt();
Adam Lesinskif9b20a92016-06-17 17:30:01 -070013718 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070013719 mMinLearnedBatteryCapacity = in.readInt();
13720 mMaxLearnedBatteryCapacity = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013721 mLowDischargeAmountSinceCharge = in.readInt();
13722 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013723 mDischargeAmountScreenOnSinceCharge = in.readInt();
13724 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070013725 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013726 mDischargeStepTracker.readFromParcel(in);
13727 mChargeStepTracker.readFromParcel(in);
13728 mDailyDischargeStepTracker.readFromParcel(in);
13729 mDailyChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070013730 mDischargeCounter.readSummaryFromParcelLocked(in);
13731 mDischargeScreenOffCounter.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070013732 mDischargeScreenDozeCounter.readSummaryFromParcelLocked(in);
Mike Ma15313c92017-11-15 17:58:21 -080013733 mDischargeLightDozeCounter.readSummaryFromParcelLocked(in);
13734 mDischargeDeepDozeCounter.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013735 int NPKG = in.readInt();
13736 if (NPKG > 0) {
13737 mDailyPackageChanges = new ArrayList<>(NPKG);
13738 while (NPKG > 0) {
13739 NPKG--;
13740 PackageChange pc = new PackageChange();
13741 pc.mPackageName = in.readString();
13742 pc.mUpdate = in.readInt() != 0;
Dianne Hackborn3accca02013-09-20 09:32:11 -070013743 pc.mVersionCode = in.readLong();
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013744 mDailyPackageChanges.add(pc);
13745 }
13746 } else {
13747 mDailyPackageChanges = null;
13748 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013749 mDailyStartTime = in.readLong();
13750 mNextMinDailyDeadline = in.readLong();
13751 mNextMaxDailyDeadline = in.readLong();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013753 mStartCount++;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013754
Jeff Browne95c3cd2014-05-02 16:59:26 -070013755 mScreenState = Display.STATE_UNKNOWN;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013756 mScreenOnTimer.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070013757 mScreenDozeTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn617f8772009-03-31 15:04:46 -070013758 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
13759 mScreenBrightnessTimer[i].readSummaryFromParcelLocked(in);
13760 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070013761 mInteractive = false;
13762 mInteractiveTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013763 mPhoneOn = false;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070013764 mPowerSaveModeEnabledTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070013765 mLongestLightIdleTime = in.readLong();
13766 mLongestFullIdleTime = in.readLong();
13767 mDeviceIdleModeLightTimer.readSummaryFromParcelLocked(in);
13768 mDeviceIdleModeFullTimer.readSummaryFromParcelLocked(in);
13769 mDeviceLightIdlingTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013770 mDeviceIdlingTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013771 mPhoneOnTimer.readSummaryFromParcelLocked(in);
Wink Saville52840902011-02-18 12:40:47 -080013772 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn627bba72009-03-24 22:32:56 -070013773 mPhoneSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
13774 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070013775 mPhoneSignalScanningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013776 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
13777 mPhoneDataConnectionsTimer[i].readSummaryFromParcelLocked(in);
13778 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013779 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013780 mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
13781 mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013782 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013783 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborne13c4c02014-02-11 17:18:35 -080013784 mMobileRadioActiveTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080013785 mMobileRadioActivePerAppTimer.readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013786 mMobileRadioActiveAdjustedTime.readSummaryFromParcelLocked(in);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013787 mMobileRadioActiveUnknownTime.readSummaryFromParcelLocked(in);
13788 mMobileRadioActiveUnknownCount.readSummaryFromParcelLocked(in);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080013789 mWifiMulticastWakelockTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070013790 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
The Android Open Source Project10592532009-03-18 17:39:46 -070013791 mWifiOn = false;
13792 mWifiOnTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013793 mGlobalWifiRunning = false;
13794 mGlobalWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080013795 for (int i=0; i<NUM_WIFI_STATES; i++) {
13796 mWifiStateTimer[i].readSummaryFromParcelLocked(in);
13797 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070013798 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
13799 mWifiSupplStateTimer[i].readSummaryFromParcelLocked(in);
13800 }
13801 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
13802 mWifiSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
13803 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080013804 mWifiActiveTimer.readSummaryFromParcelLocked(in);
13805 mWifiActivity.readSummaryFromParcel(in);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080013806 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
13807 mGpsSignalQualityTimer[i].readSummaryFromParcelLocked(in);
13808 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080013809 mBluetoothActivity.readSummaryFromParcel(in);
13810 mModemActivity.readSummaryFromParcel(in);
13811 mHasWifiReporting = in.readInt() != 0;
13812 mHasBluetoothReporting = in.readInt() != 0;
13813 mHasModemReporting = in.readInt() != 0;
Adam Lesinski33dac552015-03-09 15:24:48 -070013814
Dianne Hackborn1e01d162014-12-04 17:46:42 -080013815 mNumConnectivityChange = mLoadedNumConnectivityChange = in.readInt();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013816 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -070013817 mFlashlightOnTimer.readSummaryFromParcelLocked(in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013818 mCameraOnNesting = 0;
13819 mCameraOnTimer.readSummaryFromParcelLocked(in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013820 mBluetoothScanNesting = 0;
13821 mBluetoothScanTimer.readSummaryFromParcelLocked(in);
Siddharth Rayf5e796a2018-01-22 18:18:17 -080013822 mIsCellularTxPowerHigh = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013823
Bookatz50df7112017-08-04 14:53:26 -070013824 int NRPMS = in.readInt();
13825 if (NRPMS > 10000) {
13826 throw new ParcelFormatException("File corrupt: too many rpm stats " + NRPMS);
13827 }
13828 for (int irpm = 0; irpm < NRPMS; irpm++) {
13829 if (in.readInt() != 0) {
13830 String rpmName = in.readString();
13831 getRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
13832 }
13833 }
13834 int NSORPMS = in.readInt();
13835 if (NSORPMS > 10000) {
13836 throw new ParcelFormatException("File corrupt: too many screen-off rpm stats " + NSORPMS);
13837 }
13838 for (int irpm = 0; irpm < NSORPMS; irpm++) {
13839 if (in.readInt() != 0) {
13840 String rpmName = in.readString();
13841 getScreenOffRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
13842 }
13843 }
13844
Evan Millarc64edde2009-04-18 12:26:32 -070013845 int NKW = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013846 if (NKW > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013847 throw new ParcelFormatException("File corrupt: too many kernel wake locks " + NKW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013848 }
Evan Millarc64edde2009-04-18 12:26:32 -070013849 for (int ikw = 0; ikw < NKW; ikw++) {
13850 if (in.readInt() != 0) {
13851 String kwltName = in.readString();
13852 getKernelWakelockTimerLocked(kwltName).readSummaryFromParcelLocked(in);
13853 }
13854 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070013855
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013856 int NWR = in.readInt();
13857 if (NWR > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013858 throw new ParcelFormatException("File corrupt: too many wakeup reasons " + NWR);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013859 }
13860 for (int iwr = 0; iwr < NWR; iwr++) {
13861 if (in.readInt() != 0) {
13862 String reasonName = in.readString();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070013863 getWakeupReasonTimerLocked(reasonName).readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013864 }
13865 }
13866
James Carr3a226052016-07-01 14:49:52 -070013867 int NMS = in.readInt();
13868 for (int ims = 0; ims < NMS; ims++) {
13869 if (in.readInt() != 0) {
13870 long kmstName = in.readLong();
13871 getKernelMemoryTimerLocked(kmstName).readSummaryFromParcelLocked(in);
13872 }
13873 }
13874
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013875 final int NU = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013876 if (NU > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013877 throw new ParcelFormatException("File corrupt: too many uids " + NU);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013878 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013879 for (int iu = 0; iu < NU; iu++) {
13880 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080013881 Uid u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013882 mUidStats.put(uid, u);
13883
Bookatz867c0d72017-03-07 18:23:42 -080013884 u.mOnBatteryBackgroundTimeBase.readSummaryFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -070013885 u.mOnBatteryScreenOffBackgroundTimeBase.readSummaryFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -080013886
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013887 u.mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013888 if (in.readInt() != 0) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013889 u.mWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013890 }
The Android Open Source Project10592532009-03-18 17:39:46 -070013891 u.mFullWifiLockOut = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013892 if (in.readInt() != 0) {
13893 u.mFullWifiLockTimer.readSummaryFromParcelLocked(in);
13894 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070013895 u.mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013896 if (in.readInt() != 0) {
Nick Pelly6ccaa542012-06-15 15:22:47 -070013897 u.mWifiScanTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013898 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070013899 u.mWifiBatchedScanBinStarted = Uid.NO_BATCHED_SCAN_STARTED;
13900 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
13901 if (in.readInt() != 0) {
13902 u.makeWifiBatchedScanBin(i, null);
13903 u.mWifiBatchedScanTimer[i].readSummaryFromParcelLocked(in);
13904 }
13905 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070013906 u.mWifiMulticastEnabled = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013907 if (in.readInt() != 0) {
13908 u.mWifiMulticastTimer.readSummaryFromParcelLocked(in);
13909 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013910 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013911 u.createAudioTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013912 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013913 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013914 u.createVideoTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13915 }
13916 if (in.readInt() != 0) {
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013917 u.createFlashlightTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13918 }
13919 if (in.readInt() != 0) {
13920 u.createCameraTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13921 }
13922 if (in.readInt() != 0) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013923 u.createForegroundActivityTimerLocked().readSummaryFromParcelLocked(in);
13924 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013925 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070013926 u.createForegroundServiceTimerLocked().readSummaryFromParcelLocked(in);
13927 }
13928 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -070013929 u.createAggregatedPartialWakelockTimerLocked().readSummaryFromParcelLocked(in);
13930 }
13931 if (in.readInt() != 0) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013932 u.createBluetoothScanTimerLocked().readSummaryFromParcelLocked(in);
13933 }
Bookatz956f36bf2017-04-28 09:48:17 -070013934 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -070013935 u.createBluetoothUnoptimizedScanTimerLocked().readSummaryFromParcelLocked(in);
13936 }
13937 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -070013938 u.createBluetoothScanResultCounterLocked().readSummaryFromParcelLocked(in);
13939 }
Bookatzb1f04f32017-05-19 13:57:32 -070013940 if (in.readInt() != 0) {
13941 u.createBluetoothScanResultBgCounterLocked().readSummaryFromParcelLocked(in);
13942 }
Dianne Hackborna8d10942015-11-19 17:55:19 -080013943 u.mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -070013944 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
13945 if (in.readInt() != 0) {
13946 u.makeProcessState(i, null);
13947 u.mProcessStateTimer[i].readSummaryFromParcelLocked(in);
13948 }
13949 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013950 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013951 u.createVibratorOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013952 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070013953
Dianne Hackborn617f8772009-03-31 15:04:46 -070013954 if (in.readInt() != 0) {
13955 if (u.mUserActivityCounters == null) {
13956 u.initUserActivityLocked();
13957 }
13958 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
13959 u.mUserActivityCounters[i].readSummaryFromParcelLocked(in);
13960 }
13961 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013962
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013963 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013964 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013965 u.initNetworkActivityLocked();
13966 }
13967 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013968 u.mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
13969 u.mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013970 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013971 u.mMobileRadioActiveTime.readSummaryFromParcelLocked(in);
13972 u.mMobileRadioActiveCount.readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013973 }
13974
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013975 u.mUserCpuTime.readSummaryFromParcelLocked(in);
13976 u.mSystemCpuTime.readSummaryFromParcelLocked(in);
13977
Adam Lesinski6832f392015-09-05 18:05:40 -070013978 if (in.readInt() != 0) {
13979 final int numClusters = in.readInt();
13980 if (mPowerProfile != null && mPowerProfile.getNumCpuClusters() != numClusters) {
13981 throw new ParcelFormatException("Incompatible cpu cluster arrangement");
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013982 }
Adam Lesinski6832f392015-09-05 18:05:40 -070013983
Sudheer Shankaaf857412017-07-21 00:14:24 -070013984 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -070013985 for (int cluster = 0; cluster < numClusters; cluster++) {
Adam Lesinski6832f392015-09-05 18:05:40 -070013986 if (in.readInt() != 0) {
Adam Lesinskia57a5402015-09-28 10:21:33 -070013987 final int NSB = in.readInt();
13988 if (mPowerProfile != null &&
13989 mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != NSB) {
13990 throw new ParcelFormatException("File corrupt: too many speed bins " +
13991 NSB);
13992 }
13993
Sudheer Shankaaf857412017-07-21 00:14:24 -070013994 u.mCpuClusterSpeedTimesUs[cluster] = new LongSamplingCounter[NSB];
Adam Lesinski6832f392015-09-05 18:05:40 -070013995 for (int speed = 0; speed < NSB; speed++) {
13996 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070013997 u.mCpuClusterSpeedTimesUs[cluster][speed] = new LongSamplingCounter(
Adam Lesinski6832f392015-09-05 18:05:40 -070013998 mOnBatteryTimeBase);
Sudheer Shankaaf857412017-07-21 00:14:24 -070013999 u.mCpuClusterSpeedTimesUs[cluster][speed].readSummaryFromParcelLocked(in);
Adam Lesinski6832f392015-09-05 18:05:40 -070014000 }
14001 }
Adam Lesinskia57a5402015-09-28 10:21:33 -070014002 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070014003 u.mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -070014004 }
14005 }
14006 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070014007 u.mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014008 }
14009
Sudheer Shanka59f5c002017-05-15 10:57:15 -070014010 u.mCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
14011 in, mOnBatteryTimeBase);
14012 u.mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
14013 in, mOnBatteryScreenOffTimeBase);
Mike Ma3d422c32017-10-25 11:08:57 -070014014
14015 u.mCpuActiveTimeMs.readSummaryFromParcelLocked(in);
14016 u.mCpuClusterTimesMs.readSummaryFromParcelLocked(in);
14017
Sudheer Shankab2f83c12017-11-13 19:25:01 -080014018 int length = in.readInt();
14019 if (length == Uid.NUM_PROCESS_STATE) {
14020 u.mProcStateTimeMs = new LongSamplingCounterArray[length];
14021 for (int procState = 0; procState < length; ++procState) {
14022 u.mProcStateTimeMs[procState]
14023 = LongSamplingCounterArray.readSummaryFromParcelLocked(
14024 in, mOnBatteryTimeBase);
14025 }
14026 } else {
14027 u.mProcStateTimeMs = null;
14028 }
14029 length = in.readInt();
14030 if (length == Uid.NUM_PROCESS_STATE) {
14031 u.mProcStateScreenOffTimeMs = new LongSamplingCounterArray[length];
14032 for (int procState = 0; procState < length; ++procState) {
14033 u.mProcStateScreenOffTimeMs[procState]
14034 = LongSamplingCounterArray.readSummaryFromParcelLocked(
14035 in, mOnBatteryScreenOffTimeBase);
14036 }
14037 } else {
14038 u.mProcStateScreenOffTimeMs = null;
14039 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070014040
14041 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -070014042 u.mMobileRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
14043 u.mMobileRadioApWakeupCount.readSummaryFromParcelLocked(in);
14044 } else {
14045 u.mMobileRadioApWakeupCount = null;
14046 }
14047
14048 if (in.readInt() != 0) {
14049 u.mWifiRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
14050 u.mWifiRadioApWakeupCount.readSummaryFromParcelLocked(in);
14051 } else {
14052 u.mWifiRadioApWakeupCount = null;
14053 }
14054
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014055 int NW = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070014056 if (NW > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014057 throw new ParcelFormatException("File corrupt: too many wake locks " + NW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014058 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014059 for (int iw = 0; iw < NW; iw++) {
14060 String wlName = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014061 u.readWakeSummaryFromParcelLocked(wlName, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014062 }
14063
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014064 int NS = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070014065 if (NS > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014066 throw new ParcelFormatException("File corrupt: too many syncs " + NS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014067 }
14068 for (int is = 0; is < NS; is++) {
14069 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014070 u.readSyncSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014071 }
14072
14073 int NJ = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070014074 if (NJ > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014075 throw new ParcelFormatException("File corrupt: too many job timers " + NJ);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014076 }
14077 for (int ij = 0; ij < NJ; ij++) {
14078 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014079 u.readJobSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014080 }
14081
Dianne Hackborn94326cb2017-06-28 16:17:20 -070014082 u.readJobCompletionsFromParcelLocked(in);
14083
Amith Yamasani977e11f2018-02-16 11:29:54 -080014084 u.mJobsDeferredEventCount.readSummaryFromParcelLocked(in);
14085 u.mJobsDeferredCount.readSummaryFromParcelLocked(in);
14086 u.mJobsFreshnessTimeMs.readSummaryFromParcelLocked(in);
14087 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
14088 if (in.readInt() != 0) {
14089 u.mJobsFreshnessBuckets[i] = new Counter(u.mBsi.mOnBatteryTimeBase);
14090 u.mJobsFreshnessBuckets[i].readSummaryFromParcelLocked(in);
14091 }
14092 }
14093
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014094 int NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014095 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014096 throw new ParcelFormatException("File corrupt: too many sensors " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014097 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014098 for (int is = 0; is < NP; is++) {
14099 int seNumber = in.readInt();
14100 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -080014101 u.getSensorTimerLocked(seNumber, true).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014102 }
14103 }
14104
14105 NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014106 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014107 throw new ParcelFormatException("File corrupt: too many processes " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014108 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014109 for (int ip = 0; ip < NP; ip++) {
14110 String procName = in.readString();
14111 Uid.Proc p = u.getProcessStatsLocked(procName);
14112 p.mUserTime = p.mLoadedUserTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014113 p.mSystemTime = p.mLoadedSystemTime = in.readLong();
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014114 p.mForegroundTime = p.mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014115 p.mStarts = p.mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014116 p.mNumCrashes = p.mLoadedNumCrashes = in.readInt();
14117 p.mNumAnrs = p.mLoadedNumAnrs = in.readInt();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014118 p.readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014119 }
14120
14121 NP = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014122 if (NP > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014123 throw new ParcelFormatException("File corrupt: too many packages " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014124 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014125 for (int ip = 0; ip < NP; ip++) {
14126 String pkgName = in.readString();
14127 Uid.Pkg p = u.getPackageStatsLocked(pkgName);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014128 final int NWA = in.readInt();
14129 if (NWA > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014130 throw new ParcelFormatException("File corrupt: too many wakeup alarms " + NWA);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014131 }
14132 p.mWakeupAlarms.clear();
14133 for (int iwa=0; iwa<NWA; iwa++) {
14134 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -070014135 Counter c = new Counter(mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014136 c.readSummaryFromParcelLocked(in);
14137 p.mWakeupAlarms.put(tag, c);
14138 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014139 NS = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014140 if (NS > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014141 throw new ParcelFormatException("File corrupt: too many services " + NS);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014142 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014143 for (int is = 0; is < NS; is++) {
14144 String servName = in.readString();
14145 Uid.Pkg.Serv s = u.getServiceStatsLocked(pkgName, servName);
14146 s.mStartTime = s.mLoadedStartTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014147 s.mStarts = s.mLoadedStarts = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014148 s.mLaunches = s.mLoadedLaunches = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014149 }
14150 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014151 }
14152 }
14153
14154 /**
14155 * Writes a summary of the statistics to a Parcel, in a format suitable to be written to
14156 * disk. This format does not allow a lossless round-trip.
14157 *
14158 * @param out the Parcel to be written to.
14159 */
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070014160 public void writeSummaryToParcel(Parcel out, boolean inclHistory) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080014161 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014162
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014163 // Pull the clock time. This may update the time and make a new history entry
14164 // if we had originally pulled a time before the RTC was set.
14165 long startClockTime = getStartClockTime();
14166
Joe Onoratoabded112016-02-08 16:49:39 -080014167 final long NOW_SYS = mClocks.uptimeMillis() * 1000;
14168 final long NOWREAL_SYS = mClocks.elapsedRealtime() * 1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014169
14170 out.writeInt(VERSION);
14171
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070014172 writeHistory(out, inclHistory, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014173
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014174 out.writeInt(mStartCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014175 out.writeLong(computeUptime(NOW_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014176 out.writeLong(computeRealtime(NOWREAL_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014177 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014178 out.writeString(mStartPlatformVersion);
14179 out.writeString(mEndPlatformVersion);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014180 mOnBatteryTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
14181 mOnBatteryScreenOffTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014182 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014183 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070014184 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014185 out.writeInt(mCurrentBatteryLevel);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014186 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070014187 out.writeInt(mMinLearnedBatteryCapacity);
14188 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborne4a59512010-12-07 11:08:07 -080014189 out.writeInt(getLowDischargeAmountSinceCharge());
14190 out.writeInt(getHighDischargeAmountSinceCharge());
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014191 out.writeInt(getDischargeAmountScreenOnSinceCharge());
14192 out.writeInt(getDischargeAmountScreenOffSinceCharge());
Mike Mac2f518a2017-09-19 16:06:03 -070014193 out.writeInt(getDischargeAmountScreenDozeSinceCharge());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014194 mDischargeStepTracker.writeToParcel(out);
14195 mChargeStepTracker.writeToParcel(out);
14196 mDailyDischargeStepTracker.writeToParcel(out);
14197 mDailyChargeStepTracker.writeToParcel(out);
Adam Lesinski67c134f2016-06-10 15:15:08 -070014198 mDischargeCounter.writeSummaryFromParcelLocked(out);
14199 mDischargeScreenOffCounter.writeSummaryFromParcelLocked(out);
Mike Mac2f518a2017-09-19 16:06:03 -070014200 mDischargeScreenDozeCounter.writeSummaryFromParcelLocked(out);
Mike Ma15313c92017-11-15 17:58:21 -080014201 mDischargeLightDozeCounter.writeSummaryFromParcelLocked(out);
14202 mDischargeDeepDozeCounter.writeSummaryFromParcelLocked(out);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014203 if (mDailyPackageChanges != null) {
14204 final int NPKG = mDailyPackageChanges.size();
14205 out.writeInt(NPKG);
14206 for (int i=0; i<NPKG; i++) {
14207 PackageChange pc = mDailyPackageChanges.get(i);
14208 out.writeString(pc.mPackageName);
14209 out.writeInt(pc.mUpdate ? 1 : 0);
Dianne Hackborn3accca02013-09-20 09:32:11 -070014210 out.writeLong(pc.mVersionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014211 }
14212 } else {
14213 out.writeInt(0);
14214 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014215 out.writeLong(mDailyStartTime);
14216 out.writeLong(mNextMinDailyDeadline);
14217 out.writeLong(mNextMaxDailyDeadline);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014218
14219 mScreenOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Mike Mac2f518a2017-09-19 16:06:03 -070014220 mScreenDozeTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070014221 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014222 mScreenBrightnessTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070014223 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070014224 mInteractiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070014225 mPowerSaveModeEnabledTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014226 out.writeLong(mLongestLightIdleTime);
14227 out.writeLong(mLongestFullIdleTime);
14228 mDeviceIdleModeLightTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14229 mDeviceIdleModeFullTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14230 mDeviceLightIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014231 mDeviceIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014232 mPhoneOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Wink Saville52840902011-02-18 12:40:47 -080014233 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014234 mPhoneSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070014235 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014236 mPhoneSignalScanningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070014237 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014238 mPhoneDataConnectionsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070014239 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014240 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014241 mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
14242 mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014243 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014244 mMobileRadioActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14245 mMobileRadioActivePerAppTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014246 mMobileRadioActiveAdjustedTime.writeSummaryFromParcelLocked(out);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080014247 mMobileRadioActiveUnknownTime.writeSummaryFromParcelLocked(out);
14248 mMobileRadioActiveUnknownCount.writeSummaryFromParcelLocked(out);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014249 mWifiMulticastWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014250 mWifiOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14251 mGlobalWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080014252 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014253 mWifiStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080014254 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014255 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
14256 mWifiSupplStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14257 }
14258 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
14259 mWifiSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14260 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014261 mWifiActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14262 mWifiActivity.writeSummaryToParcel(out);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014263 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14264 mGpsSignalQualityTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14265 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014266 mBluetoothActivity.writeSummaryToParcel(out);
14267 mModemActivity.writeSummaryToParcel(out);
14268 out.writeInt(mHasWifiReporting ? 1 : 0);
14269 out.writeInt(mHasBluetoothReporting ? 1 : 0);
14270 out.writeInt(mHasModemReporting ? 1 : 0);
14271
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014272 out.writeInt(mNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070014273 mFlashlightOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014274 mCameraOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014275 mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014276
Bookatz50df7112017-08-04 14:53:26 -070014277 out.writeInt(mRpmStats.size());
14278 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
14279 Timer rpmt = ent.getValue();
14280 if (rpmt != null) {
14281 out.writeInt(1);
14282 out.writeString(ent.getKey());
14283 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14284 } else {
14285 out.writeInt(0);
14286 }
14287 }
14288 out.writeInt(mScreenOffRpmStats.size());
14289 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
14290 Timer rpmt = ent.getValue();
14291 if (rpmt != null) {
14292 out.writeInt(1);
14293 out.writeString(ent.getKey());
14294 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14295 } else {
14296 out.writeInt(0);
14297 }
14298 }
14299
Evan Millarc64edde2009-04-18 12:26:32 -070014300 out.writeInt(mKernelWakelockStats.size());
14301 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
14302 Timer kwlt = ent.getValue();
14303 if (kwlt != null) {
14304 out.writeInt(1);
14305 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014306 kwlt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14307 } else {
14308 out.writeInt(0);
14309 }
14310 }
14311
14312 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014313 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
14314 SamplingTimer timer = ent.getValue();
14315 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014316 out.writeInt(1);
14317 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014318 timer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Evan Millarc64edde2009-04-18 12:26:32 -070014319 } else {
14320 out.writeInt(0);
14321 }
14322 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014323
James Carr3a226052016-07-01 14:49:52 -070014324 out.writeInt(mKernelMemoryStats.size());
14325 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
14326 Timer kmt = mKernelMemoryStats.valueAt(i);
14327 if (kmt != null) {
14328 out.writeInt(1);
14329 out.writeLong(mKernelMemoryStats.keyAt(i));
14330 kmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14331 } else {
14332 out.writeInt(0);
14333 }
14334 }
14335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014336 final int NU = mUidStats.size();
14337 out.writeInt(NU);
14338 for (int iu = 0; iu < NU; iu++) {
14339 out.writeInt(mUidStats.keyAt(iu));
14340 Uid u = mUidStats.valueAt(iu);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014341
Bookatz867c0d72017-03-07 18:23:42 -080014342 u.mOnBatteryBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatzc8c44962017-05-11 12:12:54 -070014343 u.mOnBatteryScreenOffBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatz867c0d72017-03-07 18:23:42 -080014344
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014345 if (u.mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014346 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014347 u.mWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014348 } else {
14349 out.writeInt(0);
14350 }
14351 if (u.mFullWifiLockTimer != null) {
14352 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014353 u.mFullWifiLockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014354 } else {
14355 out.writeInt(0);
14356 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070014357 if (u.mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014358 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014359 u.mWifiScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014360 } else {
14361 out.writeInt(0);
14362 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070014363 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
14364 if (u.mWifiBatchedScanTimer[i] != null) {
14365 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014366 u.mWifiBatchedScanTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Robert Greenwalta029ea12013-09-25 16:38:12 -070014367 } else {
14368 out.writeInt(0);
14369 }
14370 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014371 if (u.mWifiMulticastTimer != null) {
14372 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014373 u.mWifiMulticastTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014374 } else {
14375 out.writeInt(0);
14376 }
14377 if (u.mAudioTurnedOnTimer != null) {
14378 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014379 u.mAudioTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014380 } else {
14381 out.writeInt(0);
14382 }
14383 if (u.mVideoTurnedOnTimer != null) {
14384 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014385 u.mVideoTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014386 } else {
14387 out.writeInt(0);
14388 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014389 if (u.mFlashlightTurnedOnTimer != null) {
14390 out.writeInt(1);
14391 u.mFlashlightTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14392 } else {
14393 out.writeInt(0);
14394 }
14395 if (u.mCameraTurnedOnTimer != null) {
14396 out.writeInt(1);
14397 u.mCameraTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14398 } else {
14399 out.writeInt(0);
14400 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014401 if (u.mForegroundActivityTimer != null) {
14402 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014403 u.mForegroundActivityTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014404 } else {
14405 out.writeInt(0);
14406 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070014407 if (u.mForegroundServiceTimer != null) {
14408 out.writeInt(1);
14409 u.mForegroundServiceTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14410 } else {
14411 out.writeInt(0);
14412 }
Bookatzc8c44962017-05-11 12:12:54 -070014413 if (u.mAggregatedPartialWakelockTimer != null) {
14414 out.writeInt(1);
14415 u.mAggregatedPartialWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14416 } else {
14417 out.writeInt(0);
14418 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014419 if (u.mBluetoothScanTimer != null) {
14420 out.writeInt(1);
14421 u.mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14422 } else {
14423 out.writeInt(0);
14424 }
Bookatzb1f04f32017-05-19 13:57:32 -070014425 if (u.mBluetoothUnoptimizedScanTimer != null) {
14426 out.writeInt(1);
14427 u.mBluetoothUnoptimizedScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14428 } else {
14429 out.writeInt(0);
14430 }
Bookatz956f36bf2017-04-28 09:48:17 -070014431 if (u.mBluetoothScanResultCounter != null) {
14432 out.writeInt(1);
14433 u.mBluetoothScanResultCounter.writeSummaryFromParcelLocked(out);
14434 } else {
14435 out.writeInt(0);
14436 }
Bookatzb1f04f32017-05-19 13:57:32 -070014437 if (u.mBluetoothScanResultBgCounter != null) {
14438 out.writeInt(1);
14439 u.mBluetoothScanResultBgCounter.writeSummaryFromParcelLocked(out);
14440 } else {
14441 out.writeInt(0);
14442 }
Dianne Hackborn61659e52014-07-09 16:13:01 -070014443 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
14444 if (u.mProcessStateTimer[i] != null) {
14445 out.writeInt(1);
14446 u.mProcessStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14447 } else {
14448 out.writeInt(0);
14449 }
14450 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014451 if (u.mVibratorOnTimer != null) {
14452 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014453 u.mVibratorOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014454 } else {
14455 out.writeInt(0);
14456 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014457
Dianne Hackborn617f8772009-03-31 15:04:46 -070014458 if (u.mUserActivityCounters == null) {
14459 out.writeInt(0);
14460 } else {
14461 out.writeInt(1);
14462 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
14463 u.mUserActivityCounters[i].writeSummaryFromParcelLocked(out);
14464 }
14465 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014466
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014467 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014468 out.writeInt(0);
14469 } else {
14470 out.writeInt(1);
14471 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014472 u.mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
14473 u.mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014474 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080014475 u.mMobileRadioActiveTime.writeSummaryFromParcelLocked(out);
14476 u.mMobileRadioActiveCount.writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014477 }
14478
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014479 u.mUserCpuTime.writeSummaryFromParcelLocked(out);
14480 u.mSystemCpuTime.writeSummaryFromParcelLocked(out);
14481
Sudheer Shankaaf857412017-07-21 00:14:24 -070014482 if (u.mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -070014483 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -070014484 out.writeInt(u.mCpuClusterSpeedTimesUs.length);
14485 for (LongSamplingCounter[] cpuSpeeds : u.mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -070014486 if (cpuSpeeds != null) {
14487 out.writeInt(1);
14488 out.writeInt(cpuSpeeds.length);
14489 for (LongSamplingCounter c : cpuSpeeds) {
14490 if (c != null) {
14491 out.writeInt(1);
14492 c.writeSummaryFromParcelLocked(out);
14493 } else {
14494 out.writeInt(0);
14495 }
14496 }
14497 } else {
14498 out.writeInt(0);
14499 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014500 }
Adam Lesinski6832f392015-09-05 18:05:40 -070014501 } else {
14502 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014503 }
14504
Sudheer Shanka59f5c002017-05-15 10:57:15 -070014505 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mCpuFreqTimeMs);
14506 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mScreenOffCpuFreqTimeMs);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070014507
Mike Ma3d422c32017-10-25 11:08:57 -070014508 u.mCpuActiveTimeMs.writeSummaryFromParcelLocked(out);
14509 u.mCpuClusterTimesMs.writeSummaryToParcelLocked(out);
14510
Sudheer Shankab2f83c12017-11-13 19:25:01 -080014511 if (u.mProcStateTimeMs != null) {
14512 out.writeInt(u.mProcStateTimeMs.length);
14513 for (LongSamplingCounterArray counters : u.mProcStateTimeMs) {
14514 LongSamplingCounterArray.writeSummaryToParcelLocked(out, counters);
14515 }
14516 } else {
14517 out.writeInt(0);
14518 }
14519 if (u.mProcStateScreenOffTimeMs != null) {
14520 out.writeInt(u.mProcStateScreenOffTimeMs.length);
14521 for (LongSamplingCounterArray counters : u.mProcStateScreenOffTimeMs) {
14522 LongSamplingCounterArray.writeSummaryToParcelLocked(out, counters);
14523 }
14524 } else {
14525 out.writeInt(0);
14526 }
14527
Adam Lesinski5f056f62016-07-14 16:56:08 -070014528 if (u.mMobileRadioApWakeupCount != null) {
14529 out.writeInt(1);
14530 u.mMobileRadioApWakeupCount.writeSummaryFromParcelLocked(out);
14531 } else {
14532 out.writeInt(0);
14533 }
14534
14535 if (u.mWifiRadioApWakeupCount != null) {
14536 out.writeInt(1);
14537 u.mWifiRadioApWakeupCount.writeSummaryFromParcelLocked(out);
14538 } else {
14539 out.writeInt(0);
14540 }
14541
Dianne Hackbornd953c532014-08-16 18:17:38 -070014542 final ArrayMap<String, Uid.Wakelock> wakeStats = u.mWakelockStats.getMap();
14543 int NW = wakeStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014544 out.writeInt(NW);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014545 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014546 out.writeString(wakeStats.keyAt(iw));
14547 Uid.Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014548 if (wl.mTimerFull != null) {
14549 out.writeInt(1);
14550 wl.mTimerFull.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14551 } else {
14552 out.writeInt(0);
14553 }
14554 if (wl.mTimerPartial != null) {
14555 out.writeInt(1);
14556 wl.mTimerPartial.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14557 } else {
14558 out.writeInt(0);
14559 }
14560 if (wl.mTimerWindow != null) {
14561 out.writeInt(1);
14562 wl.mTimerWindow.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14563 } else {
14564 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014565 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070014566 if (wl.mTimerDraw != null) {
Adam Lesinski9425fe22015-06-19 12:02:13 -070014567 out.writeInt(1);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070014568 wl.mTimerDraw.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9425fe22015-06-19 12:02:13 -070014569 } else {
14570 out.writeInt(0);
14571 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014572 }
14573
Bookatz2bffb5b2017-04-13 11:59:33 -070014574 final ArrayMap<String, DualTimer> syncStats = u.mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014575 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014576 out.writeInt(NS);
14577 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014578 out.writeString(syncStats.keyAt(is));
14579 syncStats.valueAt(is).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014580 }
14581
Bookatzaa4594a2017-03-24 12:39:56 -070014582 final ArrayMap<String, DualTimer> jobStats = u.mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014583 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014584 out.writeInt(NJ);
14585 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014586 out.writeString(jobStats.keyAt(ij));
14587 jobStats.valueAt(ij).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014588 }
14589
Dianne Hackborn94326cb2017-06-28 16:17:20 -070014590 u.writeJobCompletionsToParcelLocked(out);
14591
Amith Yamasani977e11f2018-02-16 11:29:54 -080014592 u.mJobsDeferredEventCount.writeSummaryFromParcelLocked(out);
14593 u.mJobsDeferredCount.writeSummaryFromParcelLocked(out);
14594 u.mJobsFreshnessTimeMs.writeSummaryFromParcelLocked(out);
14595 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
14596 if (u.mJobsFreshnessBuckets[i] != null) {
Adam Lesinski14082082018-02-23 12:35:55 -080014597 out.writeInt(1);
Amith Yamasani977e11f2018-02-16 11:29:54 -080014598 u.mJobsFreshnessBuckets[i].writeSummaryFromParcelLocked(out);
14599 } else {
14600 out.writeInt(0);
14601 }
14602 }
14603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014604 int NSE = u.mSensorStats.size();
14605 out.writeInt(NSE);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014606 for (int ise=0; ise<NSE; ise++) {
14607 out.writeInt(u.mSensorStats.keyAt(ise));
14608 Uid.Sensor se = u.mSensorStats.valueAt(ise);
14609 if (se.mTimer != null) {
14610 out.writeInt(1);
14611 se.mTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14612 } else {
14613 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014614 }
14615 }
14616
14617 int NP = u.mProcessStats.size();
14618 out.writeInt(NP);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014619 for (int ip=0; ip<NP; ip++) {
14620 out.writeString(u.mProcessStats.keyAt(ip));
14621 Uid.Proc ps = u.mProcessStats.valueAt(ip);
14622 out.writeLong(ps.mUserTime);
14623 out.writeLong(ps.mSystemTime);
14624 out.writeLong(ps.mForegroundTime);
14625 out.writeInt(ps.mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014626 out.writeInt(ps.mNumCrashes);
14627 out.writeInt(ps.mNumAnrs);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014628 ps.writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014629 }
14630
14631 NP = u.mPackageStats.size();
14632 out.writeInt(NP);
14633 if (NP > 0) {
14634 for (Map.Entry<String, BatteryStatsImpl.Uid.Pkg> ent
14635 : u.mPackageStats.entrySet()) {
14636 out.writeString(ent.getKey());
14637 Uid.Pkg ps = ent.getValue();
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014638 final int NWA = ps.mWakeupAlarms.size();
14639 out.writeInt(NWA);
14640 for (int iwa=0; iwa<NWA; iwa++) {
14641 out.writeString(ps.mWakeupAlarms.keyAt(iwa));
14642 ps.mWakeupAlarms.valueAt(iwa).writeSummaryFromParcelLocked(out);
14643 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014644 NS = ps.mServiceStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014645 out.writeInt(NS);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014646 for (int is=0; is<NS; is++) {
14647 out.writeString(ps.mServiceStats.keyAt(is));
14648 BatteryStatsImpl.Uid.Pkg.Serv ss = ps.mServiceStats.valueAt(is);
14649 long time = ss.getStartTimeToNowLocked(
14650 mOnBatteryTimeBase.getUptime(NOW_SYS));
14651 out.writeLong(time);
14652 out.writeInt(ss.mStarts);
14653 out.writeInt(ss.mLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014654 }
14655 }
14656 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014657 }
14658 }
14659
14660 public void readFromParcel(Parcel in) {
14661 readFromParcelLocked(in);
14662 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014664 void readFromParcelLocked(Parcel in) {
14665 int magic = in.readInt();
14666 if (magic != MAGIC) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014667 throw new ParcelFormatException("Bad magic number: #" + Integer.toHexString(magic));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014668 }
14669
Dianne Hackbornae384452011-06-28 12:33:48 -070014670 readHistory(in, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014672 mStartCount = in.readInt();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080014673 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014674 mStartPlatformVersion = in.readString();
14675 mEndPlatformVersion = in.readString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014676 mUptime = in.readLong();
14677 mUptimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014678 mRealtime = in.readLong();
14679 mRealtimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014680 mOnBattery = in.readInt() != 0;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014681 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070014682 mMinLearnedBatteryCapacity = in.readInt();
14683 mMaxLearnedBatteryCapacity = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014684 mOnBatteryInternal = false; // we are no longer really running.
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014685 mOnBatteryTimeBase.readFromParcel(in);
14686 mOnBatteryScreenOffTimeBase.readFromParcel(in);
14687
Jeff Browne95c3cd2014-05-02 16:59:26 -070014688 mScreenState = Display.STATE_UNKNOWN;
Joe Onoratoabded112016-02-08 16:49:39 -080014689 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070014690 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014691 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014692 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
14693 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014694 }
Dianne Hackborn29325132014-05-21 15:01:03 -070014695 mInteractive = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014696 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014697 mPhoneOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014698 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
14699 mOnBatteryTimeBase, in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014700 mLongestLightIdleTime = in.readLong();
14701 mLongestFullIdleTime = in.readLong();
Joe Onoratoabded112016-02-08 16:49:39 -080014702 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -14, null,
14703 mOnBatteryTimeBase, in);
14704 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -11, null,
14705 mOnBatteryTimeBase, in);
14706 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null,
14707 mOnBatteryTimeBase, in);
14708 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase, in);
14709 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014710 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014711 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014712 null, mOnBatteryTimeBase, in);
14713 }
Joe Onoratoabded112016-02-08 16:49:39 -080014714 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
14715 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014716 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014717 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014718 null, mOnBatteryTimeBase, in);
14719 }
14720 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
14721 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
14722 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
14723 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014724 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Joe Onoratoabded112016-02-08 16:49:39 -080014725 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null,
14726 mOnBatteryTimeBase, in);
Kweku Adams87b19ec2017-10-09 12:40:03 -070014727 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
Joe Onoratoabded112016-02-08 16:49:39 -080014728 mOnBatteryTimeBase, in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014729 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014730 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
14731 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase, in);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014732 mWifiMulticastWakelockTimer = new StopwatchTimer(mClocks, null, -4, null,
14733 mOnBatteryTimeBase, in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070014734 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014735 mWifiOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014736 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014737 mGlobalWifiRunning = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014738 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null,
14739 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014740 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014741 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014742 null, mOnBatteryTimeBase, in);
14743 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014744 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014745 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070014746 null, mOnBatteryTimeBase, in);
14747 }
14748 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014749 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070014750 null, mOnBatteryTimeBase, in);
14751 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014752 mWifiActiveTimer = new StopwatchTimer(mClocks, null, -900, null,
14753 mOnBatteryTimeBase, in);
14754 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14755 NUM_WIFI_TX_LEVELS, in);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014756 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14757 mGpsSignalQualityTimer[i] = new StopwatchTimer(mClocks, null, -1000-i,
14758 null, mOnBatteryTimeBase, in);
14759 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014760 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14761 NUM_BT_TX_LEVELS, in);
14762 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14763 ModemActivityInfo.TX_POWER_LEVELS, in);
14764 mHasWifiReporting = in.readInt() != 0;
14765 mHasBluetoothReporting = in.readInt() != 0;
14766 mHasModemReporting = in.readInt() != 0;
14767
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014768 mNumConnectivityChange = in.readInt();
14769 mLoadedNumConnectivityChange = in.readInt();
14770 mUnpluggedNumConnectivityChange = in.readInt();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014771 mAudioOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014772 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014773 mVideoOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014774 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014775 mFlashlightOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014776 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014777 mCameraOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014778 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014779 mBluetoothScanNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014780 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase, in);
Siddharth Rayf5e796a2018-01-22 18:18:17 -080014781 mIsCellularTxPowerHigh = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014782 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014783 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070014784 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014785 mCurrentBatteryLevel = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014786 mLowDischargeAmountSinceCharge = in.readInt();
14787 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014788 mDischargeAmountScreenOn = in.readInt();
14789 mDischargeAmountScreenOnSinceCharge = in.readInt();
14790 mDischargeAmountScreenOff = in.readInt();
14791 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070014792 mDischargeAmountScreenDoze = in.readInt();
14793 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014794 mDischargeStepTracker.readFromParcel(in);
14795 mChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070014796 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070014797 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase, in);
14798 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Ma15313c92017-11-15 17:58:21 -080014799 mDischargeLightDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
14800 mDischargeDeepDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014801 mLastWriteTime = in.readLong();
14802
Bookatz50df7112017-08-04 14:53:26 -070014803 mRpmStats.clear();
14804 int NRPMS = in.readInt();
14805 for (int irpm = 0; irpm < NRPMS; irpm++) {
14806 if (in.readInt() != 0) {
14807 String rpmName = in.readString();
14808 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
14809 mRpmStats.put(rpmName, rpmt);
14810 }
14811 }
14812 mScreenOffRpmStats.clear();
14813 int NSORPMS = in.readInt();
14814 for (int irpm = 0; irpm < NSORPMS; irpm++) {
14815 if (in.readInt() != 0) {
14816 String rpmName = in.readString();
14817 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
14818 mScreenOffRpmStats.put(rpmName, rpmt);
14819 }
14820 }
14821
Evan Millarc64edde2009-04-18 12:26:32 -070014822 mKernelWakelockStats.clear();
14823 int NKW = in.readInt();
14824 for (int ikw = 0; ikw < NKW; ikw++) {
14825 if (in.readInt() != 0) {
14826 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080014827 SamplingTimer kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -070014828 mKernelWakelockStats.put(wakelockName, kwlt);
14829 }
14830 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014831
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014832 mWakeupReasonStats.clear();
14833 int NWR = in.readInt();
14834 for (int iwr = 0; iwr < NWR; iwr++) {
14835 if (in.readInt() != 0) {
14836 String reasonName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080014837 SamplingTimer timer = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014838 mWakeupReasonStats.put(reasonName, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014839 }
14840 }
14841
James Carr3a226052016-07-01 14:49:52 -070014842 mKernelMemoryStats.clear();
14843 int nmt = in.readInt();
14844 for (int imt = 0; imt < nmt; imt++) {
14845 if (in.readInt() != 0) {
14846 Long bucket = in.readLong();
14847 SamplingTimer kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
14848 mKernelMemoryStats.put(bucket, kmt);
14849 }
14850 }
14851
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014852 mPartialTimers.clear();
14853 mFullTimers.clear();
14854 mWindowTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014855 mWifiRunningTimers.clear();
14856 mFullWifiLockTimers.clear();
Nick Pelly6ccaa542012-06-15 15:22:47 -070014857 mWifiScanTimers.clear();
Robert Greenwalta029ea12013-09-25 16:38:12 -070014858 mWifiBatchedScanTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014859 mWifiMulticastTimers.clear();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014860 mAudioTurnedOnTimers.clear();
14861 mVideoTurnedOnTimers.clear();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014862 mFlashlightTurnedOnTimers.clear();
14863 mCameraTurnedOnTimers.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014864
14865 int numUids = in.readInt();
14866 mUidStats.clear();
14867 for (int i = 0; i < numUids; i++) {
14868 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080014869 Uid u = new Uid(this, uid);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014870 u.readFromParcelLocked(mOnBatteryTimeBase, mOnBatteryScreenOffTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014871 mUidStats.append(uid, u);
14872 }
14873 }
14874
14875 public void writeToParcel(Parcel out, int flags) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014876 writeToParcelLocked(out, true, flags);
14877 }
14878
14879 public void writeToParcelWithoutUids(Parcel out, int flags) {
14880 writeToParcelLocked(out, false, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014881 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014882
14883 @SuppressWarnings("unused")
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014884 void writeToParcelLocked(Parcel out, boolean inclUids, int flags) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014885 // Need to update with current kernel wake lock counts.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080014886 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014887
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014888 // Pull the clock time. This may update the time and make a new history entry
14889 // if we had originally pulled a time before the RTC was set.
14890 long startClockTime = getStartClockTime();
14891
Joe Onoratoabded112016-02-08 16:49:39 -080014892 final long uSecUptime = mClocks.uptimeMillis() * 1000;
14893 final long uSecRealtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014894 final long batteryRealtime = mOnBatteryTimeBase.getRealtime(uSecRealtime);
14895 final long batteryScreenOffRealtime = mOnBatteryScreenOffTimeBase.getRealtime(uSecRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014896
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014897 out.writeInt(MAGIC);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014898
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070014899 writeHistory(out, true, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014901 out.writeInt(mStartCount);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014902 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014903 out.writeString(mStartPlatformVersion);
14904 out.writeString(mEndPlatformVersion);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014905 out.writeLong(mUptime);
14906 out.writeLong(mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014907 out.writeLong(mRealtime);
14908 out.writeLong(mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014909 out.writeInt(mOnBattery ? 1 : 0);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014910 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070014911 out.writeInt(mMinLearnedBatteryCapacity);
14912 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014913 mOnBatteryTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
14914 mOnBatteryScreenOffTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
14915
14916 mScreenOnTimer.writeToParcel(out, uSecRealtime);
Mike Mac2f518a2017-09-19 16:06:03 -070014917 mScreenDozeTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014918 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
14919 mScreenBrightnessTimer[i].writeToParcel(out, uSecRealtime);
14920 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070014921 mInteractiveTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070014922 mPowerSaveModeEnabledTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014923 out.writeLong(mLongestLightIdleTime);
14924 out.writeLong(mLongestFullIdleTime);
14925 mDeviceIdleModeLightTimer.writeToParcel(out, uSecRealtime);
14926 mDeviceIdleModeFullTimer.writeToParcel(out, uSecRealtime);
14927 mDeviceLightIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014928 mDeviceIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014929 mPhoneOnTimer.writeToParcel(out, uSecRealtime);
14930 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
14931 mPhoneSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
14932 }
14933 mPhoneSignalScanningTimer.writeToParcel(out, uSecRealtime);
14934 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
14935 mPhoneDataConnectionsTimer[i].writeToParcel(out, uSecRealtime);
14936 }
14937 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
14938 mNetworkByteActivityCounters[i].writeToParcel(out);
14939 mNetworkPacketActivityCounters[i].writeToParcel(out);
14940 }
14941 mMobileRadioActiveTimer.writeToParcel(out, uSecRealtime);
14942 mMobileRadioActivePerAppTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014943 mMobileRadioActiveAdjustedTime.writeToParcel(out);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014944 mMobileRadioActiveUnknownTime.writeToParcel(out);
14945 mMobileRadioActiveUnknownCount.writeToParcel(out);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014946 mWifiMulticastWakelockTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014947 mWifiOnTimer.writeToParcel(out, uSecRealtime);
14948 mGlobalWifiRunningTimer.writeToParcel(out, uSecRealtime);
14949 for (int i=0; i<NUM_WIFI_STATES; i++) {
14950 mWifiStateTimer[i].writeToParcel(out, uSecRealtime);
14951 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014952 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
14953 mWifiSupplStateTimer[i].writeToParcel(out, uSecRealtime);
14954 }
14955 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
14956 mWifiSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
14957 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014958 mWifiActiveTimer.writeToParcel(out, uSecRealtime);
14959 mWifiActivity.writeToParcel(out, 0);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014960 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14961 mGpsSignalQualityTimer[i].writeToParcel(out, uSecRealtime);
14962 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014963 mBluetoothActivity.writeToParcel(out, 0);
14964 mModemActivity.writeToParcel(out, 0);
14965 out.writeInt(mHasWifiReporting ? 1 : 0);
14966 out.writeInt(mHasBluetoothReporting ? 1 : 0);
14967 out.writeInt(mHasModemReporting ? 1 : 0);
14968
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014969 out.writeInt(mNumConnectivityChange);
14970 out.writeInt(mLoadedNumConnectivityChange);
14971 out.writeInt(mUnpluggedNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070014972 mFlashlightOnTimer.writeToParcel(out, uSecRealtime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014973 mCameraOnTimer.writeToParcel(out, uSecRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014974 mBluetoothScanTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014975 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014976 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070014977 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014978 out.writeInt(mCurrentBatteryLevel);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014979 out.writeInt(mLowDischargeAmountSinceCharge);
14980 out.writeInt(mHighDischargeAmountSinceCharge);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014981 out.writeInt(mDischargeAmountScreenOn);
14982 out.writeInt(mDischargeAmountScreenOnSinceCharge);
14983 out.writeInt(mDischargeAmountScreenOff);
14984 out.writeInt(mDischargeAmountScreenOffSinceCharge);
Mike Mac2f518a2017-09-19 16:06:03 -070014985 out.writeInt(mDischargeAmountScreenDoze);
14986 out.writeInt(mDischargeAmountScreenDozeSinceCharge);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014987 mDischargeStepTracker.writeToParcel(out);
14988 mChargeStepTracker.writeToParcel(out);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070014989 mDischargeCounter.writeToParcel(out);
14990 mDischargeScreenOffCounter.writeToParcel(out);
Mike Mac2f518a2017-09-19 16:06:03 -070014991 mDischargeScreenDozeCounter.writeToParcel(out);
Mike Ma15313c92017-11-15 17:58:21 -080014992 mDischargeLightDozeCounter.writeToParcel(out);
14993 mDischargeDeepDozeCounter.writeToParcel(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014994 out.writeLong(mLastWriteTime);
14995
Bookatz50df7112017-08-04 14:53:26 -070014996 out.writeInt(mRpmStats.size());
14997 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
14998 SamplingTimer rpmt = ent.getValue();
14999 if (rpmt != null) {
15000 out.writeInt(1);
15001 out.writeString(ent.getKey());
15002 rpmt.writeToParcel(out, uSecRealtime);
15003 } else {
15004 out.writeInt(0);
15005 }
15006 }
15007 out.writeInt(mScreenOffRpmStats.size());
15008 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
15009 SamplingTimer rpmt = ent.getValue();
15010 if (rpmt != null) {
15011 out.writeInt(1);
15012 out.writeString(ent.getKey());
15013 rpmt.writeToParcel(out, uSecRealtime);
15014 } else {
15015 out.writeInt(0);
15016 }
15017 }
15018
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015019 if (inclUids) {
15020 out.writeInt(mKernelWakelockStats.size());
15021 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
15022 SamplingTimer kwlt = ent.getValue();
15023 if (kwlt != null) {
15024 out.writeInt(1);
15025 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070015026 kwlt.writeToParcel(out, uSecRealtime);
15027 } else {
15028 out.writeInt(0);
15029 }
15030 }
15031 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070015032 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
15033 SamplingTimer timer = ent.getValue();
15034 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070015035 out.writeInt(1);
15036 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070015037 timer.writeToParcel(out, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015038 } else {
15039 out.writeInt(0);
15040 }
Evan Millarc64edde2009-04-18 12:26:32 -070015041 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015042 } else {
Bookatzba78b2b2017-10-10 11:06:33 -070015043 out.writeInt(0);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015044 out.writeInt(0);
Evan Millarc64edde2009-04-18 12:26:32 -070015045 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070015046
James Carr3a226052016-07-01 14:49:52 -070015047 out.writeInt(mKernelMemoryStats.size());
15048 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
15049 SamplingTimer kmt = mKernelMemoryStats.valueAt(i);
15050 if (kmt != null) {
15051 out.writeInt(1);
15052 out.writeLong(mKernelMemoryStats.keyAt(i));
15053 kmt.writeToParcel(out, uSecRealtime);
15054 } else {
15055 out.writeInt(0);
15056 }
15057 }
15058
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015059 if (inclUids) {
15060 int size = mUidStats.size();
15061 out.writeInt(size);
15062 for (int i = 0; i < size; i++) {
15063 out.writeInt(mUidStats.keyAt(i));
15064 Uid uid = mUidStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015065
Bookatz867c0d72017-03-07 18:23:42 -080015066 uid.writeToParcelLocked(out, uSecUptime, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015067 }
15068 } else {
15069 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015070 }
15071 }
15072
15073 public static final Parcelable.Creator<BatteryStatsImpl> CREATOR =
15074 new Parcelable.Creator<BatteryStatsImpl>() {
15075 public BatteryStatsImpl createFromParcel(Parcel in) {
15076 return new BatteryStatsImpl(in);
15077 }
15078
15079 public BatteryStatsImpl[] newArray(int size) {
15080 return new BatteryStatsImpl[size];
15081 }
15082 };
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070015083
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070015084 public void prepareForDumpLocked() {
15085 // Need to retrieve current kernel wake lock stats before printing.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080015086 pullPendingStateUpdatesLocked();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070015087
15088 // Pull the clock time. This may update the time and make a new history entry
15089 // if we had originally pulled a time before the RTC was set.
15090 getStartClockTime();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070015091 }
15092
Dianne Hackbornc51cf032014-03-02 19:08:15 -080015093 public void dumpLocked(Context context, PrintWriter pw, int flags, int reqUid, long histStart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015094 if (DEBUG) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080015095 pw.println("mOnBatteryTimeBase:");
15096 mOnBatteryTimeBase.dump(pw, " ");
15097 pw.println("mOnBatteryScreenOffTimeBase:");
15098 mOnBatteryScreenOffTimeBase.dump(pw, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015099 Printer pr = new PrintWriterPrinter(pw);
Mike Mac2f518a2017-09-19 16:06:03 -070015100 pr.println("*** Screen on timer:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015101 mScreenOnTimer.logState(pr, " ");
Mike Mac2f518a2017-09-19 16:06:03 -070015102 pr.println("*** Screen doze timer:");
15103 mScreenDozeTimer.logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070015104 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015105 pr.println("*** Screen brightness #" + i + ":");
15106 mScreenBrightnessTimer[i].logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070015107 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070015108 pr.println("*** Interactive timer:");
15109 mInteractiveTimer.logState(pr, " ");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070015110 pr.println("*** Power save mode timer:");
15111 mPowerSaveModeEnabledTimer.logState(pr, " ");
Dianne Hackborn08c47a52015-10-15 12:38:14 -070015112 pr.println("*** Device idle mode light timer:");
15113 mDeviceIdleModeLightTimer.logState(pr, " ");
15114 pr.println("*** Device idle mode full timer:");
15115 mDeviceIdleModeFullTimer.logState(pr, " ");
15116 pr.println("*** Device light idling timer:");
15117 mDeviceLightIdlingTimer.logState(pr, " ");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070015118 pr.println("*** Device idling timer:");
15119 mDeviceIdlingTimer.logState(pr, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015120 pr.println("*** Phone timer:");
15121 mPhoneOnTimer.logState(pr, " ");
Wink Saville52840902011-02-18 12:40:47 -080015122 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3251b902014-06-20 14:40:53 -070015123 pr.println("*** Phone signal strength #" + i + ":");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015124 mPhoneSignalStrengthsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070015125 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070015126 pr.println("*** Signal scanning :");
15127 mPhoneSignalScanningTimer.logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070015128 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015129 pr.println("*** Data connection type #" + i + ":");
15130 mPhoneDataConnectionsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070015131 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070015132 pr.println("*** mMobileRadioPowerState=" + mMobileRadioPowerState);
Dianne Hackborne13c4c02014-02-11 17:18:35 -080015133 pr.println("*** Mobile network active timer:");
15134 mMobileRadioActiveTimer.logState(pr, " ");
Dianne Hackborna1bd7922014-03-21 11:07:11 -070015135 pr.println("*** Mobile network active adjusted timer:");
15136 mMobileRadioActiveAdjustedTime.logState(pr, " ");
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080015137 pr.println("*** Wifi Multicast WakeLock Timer:");
15138 mWifiMulticastWakelockTimer.logState(pr, " ");
Dianne Hackborn0c820db2015-04-14 17:47:34 -070015139 pr.println("*** mWifiRadioPowerState=" + mWifiRadioPowerState);
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015140 pr.println("*** Wifi timer:");
15141 mWifiOnTimer.logState(pr, " ");
15142 pr.println("*** WifiRunning timer:");
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070015143 mGlobalWifiRunningTimer.logState(pr, " ");
Dianne Hackbornca1bf212014-02-14 14:18:36 -080015144 for (int i=0; i<NUM_WIFI_STATES; i++) {
15145 pr.println("*** Wifi state #" + i + ":");
15146 mWifiStateTimer[i].logState(pr, " ");
15147 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070015148 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
15149 pr.println("*** Wifi suppl state #" + i + ":");
15150 mWifiSupplStateTimer[i].logState(pr, " ");
15151 }
15152 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
15153 pr.println("*** Wifi signal strength #" + i + ":");
15154 mWifiSignalStrengthsTimer[i].logState(pr, " ");
15155 }
Siddharth Ray78ccaf52017-12-23 16:16:21 -080015156 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
15157 pr.println("*** GPS signal quality #" + i + ":");
15158 mGpsSignalQualityTimer[i].logState(pr, " ");
15159 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -070015160 pr.println("*** Flashlight timer:");
15161 mFlashlightOnTimer.logState(pr, " ");
Ruben Brunk6d2c3632015-05-26 17:32:16 -070015162 pr.println("*** Camera timer:");
15163 mCameraOnTimer.logState(pr, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015164 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -080015165 super.dumpLocked(context, pw, flags, reqUid, histStart);
Sudheer Shankac20379e2018-02-15 00:06:21 -080015166 pw.print("Total cpu time reads: ");
Mike Ma234d1822018-03-13 18:53:21 -070015167 pw.println(mNumSingleUidCpuTimeReads);
Sudheer Shankac20379e2018-02-15 00:06:21 -080015168 pw.print("Batched cpu time reads: ");
Mike Ma234d1822018-03-13 18:53:21 -070015169 pw.println(mNumBatchedSingleUidCpuTimeReads);
Sudheer Shankac20379e2018-02-15 00:06:21 -080015170 pw.print("Batching Duration (min): ");
15171 pw.println((mClocks.uptimeMillis() - mCpuTimeReadsTrackingStartTime) / (60 * 1000));
Mike Ma234d1822018-03-13 18:53:21 -070015172 pw.print("All UID cpu time reads since the later of device start or stats reset: ");
15173 pw.println(mNumAllUidCpuTimeReads);
15174 pw.print("UIDs removed since the later of device start or stats reset: ");
15175 pw.println(mNumUidsRemoved);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015176 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015177}