blob: 5da3874dbcec2e68fd50cc46dabb2cf5af9d0394 [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();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700582 }
583
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800584 public Handler mHandler;
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700585 private ExternalStatsSync mExternalSync = null;
Sudheer Shanka38383232017-07-25 09:55:03 -0700586 @VisibleForTesting
587 protected UserInfoProvider mUserInfoProvider = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700588
589 private BatteryCallback mCallback;
590
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800591 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -0800592 * Mapping isolated uids to the actual owning app uid.
593 */
594 final SparseIntArray mIsolatedUids = new SparseIntArray();
595
596 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800597 * The statistics we have collected organized by uids.
598 */
Adam Lesinski50e47602015-12-04 17:04:54 -0800599 final SparseArray<BatteryStatsImpl.Uid> mUidStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800600
601 // A set of pools of currently active timers. When a timer is queried, we will divide the
602 // elapsed time by the number of active timers to arrive at that timer's share of the time.
603 // In order to do this, we must refresh each timer whenever the number of active timers
604 // changes.
Sudheer Shanka38383232017-07-25 09:55:03 -0700605 @VisibleForTesting
606 protected ArrayList<StopwatchTimer> mPartialTimers = new ArrayList<>();
Adam Lesinskie08af192015-03-25 16:42:59 -0700607 final ArrayList<StopwatchTimer> mFullTimers = new ArrayList<>();
608 final ArrayList<StopwatchTimer> mWindowTimers = new ArrayList<>();
Jeff Brown6a8bd7b2015-06-19 15:07:51 -0700609 final ArrayList<StopwatchTimer> mDrawTimers = new ArrayList<>();
Adam Lesinskie08af192015-03-25 16:42:59 -0700610 final SparseArray<ArrayList<StopwatchTimer>> mSensorTimers = new SparseArray<>();
611 final ArrayList<StopwatchTimer> mWifiRunningTimers = new ArrayList<>();
612 final ArrayList<StopwatchTimer> mFullWifiLockTimers = new ArrayList<>();
613 final ArrayList<StopwatchTimer> mWifiMulticastTimers = new ArrayList<>();
614 final ArrayList<StopwatchTimer> mWifiScanTimers = new ArrayList<>();
615 final SparseArray<ArrayList<StopwatchTimer>> mWifiBatchedScanTimers = new SparseArray<>();
616 final ArrayList<StopwatchTimer> mAudioTurnedOnTimers = new ArrayList<>();
617 final ArrayList<StopwatchTimer> mVideoTurnedOnTimers = new ArrayList<>();
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700618 final ArrayList<StopwatchTimer> mFlashlightTurnedOnTimers = new ArrayList<>();
619 final ArrayList<StopwatchTimer> mCameraTurnedOnTimers = new ArrayList<>();
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800620 final ArrayList<StopwatchTimer> mBluetoothScanOnTimers = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800621
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700622 // Last partial timers we use for distributing CPU usage.
Sudheer Shanka38383232017-07-25 09:55:03 -0700623 @VisibleForTesting
624 protected ArrayList<StopwatchTimer> mLastPartialTimers = new ArrayList<>();
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626 // These are the objects that will want to do something when the device
627 // is unplugged from power.
Joe Onoratoabded112016-02-08 16:49:39 -0800628 protected final TimeBase mOnBatteryTimeBase = new TimeBase();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800629
630 // These are the objects that will want to do something when the device
Mike Mac2f518a2017-09-19 16:06:03 -0700631 // is unplugged from power *and* the screen is off or doze.
632 protected final TimeBase mOnBatteryScreenOffTimeBase = new TimeBase();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800633
634 // Set to true when we want to distribute CPU across wakelocks for the next
635 // CPU update, even if we aren't currently running wake locks.
636 boolean mDistributeWakelockCpu;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700637
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700638 boolean mShuttingDown;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700639
Dianne Hackborn37de0982014-05-09 09:32:18 -0700640 final HistoryEventTracker mActiveEvents = new HistoryEventTracker();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800641
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700642 long mHistoryBaseTime;
Narayan Kamath695cf722017-12-21 18:32:47 +0000643 protected boolean mHaveBatteryLevel = false;
644 protected boolean mRecordingHistory = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700645 int mNumHistoryItems;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700646
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700647 final Parcel mHistoryBuffer = Parcel.obtain();
648 final HistoryItem mHistoryLastWritten = new HistoryItem();
649 final HistoryItem mHistoryLastLastWritten = new HistoryItem();
Dianne Hackborn1fadab52011-04-14 17:57:33 -0700650 final HistoryItem mHistoryReadTmp = new HistoryItem();
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700651 final HistoryItem mHistoryAddTmp = new HistoryItem();
Adam Lesinskie08af192015-03-25 16:42:59 -0700652 final HashMap<HistoryTag, Integer> mHistoryTagPool = new HashMap<>();
Dianne Hackborn099bc622014-01-22 13:39:16 -0800653 String[] mReadHistoryStrings;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -0800654 int[] mReadHistoryUids;
655 int mReadHistoryChars;
656 int mNextHistoryTagIdx = 0;
657 int mNumHistoryTagChars = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700658 int mHistoryBufferLastPos = -1;
659 boolean mHistoryOverflow = false;
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700660 int mActiveHistoryStates = 0xffffffff;
661 int mActiveHistoryStates2 = 0xffffffff;
Dianne Hackborn40c87252014-03-19 16:55:40 -0700662 long mLastHistoryElapsedRealtime = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700663 long mTrackRunningHistoryElapsedRealtime = 0;
664 long mTrackRunningHistoryUptime = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700665
666 final HistoryItem mHistoryCur = new HistoryItem();
667
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700668 HistoryItem mHistory;
669 HistoryItem mHistoryEnd;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700670 HistoryItem mHistoryLastEnd;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700671 HistoryItem mHistoryCache;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700672
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800673 // Used by computeHistoryStepDetails
674 HistoryStepDetails mLastHistoryStepDetails = null;
675 byte mLastHistoryStepLevel = 0;
676 final HistoryStepDetails mCurHistoryStepDetails = new HistoryStepDetails();
677 final HistoryStepDetails mReadHistoryStepDetails = new HistoryStepDetails();
678 final HistoryStepDetails mTmpHistoryStepDetails = new HistoryStepDetails();
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700679
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800680 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700681 * Total time (in milliseconds) spent executing in user code.
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800682 */
683 long mLastStepCpuUserTime;
684 long mCurStepCpuUserTime;
685 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700686 * Total time (in milliseconds) spent executing in kernel code.
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800687 */
688 long mLastStepCpuSystemTime;
689 long mCurStepCpuSystemTime;
690 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700691 * Times from /proc/stat (but measured in milliseconds).
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800692 */
693 long mLastStepStatUserTime;
694 long mLastStepStatSystemTime;
695 long mLastStepStatIOWaitTime;
696 long mLastStepStatIrqTime;
697 long mLastStepStatSoftIrqTime;
698 long mLastStepStatIdleTime;
699 long mCurStepStatUserTime;
700 long mCurStepStatSystemTime;
701 long mCurStepStatIOWaitTime;
702 long mCurStepStatIrqTime;
703 long mCurStepStatSoftIrqTime;
704 long mCurStepStatIdleTime;
705
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700706 private HistoryItem mHistoryIterator;
707 private boolean mReadOverflow;
708 private boolean mIteratingHistory;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800710 int mStartCount;
711
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -0800712 long mStartClockTime;
Dianne Hackborncd0e3352014-08-07 17:08:09 -0700713 String mStartPlatformVersion;
714 String mEndPlatformVersion;
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -0800715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 long mUptime;
717 long mUptimeStart;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 long mRealtime;
719 long mRealtimeStart;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700720
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800721 int mWakeLockNesting;
722 boolean mWakeLockImportant;
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700723 public boolean mRecordAllHistory;
Dianne Hackborn9a755432014-05-15 17:05:22 -0700724 boolean mNoAutoReset;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800725
Mike Mac2f518a2017-09-19 16:06:03 -0700726 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
727 protected int mScreenState = Display.STATE_UNKNOWN;
728 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
729 protected StopwatchTimer mScreenOnTimer;
730 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
731 protected StopwatchTimer mScreenDozeTimer;
Amith Yamasani3718aaa2009-06-09 06:32:35 -0700732
Dianne Hackborn617f8772009-03-31 15:04:46 -0700733 int mScreenBrightnessBin = -1;
Evan Millarc64edde2009-04-18 12:26:32 -0700734 final StopwatchTimer[] mScreenBrightnessTimer = new StopwatchTimer[NUM_SCREEN_BRIGHTNESS_BINS];
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700735
Amith Yamasani674c9bb2017-02-01 09:45:17 -0800736 boolean mPretendScreenOff;
737
Jeff Browne95c3cd2014-05-02 16:59:26 -0700738 boolean mInteractive;
739 StopwatchTimer mInteractiveTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700740
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700741 boolean mPowerSaveModeEnabled;
742 StopwatchTimer mPowerSaveModeEnabledTimer;
743
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700744 boolean mDeviceIdling;
745 StopwatchTimer mDeviceIdlingTimer;
746
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700747 boolean mDeviceLightIdling;
748 StopwatchTimer mDeviceLightIdlingTimer;
749
750 int mDeviceIdleMode;
751 long mLastIdleTimeStart;
752 long mLongestLightIdleTime;
753 long mLongestFullIdleTime;
754 StopwatchTimer mDeviceIdleModeLightTimer;
755 StopwatchTimer mDeviceIdleModeFullTimer;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800757 boolean mPhoneOn;
Evan Millarc64edde2009-04-18 12:26:32 -0700758 StopwatchTimer mPhoneOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700759
Dianne Hackborn10eaa852014-07-22 22:54:55 -0700760 int mAudioOnNesting;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700761 StopwatchTimer mAudioOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700762
Dianne Hackborn10eaa852014-07-22 22:54:55 -0700763 int mVideoOnNesting;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700764 StopwatchTimer mVideoOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700765
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700766 int mFlashlightOnNesting;
Dianne Hackbornabc7c492014-06-30 16:57:46 -0700767 StopwatchTimer mFlashlightOnTimer;
768
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700769 int mCameraOnNesting;
770 StopwatchTimer mCameraOnTimer;
771
Mike Mafbc01fc2018-04-02 10:28:28 -0700772 private static final int USB_DATA_UNKNOWN = 0;
773 private static final int USB_DATA_DISCONNECTED = 1;
774 private static final int USB_DATA_CONNECTED = 2;
775 int mUsbDataState = USB_DATA_UNKNOWN;
Mike Ma926a97c2018-03-25 02:32:35 -0700776
Siddharth Ray78ccaf52017-12-23 16:16:21 -0800777 int mGpsSignalQualityBin = -1;
Narayan Kamathefa0fe62018-02-05 16:04:43 +0000778 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
779 protected final StopwatchTimer[] mGpsSignalQualityTimer =
Siddharth Ray78ccaf52017-12-23 16:16:21 -0800780 new StopwatchTimer[GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS];
781
Dianne Hackborn627bba72009-03-24 22:32:56 -0700782 int mPhoneSignalStrengthBin = -1;
Dianne Hackborne4a59512010-12-07 11:08:07 -0800783 int mPhoneSignalStrengthBinRaw = -1;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700784 final StopwatchTimer[] mPhoneSignalStrengthsTimer =
Wink Saville52840902011-02-18 12:40:47 -0800785 new StopwatchTimer[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
Amith Yamasanif37447b2009-10-08 18:28:01 -0700786
787 StopwatchTimer mPhoneSignalScanningTimer;
788
Dianne Hackborn627bba72009-03-24 22:32:56 -0700789 int mPhoneDataConnectionType = -1;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700790 final StopwatchTimer[] mPhoneDataConnectionsTimer =
Evan Millarc64edde2009-04-18 12:26:32 -0700791 new StopwatchTimer[NUM_DATA_CONNECTION_TYPES];
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700792
Dianne Hackborn57ed6a62013-12-09 18:15:56 -0800793 final LongSamplingCounter[] mNetworkByteActivityCounters =
794 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
795 final LongSamplingCounter[] mNetworkPacketActivityCounters =
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700796 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
797
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800798 /**
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -0800799 * The WiFi Overall wakelock timer
800 * This timer tracks the actual aggregate time for which MC wakelocks are enabled
801 * since addition of per UID timers would not result in an accurate value due to overlapp of
802 * per uid wakelock timers
803 */
804 StopwatchTimer mWifiMulticastWakelockTimer;
805
806 /**
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800807 * The WiFi controller activity (time in tx, rx, idle, and power consumed) for the device.
808 */
809 ControllerActivityCounterImpl mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -0700810
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800811 /**
812 * The Bluetooth controller activity (time in tx, rx, idle, and power consumed) for the device.
813 */
814 ControllerActivityCounterImpl mBluetoothActivity;
815
816 /**
817 * The Modem controller activity (time in tx, rx, idle, and power consumed) for the device.
818 */
819 ControllerActivityCounterImpl mModemActivity;
820
821 /**
822 * Whether the device supports WiFi controller energy reporting. This is set to true on
823 * the first WiFi energy report. See {@link #mWifiActivity}.
824 */
825 boolean mHasWifiReporting = false;
826
827 /**
828 * Whether the device supports Bluetooth controller energy reporting. This is set to true on
829 * the first Bluetooth energy report. See {@link #mBluetoothActivity}.
830 */
831 boolean mHasBluetoothReporting = false;
832
833 /**
834 * Whether the device supports Modem controller energy reporting. This is set to true on
835 * the first Modem energy report. See {@link #mModemActivity}.
836 */
837 boolean mHasModemReporting = false;
Adam Lesinski33dac552015-03-09 15:24:48 -0700838
The Android Open Source Project10592532009-03-18 17:39:46 -0700839 boolean mWifiOn;
Evan Millarc64edde2009-04-18 12:26:32 -0700840 StopwatchTimer mWifiOnTimer;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -0700841
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700842 boolean mGlobalWifiRunning;
843 StopwatchTimer mGlobalWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700844
Dianne Hackbornca1bf212014-02-14 14:18:36 -0800845 int mWifiState = -1;
846 final StopwatchTimer[] mWifiStateTimer = new StopwatchTimer[NUM_WIFI_STATES];
847
Dianne Hackborn3251b902014-06-20 14:40:53 -0700848 int mWifiSupplState = -1;
849 final StopwatchTimer[] mWifiSupplStateTimer = new StopwatchTimer[NUM_WIFI_SUPPL_STATES];
850
851 int mWifiSignalStrengthBin = -1;
852 final StopwatchTimer[] mWifiSignalStrengthsTimer =
853 new StopwatchTimer[NUM_WIFI_SIGNAL_STRENGTH_BINS];
854
Siddharth Rayb50a6842017-12-14 15:15:28 -0800855 StopwatchTimer mWifiActiveTimer;
856
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800857 int mBluetoothScanNesting;
Bookatz867c0d72017-03-07 18:23:42 -0800858 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
859 protected StopwatchTimer mBluetoothScanTimer;
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800860
Siddharth Rayf5e796a2018-01-22 18:18:17 -0800861 boolean mIsCellularTxPowerHigh = false;
862
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700863 int mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackbornf7097a52014-05-13 09:56:14 -0700864 long mMobileRadioActiveStartTime;
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800865 StopwatchTimer mMobileRadioActiveTimer;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800866 StopwatchTimer mMobileRadioActivePerAppTimer;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700867 LongSamplingCounter mMobileRadioActiveAdjustedTime;
Dianne Hackbornd45665b2014-02-26 12:35:32 -0800868 LongSamplingCounter mMobileRadioActiveUnknownTime;
869 LongSamplingCounter mMobileRadioActiveUnknownCount;
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800870
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700871 int mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
872
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 /**
874 * These provide time bases that discount the time the device is plugged
875 * in to power.
876 */
877 boolean mOnBattery;
Sudheer Shanka38383232017-07-25 09:55:03 -0700878 @VisibleForTesting
879 protected boolean mOnBatteryInternal;
Amith Yamasani3718aaa2009-06-09 06:32:35 -0700880
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700881 /**
882 * External reporting of whether the device is actually charging.
883 */
884 boolean mCharging = true;
885 int mLastChargingStateLevel;
886
The Android Open Source Project10592532009-03-18 17:39:46 -0700887 /*
888 * These keep track of battery levels (1-100) at the last plug event and the last unplug event.
889 */
Evan Millar633a1742009-04-02 16:36:33 -0700890 int mDischargeStartLevel;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700891 int mDischargeUnplugLevel;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700892 int mDischargePlugLevel;
Evan Millar633a1742009-04-02 16:36:33 -0700893 int mDischargeCurrentLevel;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700894 int mCurrentBatteryLevel;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -0700895 int mLowDischargeAmountSinceCharge;
896 int mHighDischargeAmountSinceCharge;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -0800897 int mDischargeScreenOnUnplugLevel;
898 int mDischargeScreenOffUnplugLevel;
Mike Mac2f518a2017-09-19 16:06:03 -0700899 int mDischargeScreenDozeUnplugLevel;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -0800900 int mDischargeAmountScreenOn;
901 int mDischargeAmountScreenOnSinceCharge;
902 int mDischargeAmountScreenOff;
903 int mDischargeAmountScreenOffSinceCharge;
Mike Mac2f518a2017-09-19 16:06:03 -0700904 int mDischargeAmountScreenDoze;
905 int mDischargeAmountScreenDozeSinceCharge;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700906
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700907 private LongSamplingCounter mDischargeScreenOffCounter;
Mike Mac2f518a2017-09-19 16:06:03 -0700908 private LongSamplingCounter mDischargeScreenDozeCounter;
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700909 private LongSamplingCounter mDischargeCounter;
Mike Ma15313c92017-11-15 17:58:21 -0800910 private LongSamplingCounter mDischargeLightDozeCounter;
911 private LongSamplingCounter mDischargeDeepDozeCounter;
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700912
Dianne Hackborncd0e3352014-08-07 17:08:09 -0700913 static final int MAX_LEVEL_STEPS = 200;
Dianne Hackborn260c5022014-04-29 11:23:16 -0700914
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700915 int mInitStepMode = 0;
916 int mCurStepMode = 0;
917 int mModStepMode = 0;
918
Dianne Hackborn260c5022014-04-29 11:23:16 -0700919 int mLastDischargeStepLevel;
Dianne Hackborn29325132014-05-21 15:01:03 -0700920 int mMinDischargeStepLevel;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800921 final LevelStepTracker mDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS);
922 final LevelStepTracker mDailyDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700923 ArrayList<PackageChange> mDailyPackageChanges;
Dianne Hackborn260c5022014-04-29 11:23:16 -0700924
925 int mLastChargeStepLevel;
Dianne Hackborn29325132014-05-21 15:01:03 -0700926 int mMaxChargeStepLevel;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800927 final LevelStepTracker mChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS);
928 final LevelStepTracker mDailyChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2);
929
930 static final int MAX_DAILY_ITEMS = 10;
931
932 long mDailyStartTime = 0;
933 long mNextMinDailyDeadline = 0;
934 long mNextMaxDailyDeadline = 0;
935
936 final ArrayList<DailyItem> mDailyItems = new ArrayList<>();
Dianne Hackborn260c5022014-04-29 11:23:16 -0700937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800938 long mLastWriteTime = 0; // Milliseconds
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700939
Amith Yamasanif37447b2009-10-08 18:28:01 -0700940 private int mPhoneServiceState = -1;
Dianne Hackborne4a59512010-12-07 11:08:07 -0800941 private int mPhoneServiceStateRaw = -1;
942 private int mPhoneSimStateRaw = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -0700943
Dianne Hackborn1e01d162014-12-04 17:46:42 -0800944 private int mNumConnectivityChange;
945 private int mLoadedNumConnectivityChange;
946 private int mUnpluggedNumConnectivityChange;
947
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700948 private int mEstimatedBatteryCapacity = -1;
949
Jocelyn Dangc627d102017-04-14 13:15:14 -0700950 private int mMinLearnedBatteryCapacity = -1;
951 private int mMaxLearnedBatteryCapacity = -1;
Adam Lesinski041d9172016-12-12 12:03:56 -0800952
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700953 private long[] mCpuFreqs;
954
Sudheer Shanka38383232017-07-25 09:55:03 -0700955 @VisibleForTesting
956 protected PowerProfile mPowerProfile;
Adam Lesinskie08af192015-03-25 16:42:59 -0700957
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800958 @GuardedBy("this")
959 private final Constants mConstants;
960
Evan Millarc64edde2009-04-18 12:26:32 -0700961 /*
Bookatz50df7112017-08-04 14:53:26 -0700962 * Holds a SamplingTimer associated with each Resource Power Manager state and voter,
963 * recording their times when on-battery (regardless of screen state).
964 */
965 private final HashMap<String, SamplingTimer> mRpmStats = new HashMap<>();
966 /** Times for each Resource Power Manager state and voter when screen-off and on-battery. */
967 private final HashMap<String, SamplingTimer> mScreenOffRpmStats = new HashMap<>();
968
969 @Override
970 public Map<String, ? extends Timer> getRpmStats() {
971 return mRpmStats;
972 }
973
Bookatz82b341172017-09-07 19:06:08 -0700974 // TODO: Note: screenOffRpmStats has been disabled via SCREEN_OFF_RPM_STATS_ENABLED.
Bookatz50df7112017-08-04 14:53:26 -0700975 @Override
976 public Map<String, ? extends Timer> getScreenOffRpmStats() {
977 return mScreenOffRpmStats;
978 }
979
980 /*
Evan Millarc64edde2009-04-18 12:26:32 -0700981 * Holds a SamplingTimer associated with each kernel wakelock name being tracked.
982 */
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700983 private final HashMap<String, SamplingTimer> mKernelWakelockStats = new HashMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700984
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700985 public Map<String, ? extends Timer> getKernelWakelockStats() {
Evan Millarc64edde2009-04-18 12:26:32 -0700986 return mKernelWakelockStats;
987 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700988
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700989 String mLastWakeupReason = null;
990 long mLastWakeupUptimeMs = 0;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -0700991 private final HashMap<String, SamplingTimer> mWakeupReasonStats = new HashMap<>();
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700992
Dianne Hackbornc3940bc2014-09-05 15:50:25 -0700993 public Map<String, ? extends Timer> getWakeupReasonStats() {
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700994 return mWakeupReasonStats;
995 }
996
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700997 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -0700998 public long getUahDischarge(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -0700999 return mDischargeCounter.getCountLocked(which);
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001000 }
1001
1002 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -07001003 public long getUahDischargeScreenOff(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -07001004 return mDischargeScreenOffCounter.getCountLocked(which);
1005 }
1006
1007 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -07001008 public long getUahDischargeScreenDoze(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -07001009 return mDischargeScreenDozeCounter.getCountLocked(which);
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001010 }
1011
Adam Lesinskif9b20a92016-06-17 17:30:01 -07001012 @Override
Mike Ma15313c92017-11-15 17:58:21 -08001013 public long getUahDischargeLightDoze(int which) {
1014 return mDischargeLightDozeCounter.getCountLocked(which);
1015 }
1016
1017 @Override
1018 public long getUahDischargeDeepDoze(int which) {
1019 return mDischargeDeepDozeCounter.getCountLocked(which);
1020 }
1021
1022 @Override
Adam Lesinskif9b20a92016-06-17 17:30:01 -07001023 public int getEstimatedBatteryCapacity() {
1024 return mEstimatedBatteryCapacity;
1025 }
1026
Jocelyn Dangc627d102017-04-14 13:15:14 -07001027 @Override
1028 public int getMinLearnedBatteryCapacity() {
1029 return mMinLearnedBatteryCapacity;
1030 }
1031
1032 @Override
1033 public int getMaxLearnedBatteryCapacity() {
1034 return mMaxLearnedBatteryCapacity;
1035 }
1036
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 public BatteryStatsImpl() {
Joe Onoratoabded112016-02-08 16:49:39 -08001038 this(new SystemClocks());
1039 }
1040
1041 public BatteryStatsImpl(Clocks clocks) {
1042 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07001043 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07001044 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08001045 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001046 mHandler = null;
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07001047 mPlatformIdleStateCallback = null;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -07001048 mUserInfoProvider = null;
Sudheer Shanka5c19b892018-01-05 17:25:46 -08001049 mConstants = new Constants(mHandler);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07001050 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 }
1052
Joe Onoratoabded112016-02-08 16:49:39 -08001053 private void init(Clocks clocks) {
1054 mClocks = clocks;
Joe Onoratoabded112016-02-08 16:49:39 -08001055 }
1056
Adam Lesinski14ae39a2017-05-26 11:50:40 -07001057 public interface TimeBaseObs {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001058 void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime);
1059 void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime);
1060 }
1061
Joe Onoratoabded112016-02-08 16:49:39 -08001062 // methods are protected not private to be VisibleForTesting
1063 public static class TimeBase {
1064 protected final ArrayList<TimeBaseObs> mObservers = new ArrayList<>();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001065
Joe Onoratoabded112016-02-08 16:49:39 -08001066 protected long mUptime;
1067 protected long mRealtime;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001068
Joe Onoratoabded112016-02-08 16:49:39 -08001069 protected boolean mRunning;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001070
Joe Onoratoabded112016-02-08 16:49:39 -08001071 protected long mPastUptime;
1072 protected long mUptimeStart;
1073 protected long mPastRealtime;
1074 protected long mRealtimeStart;
1075 protected long mUnpluggedUptime;
1076 protected long mUnpluggedRealtime;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001077
1078 public void dump(PrintWriter pw, String prefix) {
1079 StringBuilder sb = new StringBuilder(128);
1080 pw.print(prefix); pw.print("mRunning="); pw.println(mRunning);
1081 sb.setLength(0);
1082 sb.append(prefix);
1083 sb.append("mUptime=");
Dianne Hackborn4590e522014-03-24 13:36:46 -07001084 formatTimeMs(sb, mUptime / 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001085 pw.println(sb.toString());
1086 sb.setLength(0);
1087 sb.append(prefix);
1088 sb.append("mRealtime=");
Dianne Hackborn4590e522014-03-24 13:36:46 -07001089 formatTimeMs(sb, mRealtime / 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001090 pw.println(sb.toString());
1091 sb.setLength(0);
1092 sb.append(prefix);
1093 sb.append("mPastUptime=");
1094 formatTimeMs(sb, mPastUptime / 1000); sb.append("mUptimeStart=");
1095 formatTimeMs(sb, mUptimeStart / 1000);
1096 sb.append("mUnpluggedUptime="); formatTimeMs(sb, mUnpluggedUptime / 1000);
1097 pw.println(sb.toString());
1098 sb.setLength(0);
1099 sb.append(prefix);
1100 sb.append("mPastRealtime=");
1101 formatTimeMs(sb, mPastRealtime / 1000); sb.append("mRealtimeStart=");
1102 formatTimeMs(sb, mRealtimeStart / 1000);
1103 sb.append("mUnpluggedRealtime="); formatTimeMs(sb, mUnpluggedRealtime / 1000);
1104 pw.println(sb.toString());
1105 }
1106
1107 public void add(TimeBaseObs observer) {
1108 mObservers.add(observer);
1109 }
1110
1111 public void remove(TimeBaseObs observer) {
1112 if (!mObservers.remove(observer)) {
1113 Slog.wtf(TAG, "Removed unknown observer: " + observer);
1114 }
1115 }
1116
Joe Onoratoabded112016-02-08 16:49:39 -08001117 public boolean hasObserver(TimeBaseObs observer) {
1118 return mObservers.contains(observer);
1119 }
1120
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001121 public void init(long uptime, long realtime) {
1122 mRealtime = 0;
1123 mUptime = 0;
1124 mPastUptime = 0;
1125 mPastRealtime = 0;
1126 mUptimeStart = uptime;
1127 mRealtimeStart = realtime;
1128 mUnpluggedUptime = getUptime(mUptimeStart);
1129 mUnpluggedRealtime = getRealtime(mRealtimeStart);
1130 }
1131
1132 public void reset(long uptime, long realtime) {
1133 if (!mRunning) {
1134 mPastUptime = 0;
1135 mPastRealtime = 0;
1136 } else {
1137 mUptimeStart = uptime;
1138 mRealtimeStart = realtime;
Joe Onoratoabded112016-02-08 16:49:39 -08001139 // TODO: Since mUptimeStart was just reset and we are running, getUptime will
1140 // just return mPastUptime. Also, are we sure we don't want to reset that?
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001141 mUnpluggedUptime = getUptime(uptime);
Joe Onoratoabded112016-02-08 16:49:39 -08001142 // TODO: likewise.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001143 mUnpluggedRealtime = getRealtime(realtime);
1144 }
1145 }
1146
1147 public long computeUptime(long curTime, int which) {
1148 switch (which) {
1149 case STATS_SINCE_CHARGED:
1150 return mUptime + getUptime(curTime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001151 case STATS_CURRENT:
1152 return getUptime(curTime);
1153 case STATS_SINCE_UNPLUGGED:
1154 return getUptime(curTime) - mUnpluggedUptime;
1155 }
1156 return 0;
1157 }
1158
1159 public long computeRealtime(long curTime, int which) {
1160 switch (which) {
1161 case STATS_SINCE_CHARGED:
1162 return mRealtime + getRealtime(curTime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001163 case STATS_CURRENT:
1164 return getRealtime(curTime);
1165 case STATS_SINCE_UNPLUGGED:
1166 return getRealtime(curTime) - mUnpluggedRealtime;
1167 }
1168 return 0;
1169 }
1170
1171 public long getUptime(long curTime) {
1172 long time = mPastUptime;
1173 if (mRunning) {
1174 time += curTime - mUptimeStart;
1175 }
1176 return time;
1177 }
1178
1179 public long getRealtime(long curTime) {
1180 long time = mPastRealtime;
1181 if (mRunning) {
1182 time += curTime - mRealtimeStart;
1183 }
1184 return time;
1185 }
1186
1187 public long getUptimeStart() {
1188 return mUptimeStart;
1189 }
1190
1191 public long getRealtimeStart() {
1192 return mRealtimeStart;
1193 }
1194
1195 public boolean isRunning() {
1196 return mRunning;
1197 }
1198
1199 public boolean setRunning(boolean running, long uptime, long realtime) {
1200 if (mRunning != running) {
1201 mRunning = running;
1202 if (running) {
1203 mUptimeStart = uptime;
1204 mRealtimeStart = realtime;
1205 long batteryUptime = mUnpluggedUptime = getUptime(uptime);
1206 long batteryRealtime = mUnpluggedRealtime = getRealtime(realtime);
1207
1208 for (int i = mObservers.size() - 1; i >= 0; i--) {
1209 mObservers.get(i).onTimeStarted(realtime, batteryUptime, batteryRealtime);
1210 }
1211 } else {
1212 mPastUptime += uptime - mUptimeStart;
1213 mPastRealtime += realtime - mRealtimeStart;
1214
1215 long batteryUptime = getUptime(uptime);
1216 long batteryRealtime = getRealtime(realtime);
1217
1218 for (int i = mObservers.size() - 1; i >= 0; i--) {
1219 mObservers.get(i).onTimeStopped(realtime, batteryUptime, batteryRealtime);
1220 }
1221 }
1222 return true;
1223 }
1224 return false;
1225 }
1226
1227 public void readSummaryFromParcel(Parcel in) {
1228 mUptime = in.readLong();
1229 mRealtime = in.readLong();
1230 }
1231
1232 public void writeSummaryToParcel(Parcel out, long uptime, long realtime) {
1233 out.writeLong(computeUptime(uptime, STATS_SINCE_CHARGED));
1234 out.writeLong(computeRealtime(realtime, STATS_SINCE_CHARGED));
1235 }
1236
1237 public void readFromParcel(Parcel in) {
1238 mRunning = false;
1239 mUptime = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001240 mPastUptime = in.readLong();
1241 mUptimeStart = in.readLong();
Dianne Hackbornef640cd2014-03-25 14:41:05 -07001242 mRealtime = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001243 mPastRealtime = in.readLong();
1244 mRealtimeStart = in.readLong();
1245 mUnpluggedUptime = in.readLong();
1246 mUnpluggedRealtime = in.readLong();
1247 }
1248
1249 public void writeToParcel(Parcel out, long uptime, long realtime) {
1250 final long runningUptime = getUptime(uptime);
1251 final long runningRealtime = getRealtime(realtime);
1252 out.writeLong(mUptime);
1253 out.writeLong(runningUptime);
1254 out.writeLong(mUptimeStart);
Dianne Hackbornef640cd2014-03-25 14:41:05 -07001255 out.writeLong(mRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001256 out.writeLong(runningRealtime);
1257 out.writeLong(mRealtimeStart);
1258 out.writeLong(mUnpluggedUptime);
1259 out.writeLong(mUnpluggedRealtime);
1260 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001263 /**
Dianne Hackborn617f8772009-03-31 15:04:46 -07001264 * State for keeping track of counting information.
1265 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001266 public static class Counter extends BatteryStats.Counter implements TimeBaseObs {
Christopher Tate4cee7252010-03-19 14:50:40 -07001267 final AtomicInteger mCount = new AtomicInteger();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001268 final TimeBase mTimeBase;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001269 int mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001270 int mUnpluggedCount;
1271 int mPluggedCount;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001272
Bookatz8c6f3c52017-05-24 12:00:17 -07001273 public Counter(TimeBase timeBase, Parcel in) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001274 mTimeBase = timeBase;
Christopher Tate4cee7252010-03-19 14:50:40 -07001275 mPluggedCount = in.readInt();
1276 mCount.set(mPluggedCount);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001277 mLoadedCount = in.readInt();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001278 mUnpluggedCount = in.readInt();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001279 timeBase.add(this);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001280 }
1281
Bookatz8c6f3c52017-05-24 12:00:17 -07001282 public Counter(TimeBase timeBase) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001283 mTimeBase = timeBase;
1284 timeBase.add(this);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001285 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001286
Dianne Hackborn617f8772009-03-31 15:04:46 -07001287 public void writeToParcel(Parcel out) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001288 out.writeInt(mCount.get());
Dianne Hackborn617f8772009-03-31 15:04:46 -07001289 out.writeInt(mLoadedCount);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001290 out.writeInt(mUnpluggedCount);
1291 }
1292
Bookatz8c6f3c52017-05-24 12:00:17 -07001293 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001294 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001295 mUnpluggedCount = mPluggedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001296 }
1297
Bookatz8c6f3c52017-05-24 12:00:17 -07001298 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001299 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001300 mPluggedCount = mCount.get();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001301 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001302
Dianne Hackborn617f8772009-03-31 15:04:46 -07001303 /**
1304 * Writes a possibly null Counter to a Parcel.
1305 *
1306 * @param out the Parcel to be written to.
1307 * @param counter a Counter, or null.
1308 */
Amith Yamasani977e11f2018-02-16 11:29:54 -08001309 public static void writeCounterToParcel(Parcel out, @Nullable Counter counter) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07001310 if (counter == null) {
1311 out.writeInt(0); // indicates null
1312 return;
1313 }
1314 out.writeInt(1); // indicates non-null
1315
1316 counter.writeToParcel(out);
1317 }
1318
Amith Yamasani977e11f2018-02-16 11:29:54 -08001319 /**
1320 * Reads a Counter that was written using {@link #writeCounterToParcel(Parcel, Counter)}.
1321 * @param timeBase the timebase to assign to the Counter
1322 * @param in the parcel to read from
1323 * @return the Counter or null.
1324 */
1325 public static @Nullable Counter readCounterFromParcel(TimeBase timeBase, Parcel in) {
1326 if (in.readInt() == 0) {
1327 return null;
1328 }
1329 return new Counter(timeBase, in);
1330 }
1331
Dianne Hackborn617f8772009-03-31 15:04:46 -07001332 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001333 public int getCountLocked(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001334 int val = mCount.get();
1335 if (which == STATS_SINCE_UNPLUGGED) {
1336 val -= mUnpluggedCount;
1337 } else if (which != STATS_SINCE_CHARGED) {
1338 val -= mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001339 }
1340
1341 return val;
1342 }
1343
1344 public void logState(Printer pw, String prefix) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001345 pw.println(prefix + "mCount=" + mCount.get()
Bookatz8c6f3c52017-05-24 12:00:17 -07001346 + " mLoadedCount=" + mLoadedCount
Dianne Hackborn617f8772009-03-31 15:04:46 -07001347 + " mUnpluggedCount=" + mUnpluggedCount
1348 + " mPluggedCount=" + mPluggedCount);
1349 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001350
Bookatz8c6f3c52017-05-24 12:00:17 -07001351 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1352 public void stepAtomic() {
1353 if (mTimeBase.isRunning()) {
1354 mCount.incrementAndGet();
1355 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001356 }
1357
Bookatz4ebc0642017-05-11 12:21:19 -07001358 void addAtomic(int delta) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001359 if (mTimeBase.isRunning()) {
1360 mCount.addAndGet(delta);
1361 }
Bookatz4ebc0642017-05-11 12:21:19 -07001362 }
1363
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001364 /**
1365 * Clear state of this counter.
1366 */
1367 void reset(boolean detachIfReset) {
1368 mCount.set(0);
Bookatz8c6f3c52017-05-24 12:00:17 -07001369 mLoadedCount = mPluggedCount = mUnpluggedCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001370 if (detachIfReset) {
1371 detach();
1372 }
1373 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001374
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001375 void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001376 mTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001377 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001378
Bookatz8c6f3c52017-05-24 12:00:17 -07001379 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1380 public void writeSummaryFromParcelLocked(Parcel out) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001381 int count = mCount.get();
1382 out.writeInt(count);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001383 }
1384
Bookatz8c6f3c52017-05-24 12:00:17 -07001385 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1386 public void readSummaryFromParcelLocked(Parcel in) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001387 mLoadedCount = in.readInt();
1388 mCount.set(mLoadedCount);
Christopher Tate4cee7252010-03-19 14:50:40 -07001389 mUnpluggedCount = mPluggedCount = mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001390 }
1391 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07001392
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001393 @VisibleForTesting
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001394 public static class LongSamplingCounterArray extends LongCounterArray implements TimeBaseObs {
1395 final TimeBase mTimeBase;
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001396 public long[] mCounts;
1397 public long[] mLoadedCounts;
1398 public long[] mUnpluggedCounts;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001399
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001400 private LongSamplingCounterArray(TimeBase timeBase, Parcel in) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001401 mTimeBase = timeBase;
Sudheer Shankae544d162017-12-28 17:06:20 -08001402 mCounts = in.createLongArray();
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001403 mLoadedCounts = in.createLongArray();
1404 mUnpluggedCounts = in.createLongArray();
1405 timeBase.add(this);
1406 }
1407
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001408 public LongSamplingCounterArray(TimeBase timeBase) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001409 mTimeBase = timeBase;
1410 timeBase.add(this);
1411 }
1412
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001413 private void writeToParcel(Parcel out) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001414 out.writeLongArray(mCounts);
1415 out.writeLongArray(mLoadedCounts);
1416 out.writeLongArray(mUnpluggedCounts);
1417 }
1418
1419 @Override
1420 public void onTimeStarted(long elapsedRealTime, long baseUptime, long baseRealtime) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001421 mUnpluggedCounts = copyArray(mCounts, mUnpluggedCounts);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001422 }
1423
1424 @Override
1425 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001426 }
1427
1428 @Override
1429 public long[] getCountsLocked(int which) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001430 long[] val = copyArray(mCounts, null);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001431 if (which == STATS_SINCE_UNPLUGGED) {
1432 subtract(val, mUnpluggedCounts);
1433 } else if (which != STATS_SINCE_CHARGED) {
1434 subtract(val, mLoadedCounts);
1435 }
1436 return val;
1437 }
1438
1439 @Override
1440 public void logState(Printer pw, String prefix) {
1441 pw.println(prefix + "mCounts=" + Arrays.toString(mCounts)
1442 + " mLoadedCounts=" + Arrays.toString(mLoadedCounts)
Sudheer Shankae544d162017-12-28 17:06:20 -08001443 + " mUnpluggedCounts=" + Arrays.toString(mUnpluggedCounts));
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001444 }
1445
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001446 public void addCountLocked(long[] counts) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001447 addCountLocked(counts, mTimeBase.isRunning());
1448 }
1449
1450 public void addCountLocked(long[] counts, boolean isRunning) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001451 if (counts == null) {
1452 return;
1453 }
Sudheer Shankae544d162017-12-28 17:06:20 -08001454 if (isRunning) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001455 if (mCounts == null) {
1456 mCounts = new long[counts.length];
1457 }
1458 for (int i = 0; i < counts.length; ++i) {
1459 mCounts[i] += counts[i];
1460 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001461 }
1462 }
1463
Sudheer Shankab8ad5942017-08-08 12:16:09 -07001464 public int getSize() {
1465 return mCounts == null ? 0 : mCounts.length;
1466 }
1467
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001468 /**
1469 * Clear state of this counter.
1470 */
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001471 public void reset(boolean detachIfReset) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001472 fillArray(mCounts, 0);
1473 fillArray(mLoadedCounts, 0);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001474 fillArray(mUnpluggedCounts, 0);
1475 if (detachIfReset) {
1476 detach();
1477 }
1478 }
1479
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001480 public void detach() {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001481 mTimeBase.remove(this);
1482 }
1483
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001484 private void writeSummaryToParcelLocked(Parcel out) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001485 out.writeLongArray(mCounts);
1486 }
1487
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001488 private void readSummaryFromParcelLocked(Parcel in) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001489 mCounts = in.createLongArray();
1490 mLoadedCounts = copyArray(mCounts, mLoadedCounts);
1491 mUnpluggedCounts = copyArray(mCounts, mUnpluggedCounts);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001492 }
1493
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001494 public static void writeToParcel(Parcel out, LongSamplingCounterArray counterArray) {
1495 if (counterArray != null) {
1496 out.writeInt(1);
1497 counterArray.writeToParcel(out);
1498 } else {
1499 out.writeInt(0);
1500 }
1501 }
1502
1503 public static LongSamplingCounterArray readFromParcel(Parcel in, TimeBase timeBase) {
1504 if (in.readInt() != 0) {
1505 return new LongSamplingCounterArray(timeBase, in);
1506 } else {
1507 return null;
1508 }
1509 }
1510
1511 public static void writeSummaryToParcelLocked(Parcel out,
1512 LongSamplingCounterArray counterArray) {
1513 if (counterArray != null) {
1514 out.writeInt(1);
1515 counterArray.writeSummaryToParcelLocked(out);
1516 } else {
1517 out.writeInt(0);
1518 }
1519 }
1520
1521 public static LongSamplingCounterArray readSummaryFromParcelLocked(Parcel in,
1522 TimeBase timeBase) {
1523 if (in.readInt() != 0) {
1524 final LongSamplingCounterArray counterArray
1525 = new LongSamplingCounterArray(timeBase);
1526 counterArray.readSummaryFromParcelLocked(in);
1527 return counterArray;
1528 } else {
1529 return null;
1530 }
1531 }
1532
Bookatz8c6f3c52017-05-24 12:00:17 -07001533 private static void fillArray(long[] a, long val) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001534 if (a != null) {
1535 Arrays.fill(a, val);
1536 }
1537 }
1538
Bookatz8c6f3c52017-05-24 12:00:17 -07001539 private static void subtract(@NonNull long[] val, long[] toSubtract) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001540 if (toSubtract == null) {
1541 return;
1542 }
1543 for (int i = 0; i < val.length; i++) {
1544 val[i] -= toSubtract[i];
1545 }
1546 }
1547
Bookatz8c6f3c52017-05-24 12:00:17 -07001548 private static long[] copyArray(long[] src, long[] dest) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001549 if (src == null) {
1550 return null;
1551 } else {
1552 if (dest == null) {
1553 dest = new long[src.length];
1554 }
1555 System.arraycopy(src, 0, dest, 0, src.length);
1556 return dest;
1557 }
1558 }
1559 }
1560
Mike Ma561a8d92018-03-20 18:24:05 -07001561 @VisibleForTesting
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001562 public static class LongSamplingCounter extends LongCounter implements TimeBaseObs {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001563 final TimeBase mTimeBase;
Mike Ma561a8d92018-03-20 18:24:05 -07001564 public long mCount;
1565 public long mCurrentCount;
1566 public long mLoadedCount;
1567 public long mUnpluggedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001568
Mike Ma561a8d92018-03-20 18:24:05 -07001569 public LongSamplingCounter(TimeBase timeBase, Parcel in) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001570 mTimeBase = timeBase;
Sudheer Shankac57729a2018-02-09 15:44:42 -08001571 mCount = in.readLong();
Mike Ma561a8d92018-03-20 18:24:05 -07001572 mCurrentCount = in.readLong();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001573 mLoadedCount = in.readLong();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001574 mUnpluggedCount = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001575 timeBase.add(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001576 }
1577
Mike Ma561a8d92018-03-20 18:24:05 -07001578 public LongSamplingCounter(TimeBase timeBase) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001579 mTimeBase = timeBase;
1580 timeBase.add(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001581 }
1582
1583 public void writeToParcel(Parcel out) {
1584 out.writeLong(mCount);
Mike Ma561a8d92018-03-20 18:24:05 -07001585 out.writeLong(mCurrentCount);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001586 out.writeLong(mLoadedCount);
1587 out.writeLong(mUnpluggedCount);
1588 }
1589
1590 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001591 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Sudheer Shankac57729a2018-02-09 15:44:42 -08001592 mUnpluggedCount = mCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001593 }
1594
1595 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001596 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001597 }
1598
1599 public long getCountLocked(int which) {
Sudheer Shankac57729a2018-02-09 15:44:42 -08001600 long val = mCount;
Dianne Hackborn4590e522014-03-24 13:36:46 -07001601 if (which == STATS_SINCE_UNPLUGGED) {
1602 val -= mUnpluggedCount;
1603 } else if (which != STATS_SINCE_CHARGED) {
1604 val -= mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001605 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001606 return val;
1607 }
1608
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001609 @Override
1610 public void logState(Printer pw, String prefix) {
1611 pw.println(prefix + "mCount=" + mCount
Mike Ma561a8d92018-03-20 18:24:05 -07001612 + " mCurrentCount=" + mCurrentCount
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001613 + " mLoadedCount=" + mLoadedCount
Sudheer Shankac57729a2018-02-09 15:44:42 -08001614 + " mUnpluggedCount=" + mUnpluggedCount);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001615 }
1616
Mike Ma561a8d92018-03-20 18:24:05 -07001617 public void addCountLocked(long count) {
1618 update(mCurrentCount + count, mTimeBase.isRunning());
Sudheer Shankac57729a2018-02-09 15:44:42 -08001619 }
1620
Mike Ma561a8d92018-03-20 18:24:05 -07001621 public void addCountLocked(long count, boolean isRunning) {
1622 update(mCurrentCount + count, isRunning);
1623 }
1624
1625 public void update(long count) {
1626 update(count, mTimeBase.isRunning());
1627 }
1628
1629 public void update(long count, boolean isRunning) {
1630 if (count < mCurrentCount) {
1631 mCurrentCount = 0;
Bookatz8c6f3c52017-05-24 12:00:17 -07001632 }
Mike Ma561a8d92018-03-20 18:24:05 -07001633 if (isRunning) {
1634 mCount += count - mCurrentCount;
1635 }
1636 mCurrentCount = count;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001637 }
1638
1639 /**
1640 * Clear state of this counter.
1641 */
Mike Ma561a8d92018-03-20 18:24:05 -07001642 public void reset(boolean detachIfReset) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001643 mCount = 0;
Sudheer Shankac57729a2018-02-09 15:44:42 -08001644 mLoadedCount = mUnpluggedCount = 0;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001645 if (detachIfReset) {
1646 detach();
1647 }
1648 }
1649
Mike Ma561a8d92018-03-20 18:24:05 -07001650 public void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001651 mTimeBase.remove(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001652 }
1653
Mike Ma561a8d92018-03-20 18:24:05 -07001654 public void writeSummaryFromParcelLocked(Parcel out) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001655 out.writeLong(mCount);
1656 }
1657
Mike Ma561a8d92018-03-20 18:24:05 -07001658 public void readSummaryFromParcelLocked(Parcel in) {
1659 mCount = mUnpluggedCount= mLoadedCount = in.readLong();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001660 }
1661 }
1662
Dianne Hackborn617f8772009-03-31 15:04:46 -07001663 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 * State for keeping track of timing information.
1665 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001666 public static abstract class Timer extends BatteryStats.Timer implements TimeBaseObs {
Joe Onoratoabded112016-02-08 16:49:39 -08001667 protected final Clocks mClocks;
1668 protected final int mType;
1669 protected final TimeBase mTimeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001670
Joe Onoratoabded112016-02-08 16:49:39 -08001671 protected int mCount;
1672 protected int mLoadedCount;
1673 protected int mLastCount;
1674 protected int mUnpluggedCount;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 // Times are in microseconds for better accuracy when dividing by the
1677 // lock count, and are in "battery realtime" units.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001678
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 /**
1680 * The total time we have accumulated since the start of the original
1681 * boot, to the last time something interesting happened in the
1682 * current run.
1683 */
Joe Onoratoabded112016-02-08 16:49:39 -08001684 protected long mTotalTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 /**
1687 * The total time we loaded for the previous runs. Subtract this from
1688 * mTotalTime to find the time for the current run of the system.
1689 */
Joe Onoratoabded112016-02-08 16:49:39 -08001690 protected long mLoadedTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 /**
1693 * The run time of the last run of the system, as loaded from the
1694 * saved data.
1695 */
Joe Onoratoabded112016-02-08 16:49:39 -08001696 protected long mLastTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 /**
1699 * The value of mTotalTime when unplug() was last called. Subtract
1700 * this from mTotalTime to find the time since the last unplug from
1701 * power.
1702 */
Joe Onoratoabded112016-02-08 16:49:39 -08001703 protected long mUnpluggedTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001704
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001705 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07001706 * The total time this timer has been running until the latest mark has been set.
1707 * Subtract this from mTotalTime to get the time spent running since the mark was set.
1708 */
Joe Onoratoabded112016-02-08 16:49:39 -08001709 protected long mTimeBeforeMark;
Adam Lesinskie08af192015-03-25 16:42:59 -07001710
1711 /**
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001712 * Constructs from a parcel.
1713 * @param type
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001714 * @param timeBase
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001715 * @param in
1716 */
Joe Onoratoabded112016-02-08 16:49:39 -08001717 public Timer(Clocks clocks, int type, TimeBase timeBase, Parcel in) {
1718 mClocks = clocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001719 mType = type;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001720 mTimeBase = timeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722 mCount = in.readInt();
1723 mLoadedCount = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001724 mLastCount = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 mUnpluggedCount = in.readInt();
1726 mTotalTime = in.readLong();
1727 mLoadedTime = in.readLong();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001728 mLastTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001729 mUnpluggedTime = in.readLong();
Adam Lesinskie08af192015-03-25 16:42:59 -07001730 mTimeBeforeMark = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001731 timeBase.add(this);
Dianne Hackborn29325132014-05-21 15:01:03 -07001732 if (DEBUG) Log.i(TAG, "**** READ TIMER #" + mType + ": mTotalTime=" + mTotalTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001733 }
1734
Joe Onoratoabded112016-02-08 16:49:39 -08001735 public Timer(Clocks clocks, int type, TimeBase timeBase) {
1736 mClocks = clocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 mType = type;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001738 mTimeBase = timeBase;
1739 timeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 }
Evan Millarc64edde2009-04-18 12:26:32 -07001741
1742 protected abstract long computeRunTimeLocked(long curBatteryRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001743
Evan Millarc64edde2009-04-18 12:26:32 -07001744 protected abstract int computeCurrentCountLocked();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001745
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001746 /**
1747 * Clear state of this timer. Returns true if the timer is inactive
1748 * so can be completely dropped.
1749 */
Joe Onoratoabded112016-02-08 16:49:39 -08001750 public boolean reset(boolean detachIfReset) {
Adam Lesinskie08af192015-03-25 16:42:59 -07001751 mTotalTime = mLoadedTime = mLastTime = mTimeBeforeMark = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001752 mCount = mLoadedCount = mLastCount = 0;
1753 if (detachIfReset) {
1754 detach();
1755 }
1756 return true;
1757 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001758
Joe Onoratoabded112016-02-08 16:49:39 -08001759 public void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001760 mTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001761 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001762
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001763 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
Dianne Hackborn29325132014-05-21 15:01:03 -07001764 if (DEBUG) Log.i(TAG, "**** WRITING TIMER #" + mType + ": mTotalTime="
1765 + computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)));
Adam Lesinski98f0d462016-04-19 16:46:20 -07001766 out.writeInt(computeCurrentCountLocked());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001767 out.writeInt(mLoadedCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 out.writeInt(mUnpluggedCount);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001769 out.writeLong(computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001770 out.writeLong(mLoadedTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001771 out.writeLong(mUnpluggedTime);
Adam Lesinskie08af192015-03-25 16:42:59 -07001772 out.writeLong(mTimeBeforeMark);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001773 }
1774
Adam Lesinskie08af192015-03-25 16:42:59 -07001775 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001776 public void onTimeStarted(long elapsedRealtime, long timeBaseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 if (DEBUG && mType < 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001778 Log.v(TAG, "unplug #" + mType + ": realtime=" + baseRealtime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001779 + " old mUnpluggedTime=" + mUnpluggedTime
1780 + " old mUnpluggedCount=" + mUnpluggedCount);
1781 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001782 mUnpluggedTime = computeRunTimeLocked(baseRealtime);
Adam Lesinski98f0d462016-04-19 16:46:20 -07001783 mUnpluggedCount = computeCurrentCountLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001784 if (DEBUG && mType < 0) {
1785 Log.v(TAG, "unplug #" + mType
1786 + ": new mUnpluggedTime=" + mUnpluggedTime
1787 + " new mUnpluggedCount=" + mUnpluggedCount);
1788 }
1789 }
1790
Adam Lesinskie08af192015-03-25 16:42:59 -07001791 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001792 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Evan Millarc64edde2009-04-18 12:26:32 -07001793 if (DEBUG && mType < 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001794 Log.v(TAG, "plug #" + mType + ": realtime=" + baseRealtime
Evan Millarc64edde2009-04-18 12:26:32 -07001795 + " old mTotalTime=" + mTotalTime);
1796 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001797 mTotalTime = computeRunTimeLocked(baseRealtime);
Evan Millarc64edde2009-04-18 12:26:32 -07001798 mCount = computeCurrentCountLocked();
1799 if (DEBUG && mType < 0) {
1800 Log.v(TAG, "plug #" + mType
1801 + ": new mTotalTime=" + mTotalTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802 }
1803 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001805 /**
1806 * Writes a possibly null Timer to a Parcel.
1807 *
1808 * @param out the Parcel to be written to.
1809 * @param timer a Timer, or null.
1810 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001811 public static void writeTimerToParcel(Parcel out, Timer timer, long elapsedRealtimeUs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001812 if (timer == null) {
1813 out.writeInt(0); // indicates null
1814 return;
1815 }
1816 out.writeInt(1); // indicates non-null
1817
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001818 timer.writeToParcel(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 }
1820
1821 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001822 public long getTotalTimeLocked(long elapsedRealtimeUs, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001823 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1824 if (which == STATS_SINCE_UNPLUGGED) {
1825 val -= mUnpluggedTime;
1826 } else if (which != STATS_SINCE_CHARGED) {
1827 val -= mLoadedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 }
1829
1830 return val;
1831 }
1832
1833 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001834 public int getCountLocked(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001835 int val = computeCurrentCountLocked();
1836 if (which == STATS_SINCE_UNPLUGGED) {
1837 val -= mUnpluggedCount;
1838 } else if (which != STATS_SINCE_CHARGED) {
1839 val -= mLoadedCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 }
1841
1842 return val;
1843 }
1844
Adam Lesinskie08af192015-03-25 16:42:59 -07001845 @Override
1846 public long getTimeSinceMarkLocked(long elapsedRealtimeUs) {
1847 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1848 return val - mTimeBeforeMark;
1849 }
1850
1851 @Override
Dianne Hackborn627bba72009-03-24 22:32:56 -07001852 public void logState(Printer pw, String prefix) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07001853 pw.println(prefix + "mCount=" + mCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 + " mLoadedCount=" + mLoadedCount + " mLastCount=" + mLastCount
1855 + " mUnpluggedCount=" + mUnpluggedCount);
Dianne Hackborn627bba72009-03-24 22:32:56 -07001856 pw.println(prefix + "mTotalTime=" + mTotalTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001857 + " mLoadedTime=" + mLoadedTime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07001858 pw.println(prefix + "mLastTime=" + mLastTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001859 + " mUnpluggedTime=" + mUnpluggedTime);
Evan Millarc64edde2009-04-18 12:26:32 -07001860 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001861
1862
Joe Onoratoabded112016-02-08 16:49:39 -08001863 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001864 long runTime = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1865 out.writeLong(runTime);
Adam Lesinski98f0d462016-04-19 16:46:20 -07001866 out.writeInt(computeCurrentCountLocked());
Evan Millarc64edde2009-04-18 12:26:32 -07001867 }
1868
Joe Onoratoabded112016-02-08 16:49:39 -08001869 public void readSummaryFromParcelLocked(Parcel in) {
Evan Millarc64edde2009-04-18 12:26:32 -07001870 // Multiply by 1000 for backwards compatibility
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001871 mTotalTime = mLoadedTime = in.readLong();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001872 mLastTime = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001873 mUnpluggedTime = mTotalTime;
1874 mCount = mLoadedCount = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001875 mLastCount = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001876 mUnpluggedCount = mCount;
Adam Lesinskie08af192015-03-25 16:42:59 -07001877
1878 // When reading the summary, we set the mark to be the latest information.
1879 mTimeBeforeMark = mTotalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001880 }
1881 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001882
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001883 /**
1884 * A counter meant to accept monotonically increasing values to its {@link #update(long, int)}
1885 * method. The state of the timer according to its {@link TimeBase} will determine how much
1886 * of the value is recorded.
1887 *
1888 * If the value being recorded resets, {@link #endSample()} can be called in order to
1889 * account for the change. If the value passed in to {@link #update(long, int)} decreased
1890 * between calls, the {@link #endSample()} is automatically called and the new value is
1891 * expected to increase monotonically from that point on.
1892 */
Joe Onoratoabded112016-02-08 16:49:39 -08001893 public static class SamplingTimer extends Timer {
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001894
Evan Millarc64edde2009-04-18 12:26:32 -07001895 /**
1896 * The most recent reported count from /proc/wakelocks.
1897 */
1898 int mCurrentReportedCount;
1899
1900 /**
1901 * The reported count from /proc/wakelocks when unplug() was last
1902 * called.
1903 */
1904 int mUnpluggedReportedCount;
1905
1906 /**
1907 * The most recent reported total_time from /proc/wakelocks.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001908 */
Evan Millarc64edde2009-04-18 12:26:32 -07001909 long mCurrentReportedTotalTime;
1910
1911
1912 /**
1913 * The reported total_time from /proc/wakelocks when unplug() was last
1914 * called.
1915 */
1916 long mUnpluggedReportedTotalTime;
1917
1918 /**
1919 * Whether we are currently in a discharge cycle.
1920 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001921 boolean mTimeBaseRunning;
Evan Millarc64edde2009-04-18 12:26:32 -07001922
1923 /**
1924 * Whether we are currently recording reported values.
1925 */
1926 boolean mTrackingReportedValues;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001927
Evan Millarc64edde2009-04-18 12:26:32 -07001928 /*
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001929 * A sequence counter, incremented once for each update of the stats.
Evan Millarc64edde2009-04-18 12:26:32 -07001930 */
1931 int mUpdateVersion;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001932
Adam Lesinski98f0d462016-04-19 16:46:20 -07001933 @VisibleForTesting
1934 public SamplingTimer(Clocks clocks, TimeBase timeBase, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08001935 super(clocks, 0, timeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -07001936 mCurrentReportedCount = in.readInt();
1937 mUnpluggedReportedCount = in.readInt();
1938 mCurrentReportedTotalTime = in.readLong();
1939 mUnpluggedReportedTotalTime = in.readLong();
1940 mTrackingReportedValues = in.readInt() == 1;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001941 mTimeBaseRunning = timeBase.isRunning();
Evan Millarc64edde2009-04-18 12:26:32 -07001942 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001943
Adam Lesinski98f0d462016-04-19 16:46:20 -07001944 @VisibleForTesting
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001945 public SamplingTimer(Clocks clocks, TimeBase timeBase) {
Joe Onoratoabded112016-02-08 16:49:39 -08001946 super(clocks, 0, timeBase);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001947 mTrackingReportedValues = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001948 mTimeBaseRunning = timeBase.isRunning();
Evan Millarc64edde2009-04-18 12:26:32 -07001949 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001950
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001951 /**
1952 * Ends the current sample, allowing subsequent values to {@link #update(long, int)} to
1953 * be less than the values used for a previous invocation.
1954 */
1955 public void endSample() {
1956 mTotalTime = computeRunTimeLocked(0 /* unused by us */);
1957 mCount = computeCurrentCountLocked();
1958 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime = 0;
1959 mUnpluggedReportedCount = mCurrentReportedCount = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001960 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001961
Evan Millarc64edde2009-04-18 12:26:32 -07001962 public void setUpdateVersion(int version) {
1963 mUpdateVersion = version;
1964 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001965
Evan Millarc64edde2009-04-18 12:26:32 -07001966 public int getUpdateVersion() {
1967 return mUpdateVersion;
1968 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001969
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001970 /**
1971 * Updates the current recorded values. These are meant to be monotonically increasing
1972 * and cumulative. If you are dealing with deltas, use {@link #add(long, int)}.
1973 *
1974 * If the values being recorded have been reset, the monotonically increasing requirement
1975 * will be broken. In this case, {@link #endSample()} is automatically called and
1976 * the total value of totalTime and count are recorded, starting a new monotonically
1977 * increasing sample.
1978 *
1979 * @param totalTime total time of sample in microseconds.
1980 * @param count total number of times the event being sampled occurred.
1981 */
1982 public void update(long totalTime, int count) {
1983 if (mTimeBaseRunning && !mTrackingReportedValues) {
Evan Millarc64edde2009-04-18 12:26:32 -07001984 // Updating the reported value for the first time.
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001985 mUnpluggedReportedTotalTime = totalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001986 mUnpluggedReportedCount = count;
Evan Millarc64edde2009-04-18 12:26:32 -07001987 }
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001988
1989 mTrackingReportedValues = true;
1990
1991 if (totalTime < mCurrentReportedTotalTime || count < mCurrentReportedCount) {
1992 endSample();
1993 }
1994
1995 mCurrentReportedTotalTime = totalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001996 mCurrentReportedCount = count;
1997 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001998
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001999 /**
2000 * Adds deltaTime and deltaCount to the current sample.
2001 *
2002 * @param deltaTime additional time recorded since the last sampled event, in microseconds.
2003 * @param deltaCount additional number of times the event being sampled occurred.
2004 */
2005 public void add(long deltaTime, int deltaCount) {
2006 update(mCurrentReportedTotalTime + deltaTime, mCurrentReportedCount + deltaCount);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002007 }
2008
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002009 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002010 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
2011 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime);
Evan Millarc64edde2009-04-18 12:26:32 -07002012 if (mTrackingReportedValues) {
2013 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime;
2014 mUnpluggedReportedCount = mCurrentReportedCount;
2015 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002016 mTimeBaseRunning = true;
Evan Millarc64edde2009-04-18 12:26:32 -07002017 }
2018
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002019 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002020 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
2021 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
2022 mTimeBaseRunning = false;
Evan Millarc64edde2009-04-18 12:26:32 -07002023 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002024
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002025 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07002026 public void logState(Printer pw, String prefix) {
2027 super.logState(pw, prefix);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002028 pw.println(prefix + "mCurrentReportedCount=" + mCurrentReportedCount
Evan Millarc64edde2009-04-18 12:26:32 -07002029 + " mUnpluggedReportedCount=" + mUnpluggedReportedCount
2030 + " mCurrentReportedTotalTime=" + mCurrentReportedTotalTime
2031 + " mUnpluggedReportedTotalTime=" + mUnpluggedReportedTotalTime);
2032 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002033
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002034 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07002035 protected long computeRunTimeLocked(long curBatteryRealtime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002036 return mTotalTime + (mTimeBaseRunning && mTrackingReportedValues
Evan Millarc64edde2009-04-18 12:26:32 -07002037 ? mCurrentReportedTotalTime - mUnpluggedReportedTotalTime : 0);
2038 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002039
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002040 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07002041 protected int computeCurrentCountLocked() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002042 return mCount + (mTimeBaseRunning && mTrackingReportedValues
Evan Millarc64edde2009-04-18 12:26:32 -07002043 ? mCurrentReportedCount - mUnpluggedReportedCount : 0);
2044 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002045
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002046 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002047 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2048 super.writeToParcel(out, elapsedRealtimeUs);
Evan Millarc64edde2009-04-18 12:26:32 -07002049 out.writeInt(mCurrentReportedCount);
2050 out.writeInt(mUnpluggedReportedCount);
2051 out.writeLong(mCurrentReportedTotalTime);
2052 out.writeLong(mUnpluggedReportedTotalTime);
2053 out.writeInt(mTrackingReportedValues ? 1 : 0);
2054 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002055
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002056 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002057 public boolean reset(boolean detachIfReset) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002058 super.reset(detachIfReset);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002059 mTrackingReportedValues = false;
2060 mUnpluggedReportedTotalTime = 0;
2061 mUnpluggedReportedCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002062 return true;
2063 }
Evan Millarc64edde2009-04-18 12:26:32 -07002064 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002065
Evan Millarc64edde2009-04-18 12:26:32 -07002066 /**
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002067 * A timer that increments in batches. It does not run for durations, but just jumps
2068 * for a pre-determined amount.
2069 */
Joe Onoratoabded112016-02-08 16:49:39 -08002070 public static class BatchTimer extends Timer {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002071 final Uid mUid;
2072
2073 /**
2074 * The last time at which we updated the timer. This is in elapsed realtime microseconds.
2075 */
2076 long mLastAddedTime;
2077
2078 /**
2079 * The last duration that we added to the timer. This is in microseconds.
2080 */
2081 long mLastAddedDuration;
2082
2083 /**
2084 * Whether we are currently in a discharge cycle.
2085 */
2086 boolean mInDischarge;
2087
Joe Onoratoabded112016-02-08 16:49:39 -08002088 BatchTimer(Clocks clocks, Uid uid, int type, TimeBase timeBase, Parcel in) {
2089 super(clocks, type, timeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002090 mUid = uid;
2091 mLastAddedTime = in.readLong();
2092 mLastAddedDuration = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002093 mInDischarge = timeBase.isRunning();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002094 }
2095
Joe Onoratoabded112016-02-08 16:49:39 -08002096 BatchTimer(Clocks clocks, Uid uid, int type, TimeBase timeBase) {
2097 super(clocks, type, timeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002098 mUid = uid;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002099 mInDischarge = timeBase.isRunning();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002100 }
2101
2102 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002103 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2104 super.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002105 out.writeLong(mLastAddedTime);
2106 out.writeLong(mLastAddedDuration);
2107 }
2108
2109 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002110 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Joe Onoratoabded112016-02-08 16:49:39 -08002111 recomputeLastDuration(mClocks.elapsedRealtime() * 1000, false);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002112 mInDischarge = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002113 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002114 }
2115
2116 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002117 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002118 recomputeLastDuration(elapsedRealtime, false);
2119 mInDischarge = true;
2120 // If we are still within the last added duration, then re-added whatever remains.
2121 if (mLastAddedTime == elapsedRealtime) {
2122 mTotalTime += mLastAddedDuration;
2123 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002124 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002125 }
2126
2127 @Override
2128 public void logState(Printer pw, String prefix) {
2129 super.logState(pw, prefix);
2130 pw.println(prefix + "mLastAddedTime=" + mLastAddedTime
2131 + " mLastAddedDuration=" + mLastAddedDuration);
2132 }
2133
2134 private long computeOverage(long curTime) {
2135 if (mLastAddedTime > 0) {
2136 return mLastTime + mLastAddedDuration - curTime;
2137 }
2138 return 0;
2139 }
2140
2141 private void recomputeLastDuration(long curTime, boolean abort) {
2142 final long overage = computeOverage(curTime);
2143 if (overage > 0) {
2144 // Aborting before the duration ran out -- roll back the remaining
2145 // duration. Only do this if currently discharging; otherwise we didn't
2146 // actually add the time.
2147 if (mInDischarge) {
2148 mTotalTime -= overage;
2149 }
2150 if (abort) {
2151 mLastAddedTime = 0;
2152 } else {
2153 mLastAddedTime = curTime;
2154 mLastAddedDuration -= overage;
2155 }
2156 }
2157 }
2158
2159 public void addDuration(BatteryStatsImpl stats, long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08002160 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002161 recomputeLastDuration(now, true);
2162 mLastAddedTime = now;
2163 mLastAddedDuration = durationMillis * 1000;
2164 if (mInDischarge) {
2165 mTotalTime += mLastAddedDuration;
2166 mCount++;
2167 }
2168 }
2169
2170 public void abortLastDuration(BatteryStatsImpl stats) {
Joe Onoratoabded112016-02-08 16:49:39 -08002171 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002172 recomputeLastDuration(now, true);
2173 }
2174
2175 @Override
2176 protected int computeCurrentCountLocked() {
2177 return mCount;
2178 }
2179
2180 @Override
2181 protected long computeRunTimeLocked(long curBatteryRealtime) {
Joe Onoratoabded112016-02-08 16:49:39 -08002182 final long overage = computeOverage(mClocks.elapsedRealtime() * 1000);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002183 if (overage > 0) {
2184 return mTotalTime = overage;
2185 }
2186 return mTotalTime;
2187 }
2188
2189 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002190 public boolean reset(boolean detachIfReset) {
2191 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002192 recomputeLastDuration(now, true);
2193 boolean stillActive = mLastAddedTime == now;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002194 super.reset(!stillActive && detachIfReset);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002195 return !stillActive;
2196 }
2197 }
2198
Joe Onorato92fd23f2016-07-25 11:18:42 -07002199
2200 /**
2201 * A StopwatchTimer that also tracks the total and max individual
2202 * time spent active according to the given timebase. Whereas
2203 * StopwatchTimer apportions the time amongst all in the pool,
2204 * the total and max durations are not apportioned.
2205 */
2206 public static class DurationTimer extends StopwatchTimer {
2207 /**
2208 * The time (in ms) that the timer was last acquired or the time base
2209 * last (re-)started. Increasing the nesting depth does not reset this time.
2210 *
2211 * -1 if the timer is currently not running or the time base is not running.
2212 *
2213 * If written to a parcel, the start time is reset, as is mNesting in the base class
2214 * StopwatchTimer.
2215 */
2216 long mStartTimeMs = -1;
2217
2218 /**
Bookatz867c0d72017-03-07 18:23:42 -08002219 * The longest time period (in ms) that the timer has been active. Not pooled.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002220 */
2221 long mMaxDurationMs;
2222
2223 /**
Bookatz867c0d72017-03-07 18:23:42 -08002224 * The time (in ms) that that the timer has been active since most recent
2225 * stopRunningLocked() or reset(). Not pooled.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002226 */
2227 long mCurrentDurationMs;
2228
Bookatz867c0d72017-03-07 18:23:42 -08002229 /**
2230 * The total time (in ms) that that the timer has been active since most recent reset()
2231 * prior to the current startRunningLocked. This is the sum of all past currentDurations
2232 * (but not including the present currentDuration) since reset. Not pooled.
2233 */
2234 long mTotalDurationMs;
2235
Joe Onorato92fd23f2016-07-25 11:18:42 -07002236 public DurationTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2237 TimeBase timeBase, Parcel in) {
2238 super(clocks, uid, type, timerPool, timeBase, in);
2239 mMaxDurationMs = in.readLong();
Bookatz867c0d72017-03-07 18:23:42 -08002240 mTotalDurationMs = in.readLong();
jackqdyulei610a0a02017-08-09 14:02:01 -07002241 mCurrentDurationMs = in.readLong();
Joe Onorato92fd23f2016-07-25 11:18:42 -07002242 }
2243
2244 public DurationTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2245 TimeBase timeBase) {
2246 super(clocks, uid, type, timerPool, timeBase);
2247 }
2248
2249 @Override
2250 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2251 super.writeToParcel(out, elapsedRealtimeUs);
Kweku Adams47db5a82016-12-09 19:04:50 -08002252 out.writeLong(getMaxDurationMsLocked(elapsedRealtimeUs / 1000));
jackqdyulei610a0a02017-08-09 14:02:01 -07002253 out.writeLong(mTotalDurationMs);
2254 out.writeLong(getCurrentDurationMsLocked(elapsedRealtimeUs / 1000));
Joe Onorato92fd23f2016-07-25 11:18:42 -07002255 }
2256
2257 /**
2258 * Write the summary to the parcel.
2259 *
2260 * Since the time base is probably meaningless after we come back, reading
2261 * from this will have the effect of stopping the timer. So here all we write
Bookatz867c0d72017-03-07 18:23:42 -08002262 * is the max and total durations.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002263 */
2264 @Override
2265 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
2266 super.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
Kweku Adams47db5a82016-12-09 19:04:50 -08002267 out.writeLong(getMaxDurationMsLocked(elapsedRealtimeUs / 1000));
Bookatz867c0d72017-03-07 18:23:42 -08002268 out.writeLong(getTotalDurationMsLocked(elapsedRealtimeUs / 1000));
Joe Onorato92fd23f2016-07-25 11:18:42 -07002269 }
2270
2271 /**
2272 * Read the summary parcel.
2273 *
2274 * Has the side effect of stopping the timer.
2275 */
2276 @Override
2277 public void readSummaryFromParcelLocked(Parcel in) {
2278 super.readSummaryFromParcelLocked(in);
2279 mMaxDurationMs = in.readLong();
Bookatz867c0d72017-03-07 18:23:42 -08002280 mTotalDurationMs = in.readLong();
Joe Onorato92fd23f2016-07-25 11:18:42 -07002281 mStartTimeMs = -1;
2282 mCurrentDurationMs = 0;
2283 }
2284
2285 /**
2286 * The TimeBase time started (again).
2287 *
2288 * If the timer is also running, store the start time.
2289 */
2290 public void onTimeStarted(long elapsedRealtimeUs, long baseUptime, long baseRealtime) {
2291 super.onTimeStarted(elapsedRealtimeUs, baseUptime, baseRealtime);
2292 if (mNesting > 0) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002293 mStartTimeMs = baseRealtime / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002294 }
2295 }
2296
2297 /**
2298 * The TimeBase stopped running.
2299 *
2300 * If the timer is running, add the duration into mCurrentDurationMs.
2301 */
2302 @Override
Kweku Adams47db5a82016-12-09 19:04:50 -08002303 public void onTimeStopped(long elapsedRealtimeUs, long baseUptime, long baseRealtimeUs) {
2304 super.onTimeStopped(elapsedRealtimeUs, baseUptime, baseRealtimeUs);
Joe Onorato92fd23f2016-07-25 11:18:42 -07002305 if (mNesting > 0) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002306 // baseRealtimeUs has already been converted to the timebase's realtime.
2307 mCurrentDurationMs += (baseRealtimeUs / 1000) - mStartTimeMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002308 }
2309 mStartTimeMs = -1;
2310 }
2311
2312 @Override
2313 public void logState(Printer pw, String prefix) {
2314 super.logState(pw, prefix);
2315 }
2316
2317 @Override
2318 public void startRunningLocked(long elapsedRealtimeMs) {
2319 super.startRunningLocked(elapsedRealtimeMs);
2320 if (mNesting == 1 && mTimeBase.isRunning()) {
2321 // Just started
Kweku Adams47db5a82016-12-09 19:04:50 -08002322 mStartTimeMs = mTimeBase.getRealtime(elapsedRealtimeMs * 1000) / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002323 }
2324 }
2325
2326 /**
2327 * Decrements the mNesting ref-count on this timer.
2328 *
2329 * If it actually stopped (mNesting went to 0), then possibly update
2330 * mMaxDuration if the current duration was the longest ever.
2331 */
2332 @Override
2333 public void stopRunningLocked(long elapsedRealtimeMs) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002334 if (mNesting == 1) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07002335 final long durationMs = getCurrentDurationMsLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002336 mTotalDurationMs += durationMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002337 if (durationMs > mMaxDurationMs) {
2338 mMaxDurationMs = durationMs;
2339 }
2340 mStartTimeMs = -1;
2341 mCurrentDurationMs = 0;
2342 }
Kweku Adams47db5a82016-12-09 19:04:50 -08002343 // super method decrements mNesting, which getCurrentDurationMsLocked relies on,
2344 // so call super.stopRunningLocked after calling getCurrentDurationMsLocked.
2345 super.stopRunningLocked(elapsedRealtimeMs);
Joe Onorato92fd23f2016-07-25 11:18:42 -07002346 }
2347
2348 @Override
2349 public boolean reset(boolean detachIfReset) {
2350 boolean result = super.reset(detachIfReset);
2351 mMaxDurationMs = 0;
Bookatz867c0d72017-03-07 18:23:42 -08002352 mTotalDurationMs = 0;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002353 mCurrentDurationMs = 0;
2354 if (mNesting > 0) {
2355 mStartTimeMs = mTimeBase.getRealtime(mClocks.elapsedRealtime()*1000) / 1000;
2356 } else {
2357 mStartTimeMs = -1;
2358 }
2359 return result;
2360 }
2361
2362 /**
2363 * Returns the max duration that this timer has ever seen.
2364 *
2365 * Note that this time is NOT split between the timers in the timer group that
2366 * this timer is attached to. It is the TOTAL time.
2367 */
2368 @Override
2369 public long getMaxDurationMsLocked(long elapsedRealtimeMs) {
2370 if (mNesting > 0) {
2371 final long durationMs = getCurrentDurationMsLocked(elapsedRealtimeMs);
2372 if (durationMs > mMaxDurationMs) {
2373 return durationMs;
2374 }
2375 }
2376 return mMaxDurationMs;
2377 }
2378
2379 /**
2380 * Returns the time since the timer was started.
Bookatz867c0d72017-03-07 18:23:42 -08002381 * Returns 0 if the timer is not currently running.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002382 *
2383 * Note that this time is NOT split between the timers in the timer group that
2384 * this timer is attached to. It is the TOTAL time.
jackqdyulei610a0a02017-08-09 14:02:01 -07002385 *
2386 * Note that if running timer is parceled and unparceled, this method will return
2387 * current duration value at the time of parceling even though timer may not be
2388 * currently running.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002389 */
2390 @Override
2391 public long getCurrentDurationMsLocked(long elapsedRealtimeMs) {
2392 long durationMs = mCurrentDurationMs;
Kweku Adams47db5a82016-12-09 19:04:50 -08002393 if (mNesting > 0 && mTimeBase.isRunning()) {
2394 durationMs += (mTimeBase.getRealtime(elapsedRealtimeMs*1000)/1000)
2395 - mStartTimeMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002396 }
2397 return durationMs;
2398 }
Bookatz867c0d72017-03-07 18:23:42 -08002399
2400 /**
2401 * Returns the total cumulative duration that this timer has been on since reset().
2402 * If mTimerPool == null, this should be the same
2403 * as getTotalTimeLocked(elapsedRealtimeMs*1000, STATS_SINCE_CHARGED)/1000.
2404 *
2405 * Note that this time is NOT split between the timers in the timer group that
2406 * this timer is attached to. It is the TOTAL time. For this reason, if mTimerPool != null,
2407 * the result will not be equivalent to getTotalTimeLocked.
2408 */
2409 @Override
2410 public long getTotalDurationMsLocked(long elapsedRealtimeMs) {
2411 return mTotalDurationMs + getCurrentDurationMsLocked(elapsedRealtimeMs);
2412 }
Joe Onorato92fd23f2016-07-25 11:18:42 -07002413 }
2414
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002415 /**
Evan Millarc64edde2009-04-18 12:26:32 -07002416 * State for keeping track of timing information.
2417 */
Joe Onoratoabded112016-02-08 16:49:39 -08002418 public static class StopwatchTimer extends Timer {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002419 final Uid mUid;
Evan Millarc64edde2009-04-18 12:26:32 -07002420 final ArrayList<StopwatchTimer> mTimerPool;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002421
Evan Millarc64edde2009-04-18 12:26:32 -07002422 int mNesting;
2423
Evan Millarc64edde2009-04-18 12:26:32 -07002424 /**
2425 * The last time at which we updated the timer. If mNesting is > 0,
2426 * subtract this from the current battery time to find the amount of
2427 * time we have been running since we last computed an update.
2428 */
2429 long mUpdateTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002430
Evan Millarc64edde2009-04-18 12:26:32 -07002431 /**
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002432 * The total time at which the timer was acquired, to determine if it
Bookatzceebafe2017-04-06 11:59:13 -07002433 * was actually held for an interesting duration. If time base was not running when timer
2434 * was acquired, will be -1.
Evan Millarc64edde2009-04-18 12:26:32 -07002435 */
Bookatzceebafe2017-04-06 11:59:13 -07002436 long mAcquireTime = -1;
Evan Millarc64edde2009-04-18 12:26:32 -07002437
Amith Yamasanif37447b2009-10-08 18:28:01 -07002438 long mTimeout;
2439
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002440 /**
2441 * For partial wake locks, keep track of whether we are in the list
2442 * to consume CPU cycles.
2443 */
Sudheer Shanka38383232017-07-25 09:55:03 -07002444 @VisibleForTesting
2445 public boolean mInList;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002446
Joe Onoratoabded112016-02-08 16:49:39 -08002447 public StopwatchTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002448 TimeBase timeBase, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08002449 super(clocks, type, timeBase, in);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002450 mUid = uid;
Evan Millarc64edde2009-04-18 12:26:32 -07002451 mTimerPool = timerPool;
2452 mUpdateTime = in.readLong();
2453 }
2454
Joe Onoratoabded112016-02-08 16:49:39 -08002455 public StopwatchTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002456 TimeBase timeBase) {
Joe Onoratoabded112016-02-08 16:49:39 -08002457 super(clocks, type, timeBase);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002458 mUid = uid;
Evan Millarc64edde2009-04-18 12:26:32 -07002459 mTimerPool = timerPool;
2460 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002461
Joe Onoratoabded112016-02-08 16:49:39 -08002462 public void setTimeout(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07002463 mTimeout = timeout;
2464 }
2465
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002466 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2467 super.writeToParcel(out, elapsedRealtimeUs);
Evan Millarc64edde2009-04-18 12:26:32 -07002468 out.writeLong(mUpdateTime);
2469 }
2470
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002471 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Evan Millarc64edde2009-04-18 12:26:32 -07002472 if (mNesting > 0) {
2473 if (DEBUG && mType < 0) {
2474 Log.v(TAG, "old mUpdateTime=" + mUpdateTime);
2475 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002476 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
2477 mUpdateTime = baseRealtime;
Evan Millarc64edde2009-04-18 12:26:32 -07002478 if (DEBUG && mType < 0) {
2479 Log.v(TAG, "new mUpdateTime=" + mUpdateTime);
2480 }
2481 }
2482 }
2483
2484 public void logState(Printer pw, String prefix) {
2485 super.logState(pw, prefix);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07002486 pw.println(prefix + "mNesting=" + mNesting + " mUpdateTime=" + mUpdateTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002487 + " mAcquireTime=" + mAcquireTime);
2488 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002489
Joe Onoratoabded112016-02-08 16:49:39 -08002490 public void startRunningLocked(long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002491 if (mNesting++ == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002492 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002493 mUpdateTime = batteryRealtime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002494 if (mTimerPool != null) {
2495 // Accumulate time to all currently active timers before adding
2496 // this new one to the pool.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002497 refreshTimersLocked(batteryRealtime, mTimerPool, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002498 // Add this timer to the active pool
2499 mTimerPool.add(this);
2500 }
Bookatzceebafe2017-04-06 11:59:13 -07002501 if (mTimeBase.isRunning()) {
2502 // Increment the count
2503 mCount++;
2504 mAcquireTime = mTotalTime;
2505 } else {
2506 mAcquireTime = -1;
2507 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002508 if (DEBUG && mType < 0) {
2509 Log.v(TAG, "start #" + mType + ": mUpdateTime=" + mUpdateTime
2510 + " mTotalTime=" + mTotalTime + " mCount=" + mCount
2511 + " mAcquireTime=" + mAcquireTime);
2512 }
2513 }
2514 }
2515
Joe Onoratoabded112016-02-08 16:49:39 -08002516 public boolean isRunningLocked() {
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002517 return mNesting > 0;
2518 }
2519
Joe Onoratoabded112016-02-08 16:49:39 -08002520 public void stopRunningLocked(long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002521 // Ignore attempt to stop a timer that isn't running
2522 if (mNesting == 0) {
2523 return;
2524 }
2525 if (--mNesting == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002526 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527 if (mTimerPool != null) {
2528 // Accumulate time to all active counters, scaled by the total
2529 // active in the pool, before taking this one out of the pool.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002530 refreshTimersLocked(batteryRealtime, mTimerPool, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002531 // Remove this timer from the active pool
2532 mTimerPool.remove(this);
2533 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 mNesting = 1;
2535 mTotalTime = computeRunTimeLocked(batteryRealtime);
2536 mNesting = 0;
2537 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002539 if (DEBUG && mType < 0) {
2540 Log.v(TAG, "stop #" + mType + ": mUpdateTime=" + mUpdateTime
2541 + " mTotalTime=" + mTotalTime + " mCount=" + mCount
2542 + " mAcquireTime=" + mAcquireTime);
2543 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002544
Bookatzceebafe2017-04-06 11:59:13 -07002545 if (mAcquireTime >= 0 && mTotalTime == mAcquireTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002546 // If there was no change in the time, then discard this
2547 // count. A somewhat cheezy strategy, but hey.
2548 mCount--;
2549 }
2550 }
2551 }
2552
Joe Onoratoabded112016-02-08 16:49:39 -08002553 public void stopAllRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07002554 if (mNesting > 0) {
2555 mNesting = 1;
2556 stopRunningLocked(elapsedRealtimeMs);
2557 }
2558 }
2559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002560 // Update the total time for all other running Timers with the same type as this Timer
2561 // due to a change in timer count
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002562 private static long refreshTimersLocked(long batteryRealtime,
2563 final ArrayList<StopwatchTimer> pool, StopwatchTimer self) {
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002564 long selfTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002565 final int N = pool.size();
2566 for (int i=N-1; i>= 0; i--) {
Evan Millarc64edde2009-04-18 12:26:32 -07002567 final StopwatchTimer t = pool.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002568 long heldTime = batteryRealtime - t.mUpdateTime;
2569 if (heldTime > 0) {
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002570 final long myTime = heldTime / N;
2571 if (t == self) {
2572 selfTime = myTime;
2573 }
2574 t.mTotalTime += myTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002575 }
2576 t.mUpdateTime = batteryRealtime;
2577 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002578 return selfTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 }
2580
Evan Millarc64edde2009-04-18 12:26:32 -07002581 @Override
2582 protected long computeRunTimeLocked(long curBatteryRealtime) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07002583 if (mTimeout > 0 && curBatteryRealtime > mUpdateTime + mTimeout) {
2584 curBatteryRealtime = mUpdateTime + mTimeout;
2585 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002586 return mTotalTime + (mNesting > 0
2587 ? (curBatteryRealtime - mUpdateTime)
2588 / (mTimerPool != null ? mTimerPool.size() : 1)
2589 : 0);
2590 }
2591
Evan Millarc64edde2009-04-18 12:26:32 -07002592 @Override
2593 protected int computeCurrentCountLocked() {
2594 return mCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002595 }
2596
Adam Lesinskie08af192015-03-25 16:42:59 -07002597 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002598 public boolean reset(boolean detachIfReset) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002599 boolean canDetach = mNesting <= 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002600 super.reset(canDetach && detachIfReset);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002601 if (mNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08002602 mUpdateTime = mTimeBase.getRealtime(mClocks.elapsedRealtime() * 1000);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002603 }
Bookatzceebafe2017-04-06 11:59:13 -07002604 mAcquireTime = -1; // to ensure mCount isn't decreased to -1 if timer is stopped later.
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002605 return canDetach;
2606 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002607
Adam Lesinskie08af192015-03-25 16:42:59 -07002608 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002609 public void detach() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002610 super.detach();
2611 if (mTimerPool != null) {
2612 mTimerPool.remove(this);
2613 }
2614 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002615
Adam Lesinskie08af192015-03-25 16:42:59 -07002616 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002617 public void readSummaryFromParcelLocked(Parcel in) {
Evan Millarc64edde2009-04-18 12:26:32 -07002618 super.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002619 mNesting = 0;
2620 }
Adam Lesinskie08af192015-03-25 16:42:59 -07002621
2622 /**
2623 * Set the mark so that we can query later for the total time the timer has
2624 * accumulated since this point. The timer can be running or not.
2625 *
2626 * @param elapsedRealtimeMs the current elapsed realtime in milliseconds.
2627 */
2628 public void setMark(long elapsedRealtimeMs) {
2629 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
2630 if (mNesting > 0) {
2631 // We are running.
2632 if (mTimerPool != null) {
2633 refreshTimersLocked(batteryRealtime, mTimerPool, this);
2634 } else {
2635 mTotalTime += batteryRealtime - mUpdateTime;
2636 mUpdateTime = batteryRealtime;
2637 }
2638 }
2639 mTimeBeforeMark = mTotalTime;
2640 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002641 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002642
Bookatz867c0d72017-03-07 18:23:42 -08002643 /**
2644 * State for keeping track of two DurationTimers with different TimeBases, presumably where one
2645 * TimeBase is effectively a subset of the other.
2646 */
Bookatzaa4594a2017-03-24 12:39:56 -07002647 public static class DualTimer extends DurationTimer {
2648 // This class both is a DurationTimer and also holds a second DurationTimer.
2649 // The main timer (this) typically tracks the total time. It may be pooled (but since it's a
2650 // durationTimer, it also has the unpooled getTotalDurationMsLocked() for
2651 // STATS_SINCE_CHARGED).
Bookatz867c0d72017-03-07 18:23:42 -08002652 // mSubTimer typically tracks only part of the total time, such as background time, as
2653 // determined by a subTimeBase. It is NOT pooled.
2654 private final DurationTimer mSubTimer;
2655
2656 /**
Bookatzaa4594a2017-03-24 12:39:56 -07002657 * Creates a DualTimer to hold a main timer (this) and a mSubTimer.
2658 * The main timer (this) is based on the given timeBase and timerPool.
Bookatz867c0d72017-03-07 18:23:42 -08002659 * The mSubTimer is based on the given subTimeBase. The mSubTimer is not pooled, even if
Bookatzaa4594a2017-03-24 12:39:56 -07002660 * the main timer is.
Bookatz867c0d72017-03-07 18:23:42 -08002661 */
2662 public DualTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2663 TimeBase timeBase, TimeBase subTimeBase, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07002664 super(clocks, uid, type, timerPool, timeBase, in);
Bookatz867c0d72017-03-07 18:23:42 -08002665 mSubTimer = new DurationTimer(clocks, uid, type, null, subTimeBase, in);
2666 }
2667
2668 /**
Bookatzaa4594a2017-03-24 12:39:56 -07002669 * Creates a DualTimer to hold a main timer (this) and a mSubTimer.
2670 * The main timer (this) is based on the given timeBase and timerPool.
Bookatz867c0d72017-03-07 18:23:42 -08002671 * The mSubTimer is based on the given subTimeBase. The mSubTimer is not pooled, even if
Bookatzaa4594a2017-03-24 12:39:56 -07002672 * the main timer is.
Bookatz867c0d72017-03-07 18:23:42 -08002673 */
2674 public DualTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2675 TimeBase timeBase, TimeBase subTimeBase) {
Bookatzaa4594a2017-03-24 12:39:56 -07002676 super(clocks, uid, type, timerPool, timeBase);
Bookatz867c0d72017-03-07 18:23:42 -08002677 mSubTimer = new DurationTimer(clocks, uid, type, null, subTimeBase);
2678 }
2679
Bookatz867c0d72017-03-07 18:23:42 -08002680 /** Get the secondary timer. */
Bookatzaa4594a2017-03-24 12:39:56 -07002681 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002682 public DurationTimer getSubTimer() {
2683 return mSubTimer;
2684 }
2685
Bookatzaa4594a2017-03-24 12:39:56 -07002686 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002687 public void startRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002688 super.startRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002689 mSubTimer.startRunningLocked(elapsedRealtimeMs);
2690 }
2691
Bookatzaa4594a2017-03-24 12:39:56 -07002692 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002693 public void stopRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002694 super.stopRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002695 mSubTimer.stopRunningLocked(elapsedRealtimeMs);
2696 }
2697
Bookatzaa4594a2017-03-24 12:39:56 -07002698 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002699 public void stopAllRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002700 super.stopAllRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002701 mSubTimer.stopAllRunningLocked(elapsedRealtimeMs);
2702 }
2703
Bookatzaa4594a2017-03-24 12:39:56 -07002704 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002705 public boolean reset(boolean detachIfReset) {
2706 boolean active = false;
Bookatz4a3eda92017-04-10 13:10:46 -07002707 // Do not detach the subTimer explicitly since that'll be done by DualTimer.detach().
2708 active |= !mSubTimer.reset(false);
Bookatzaa4594a2017-03-24 12:39:56 -07002709 active |= !super.reset(detachIfReset);
Bookatz867c0d72017-03-07 18:23:42 -08002710 return !active;
2711 }
2712
Bookatzaa4594a2017-03-24 12:39:56 -07002713 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002714 public void detach() {
Bookatz867c0d72017-03-07 18:23:42 -08002715 mSubTimer.detach();
Bookatz4a3eda92017-04-10 13:10:46 -07002716 super.detach();
Bookatz867c0d72017-03-07 18:23:42 -08002717 }
2718
Bookatzaa4594a2017-03-24 12:39:56 -07002719 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002720 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002721 super.writeToParcel(out, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08002722 mSubTimer.writeToParcel(out, elapsedRealtimeUs);
2723 }
2724
Bookatzaa4594a2017-03-24 12:39:56 -07002725 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002726 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002727 super.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08002728 mSubTimer.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
2729 }
2730
Bookatzaa4594a2017-03-24 12:39:56 -07002731 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002732 public void readSummaryFromParcelLocked(Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07002733 super.readSummaryFromParcelLocked(in);
Bookatz867c0d72017-03-07 18:23:42 -08002734 mSubTimer.readSummaryFromParcelLocked(in);
2735 }
2736 }
2737
2738
Dianne Hackbornd953c532014-08-16 18:17:38 -07002739 public abstract class OverflowArrayMap<T> {
2740 private static final String OVERFLOW_NAME = "*overflow*";
2741
Dianne Hackborn657153b2016-07-29 14:54:14 -07002742 final int mUid;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002743 final ArrayMap<String, T> mMap = new ArrayMap<>();
2744 T mCurOverflow;
2745 ArrayMap<String, MutableInt> mActiveOverflow;
Dianne Hackborn657153b2016-07-29 14:54:14 -07002746 long mLastOverflowTime;
2747 long mLastOverflowFinishTime;
2748 long mLastClearTime;
2749 long mLastCleanupTime;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002750
Dianne Hackborn657153b2016-07-29 14:54:14 -07002751 public OverflowArrayMap(int uid) {
2752 mUid = uid;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002753 }
2754
2755 public ArrayMap<String, T> getMap() {
2756 return mMap;
2757 }
2758
2759 public void clear() {
Dianne Hackborn657153b2016-07-29 14:54:14 -07002760 mLastClearTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002761 mMap.clear();
2762 mCurOverflow = null;
2763 mActiveOverflow = null;
2764 }
2765
2766 public void add(String name, T obj) {
Joe Onorato388fc332016-04-12 17:06:47 -07002767 if (name == null) {
2768 name = "";
2769 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002770 mMap.put(name, obj);
2771 if (OVERFLOW_NAME.equals(name)) {
2772 mCurOverflow = obj;
2773 }
2774 }
2775
2776 public void cleanup() {
Dianne Hackborn657153b2016-07-29 14:54:14 -07002777 mLastCleanupTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002778 if (mActiveOverflow != null) {
2779 if (mActiveOverflow.size() == 0) {
2780 mActiveOverflow = null;
2781 }
2782 }
2783 if (mActiveOverflow == null) {
2784 // There is no currently active overflow, so we should no longer have
2785 // an overflow entry.
2786 if (mMap.containsKey(OVERFLOW_NAME)) {
2787 Slog.wtf(TAG, "Cleaning up with no active overflow, but have overflow entry "
2788 + mMap.get(OVERFLOW_NAME));
2789 mMap.remove(OVERFLOW_NAME);
2790 }
2791 mCurOverflow = null;
2792 } else {
2793 // There is currently active overflow, so we should still have an overflow entry.
2794 if (mCurOverflow == null || !mMap.containsKey(OVERFLOW_NAME)) {
2795 Slog.wtf(TAG, "Cleaning up with active overflow, but no overflow entry: cur="
2796 + mCurOverflow + " map=" + mMap.get(OVERFLOW_NAME));
2797 }
2798 }
2799 }
2800
2801 public T startObject(String name) {
Joe Onorato388fc332016-04-12 17:06:47 -07002802 if (name == null) {
2803 name = "";
2804 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002805 T obj = mMap.get(name);
2806 if (obj != null) {
2807 return obj;
2808 }
2809
2810 // No object exists for the given name, but do we currently have it
2811 // running as part of the overflow?
2812 if (mActiveOverflow != null) {
2813 MutableInt over = mActiveOverflow.get(name);
2814 if (over != null) {
2815 // We are already actively counting this name in the overflow object.
2816 obj = mCurOverflow;
2817 if (obj == null) {
2818 // Shouldn't be here, but we'll try to recover.
2819 Slog.wtf(TAG, "Have active overflow " + name + " but null overflow");
2820 obj = mCurOverflow = instantiateObject();
2821 mMap.put(OVERFLOW_NAME, obj);
2822 }
2823 over.value++;
2824 return obj;
2825 }
2826 }
2827
2828 // No object exists for given name nor in the overflow; we need to make
2829 // a new one.
2830 final int N = mMap.size();
2831 if (N >= MAX_WAKELOCKS_PER_UID) {
2832 // Went over the limit on number of objects to track; this one goes
2833 // in to the overflow.
2834 obj = mCurOverflow;
2835 if (obj == null) {
2836 // Need to start overflow now...
2837 obj = mCurOverflow = instantiateObject();
2838 mMap.put(OVERFLOW_NAME, obj);
2839 }
2840 if (mActiveOverflow == null) {
2841 mActiveOverflow = new ArrayMap<>();
2842 }
2843 mActiveOverflow.put(name, new MutableInt(1));
Dianne Hackborn657153b2016-07-29 14:54:14 -07002844 mLastOverflowTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002845 return obj;
2846 }
2847
2848 // Normal case where we just need to make a new object.
2849 obj = instantiateObject();
2850 mMap.put(name, obj);
2851 return obj;
2852 }
2853
2854 public T stopObject(String name) {
Joe Onorato388fc332016-04-12 17:06:47 -07002855 if (name == null) {
2856 name = "";
2857 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002858 T obj = mMap.get(name);
2859 if (obj != null) {
2860 return obj;
2861 }
2862
2863 // No object exists for the given name, but do we currently have it
2864 // running as part of the overflow?
2865 if (mActiveOverflow != null) {
2866 MutableInt over = mActiveOverflow.get(name);
2867 if (over != null) {
2868 // We are already actively counting this name in the overflow object.
2869 obj = mCurOverflow;
2870 if (obj != null) {
2871 over.value--;
2872 if (over.value <= 0) {
2873 mActiveOverflow.remove(name);
Dianne Hackborn657153b2016-07-29 14:54:14 -07002874 mLastOverflowFinishTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002875 }
2876 return obj;
2877 }
2878 }
2879 }
2880
2881 // Huh, they are stopping an active operation but we can't find one!
2882 // That's not good.
Dianne Hackborn657153b2016-07-29 14:54:14 -07002883 StringBuilder sb = new StringBuilder();
2884 sb.append("Unable to find object for ");
2885 sb.append(name);
2886 sb.append(" in uid ");
2887 sb.append(mUid);
2888 sb.append(" mapsize=");
2889 sb.append(mMap.size());
2890 sb.append(" activeoverflow=");
2891 sb.append(mActiveOverflow);
2892 sb.append(" curoverflow=");
2893 sb.append(mCurOverflow);
2894 long now = SystemClock.elapsedRealtime();
2895 if (mLastOverflowTime != 0) {
2896 sb.append(" lastOverflowTime=");
2897 TimeUtils.formatDuration(mLastOverflowTime-now, sb);
2898 }
2899 if (mLastOverflowFinishTime != 0) {
2900 sb.append(" lastOverflowFinishTime=");
2901 TimeUtils.formatDuration(mLastOverflowFinishTime-now, sb);
2902 }
2903 if (mLastClearTime != 0) {
2904 sb.append(" lastClearTime=");
2905 TimeUtils.formatDuration(mLastClearTime-now, sb);
2906 }
2907 if (mLastCleanupTime != 0) {
2908 sb.append(" lastCleanupTime=");
2909 TimeUtils.formatDuration(mLastCleanupTime-now, sb);
2910 }
2911 Slog.wtf(TAG, sb.toString());
Dianne Hackbornd953c532014-08-16 18:17:38 -07002912 return null;
2913 }
2914
2915 public abstract T instantiateObject();
2916 }
2917
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002918 public static class ControllerActivityCounterImpl extends ControllerActivityCounter
2919 implements Parcelable {
2920 private final LongSamplingCounter mIdleTimeMillis;
Siddharth Rayb50a6842017-12-14 15:15:28 -08002921 private final LongSamplingCounter mScanTimeMillis;
Siddharth Rayed754702018-02-15 12:44:37 -08002922 private final LongSamplingCounter mSleepTimeMillis;
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002923 private final LongSamplingCounter mRxTimeMillis;
2924 private final LongSamplingCounter[] mTxTimeMillis;
2925 private final LongSamplingCounter mPowerDrainMaMs;
2926
2927 public ControllerActivityCounterImpl(TimeBase timeBase, int numTxStates) {
2928 mIdleTimeMillis = new LongSamplingCounter(timeBase);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002929 mScanTimeMillis = new LongSamplingCounter(timeBase);
Siddharth Rayed754702018-02-15 12:44:37 -08002930 mSleepTimeMillis = new LongSamplingCounter(timeBase);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002931 mRxTimeMillis = new LongSamplingCounter(timeBase);
2932 mTxTimeMillis = new LongSamplingCounter[numTxStates];
2933 for (int i = 0; i < numTxStates; i++) {
2934 mTxTimeMillis[i] = new LongSamplingCounter(timeBase);
2935 }
2936 mPowerDrainMaMs = new LongSamplingCounter(timeBase);
2937 }
2938
2939 public ControllerActivityCounterImpl(TimeBase timeBase, int numTxStates, Parcel in) {
2940 mIdleTimeMillis = new LongSamplingCounter(timeBase, in);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002941 mScanTimeMillis = new LongSamplingCounter(timeBase, in);
Siddharth Rayed754702018-02-15 12:44:37 -08002942 mSleepTimeMillis = new LongSamplingCounter(timeBase, in);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002943 mRxTimeMillis = new LongSamplingCounter(timeBase, in);
2944 final int recordedTxStates = in.readInt();
2945 if (recordedTxStates != numTxStates) {
2946 throw new ParcelFormatException("inconsistent tx state lengths");
2947 }
2948
2949 mTxTimeMillis = new LongSamplingCounter[numTxStates];
2950 for (int i = 0; i < numTxStates; i++) {
2951 mTxTimeMillis[i] = new LongSamplingCounter(timeBase, in);
2952 }
2953 mPowerDrainMaMs = new LongSamplingCounter(timeBase, in);
2954 }
2955
2956 public void readSummaryFromParcel(Parcel in) {
2957 mIdleTimeMillis.readSummaryFromParcelLocked(in);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002958 mScanTimeMillis.readSummaryFromParcelLocked(in);
Siddharth Rayed754702018-02-15 12:44:37 -08002959 mSleepTimeMillis.readSummaryFromParcelLocked(in);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002960 mRxTimeMillis.readSummaryFromParcelLocked(in);
2961 final int recordedTxStates = in.readInt();
2962 if (recordedTxStates != mTxTimeMillis.length) {
2963 throw new ParcelFormatException("inconsistent tx state lengths");
2964 }
2965 for (LongSamplingCounter counter : mTxTimeMillis) {
2966 counter.readSummaryFromParcelLocked(in);
2967 }
2968 mPowerDrainMaMs.readSummaryFromParcelLocked(in);
2969 }
2970
2971 @Override
2972 public int describeContents() {
2973 return 0;
2974 }
2975
2976 public void writeSummaryToParcel(Parcel dest) {
2977 mIdleTimeMillis.writeSummaryFromParcelLocked(dest);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002978 mScanTimeMillis.writeSummaryFromParcelLocked(dest);
Siddharth Rayed754702018-02-15 12:44:37 -08002979 mSleepTimeMillis.writeSummaryFromParcelLocked(dest);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002980 mRxTimeMillis.writeSummaryFromParcelLocked(dest);
2981 dest.writeInt(mTxTimeMillis.length);
2982 for (LongSamplingCounter counter : mTxTimeMillis) {
2983 counter.writeSummaryFromParcelLocked(dest);
2984 }
2985 mPowerDrainMaMs.writeSummaryFromParcelLocked(dest);
2986 }
2987
2988 @Override
2989 public void writeToParcel(Parcel dest, int flags) {
2990 mIdleTimeMillis.writeToParcel(dest);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002991 mScanTimeMillis.writeToParcel(dest);
Siddharth Rayed754702018-02-15 12:44:37 -08002992 mSleepTimeMillis.writeToParcel(dest);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002993 mRxTimeMillis.writeToParcel(dest);
2994 dest.writeInt(mTxTimeMillis.length);
2995 for (LongSamplingCounter counter : mTxTimeMillis) {
2996 counter.writeToParcel(dest);
2997 }
2998 mPowerDrainMaMs.writeToParcel(dest);
2999 }
3000
3001 public void reset(boolean detachIfReset) {
3002 mIdleTimeMillis.reset(detachIfReset);
Siddharth Rayb50a6842017-12-14 15:15:28 -08003003 mScanTimeMillis.reset(detachIfReset);
Siddharth Rayed754702018-02-15 12:44:37 -08003004 mSleepTimeMillis.reset(detachIfReset);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08003005 mRxTimeMillis.reset(detachIfReset);
3006 for (LongSamplingCounter counter : mTxTimeMillis) {
3007 counter.reset(detachIfReset);
3008 }
3009 mPowerDrainMaMs.reset(detachIfReset);
3010 }
3011
3012 public void detach() {
3013 mIdleTimeMillis.detach();
Siddharth Rayb50a6842017-12-14 15:15:28 -08003014 mScanTimeMillis.detach();
Siddharth Rayed754702018-02-15 12:44:37 -08003015 mSleepTimeMillis.detach();
Adam Lesinski21f76aa2016-01-25 12:27:06 -08003016 mRxTimeMillis.detach();
3017 for (LongSamplingCounter counter : mTxTimeMillis) {
3018 counter.detach();
3019 }
3020 mPowerDrainMaMs.detach();
3021 }
3022
3023 /**
3024 * @return a LongSamplingCounter, measuring time spent in the idle state in
3025 * milliseconds.
3026 */
3027 @Override
3028 public LongSamplingCounter getIdleTimeCounter() {
Roshan Pius81643302016-03-14 16:45:55 -07003029 return mIdleTimeMillis;
Adam Lesinski21f76aa2016-01-25 12:27:06 -08003030 }
3031
3032 /**
Siddharth Rayb50a6842017-12-14 15:15:28 -08003033 * @return a LongSamplingCounter, measuring time spent in the scan state in
3034 * milliseconds.
3035 */
3036 @Override
3037 public LongSamplingCounter getScanTimeCounter() {
3038 return mScanTimeMillis;
3039 }
3040
3041 /**
Siddharth Rayed754702018-02-15 12:44:37 -08003042 * @return a LongSamplingCounter, measuring time spent in the sleep state in
3043 * milliseconds.
3044 */
3045 @Override
3046 public LongSamplingCounter getSleepTimeCounter() {
3047 return mSleepTimeMillis;
3048 }
3049
3050 /**
Adam Lesinski21f76aa2016-01-25 12:27:06 -08003051 * @return a LongSamplingCounter, measuring time spent in the receive state in
3052 * milliseconds.
3053 */
3054 @Override
3055 public LongSamplingCounter getRxTimeCounter() {
3056 return mRxTimeMillis;
3057 }
3058
3059 /**
3060 * @return a LongSamplingCounter[], measuring time spent in various transmit states in
3061 * milliseconds.
3062 */
3063 @Override
3064 public LongSamplingCounter[] getTxTimeCounters() {
3065 return mTxTimeMillis;
3066 }
3067
3068 /**
3069 * @return a LongSamplingCounter, measuring power use in milli-ampere milliseconds (mAmS).
3070 */
3071 @Override
3072 public LongSamplingCounter getPowerCounter() {
3073 return mPowerDrainMaMs;
3074 }
3075 }
3076
Bookatz50df7112017-08-04 14:53:26 -07003077 /** Get Resource Power Manager stats. Create a new one if it doesn't already exist. */
3078 public SamplingTimer getRpmTimerLocked(String name) {
3079 SamplingTimer rpmt = mRpmStats.get(name);
3080 if (rpmt == null) {
3081 rpmt = new SamplingTimer(mClocks, mOnBatteryTimeBase);
3082 mRpmStats.put(name, rpmt);
3083 }
3084 return rpmt;
3085 }
3086
3087 /** Get Screen-off Resource Power Manager stats. Create new one if it doesn't already exist. */
3088 public SamplingTimer getScreenOffRpmTimerLocked(String name) {
3089 SamplingTimer rpmt = mScreenOffRpmStats.get(name);
3090 if (rpmt == null) {
3091 rpmt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
3092 mScreenOffRpmStats.put(name, rpmt);
3093 }
3094 return rpmt;
3095 }
3096
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003097 /*
3098 * Get the wakeup reason counter, and create a new one if one
3099 * doesn't already exist.
3100 */
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07003101 public SamplingTimer getWakeupReasonTimerLocked(String name) {
3102 SamplingTimer timer = mWakeupReasonStats.get(name);
3103 if (timer == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07003104 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07003105 mWakeupReasonStats.put(name, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003106 }
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07003107 return timer;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003108 }
3109
Evan Millarc64edde2009-04-18 12:26:32 -07003110 /*
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003111 * Get the KernelWakelockTimer associated with name, and create a new one if one
Evan Millarc64edde2009-04-18 12:26:32 -07003112 * doesn't already exist.
3113 */
3114 public SamplingTimer getKernelWakelockTimerLocked(String name) {
3115 SamplingTimer kwlt = mKernelWakelockStats.get(name);
3116 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07003117 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Evan Millarc64edde2009-04-18 12:26:32 -07003118 mKernelWakelockStats.put(name, kwlt);
3119 }
3120 return kwlt;
3121 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07003122
James Carr3a226052016-07-01 14:49:52 -07003123 public SamplingTimer getKernelMemoryTimerLocked(long bucket) {
3124 SamplingTimer kmt = mKernelMemoryStats.get(bucket);
3125 if (kmt == null) {
3126 kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase);
3127 mKernelMemoryStats.put(bucket, kmt);
3128 }
3129 return kmt;
3130 }
3131
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003132 private int writeHistoryTag(HistoryTag tag) {
3133 Integer idxObj = mHistoryTagPool.get(tag);
3134 int idx;
3135 if (idxObj != null) {
3136 idx = idxObj;
3137 } else {
3138 idx = mNextHistoryTagIdx;
3139 HistoryTag key = new HistoryTag();
3140 key.setTo(tag);
3141 tag.poolIdx = idx;
3142 mHistoryTagPool.put(key, idx);
3143 mNextHistoryTagIdx++;
3144 mNumHistoryTagChars += key.string.length() + 1;
3145 }
3146 return idx;
3147 }
3148
3149 private void readHistoryTag(int index, HistoryTag tag) {
3150 tag.string = mReadHistoryStrings[index];
3151 tag.uid = mReadHistoryUids[index];
3152 tag.poolIdx = index;
3153 }
3154
Adam Lesinski926969b2016-04-28 17:31:12 -07003155 /*
3156 The history delta format uses flags to denote further data in subsequent ints in the parcel.
3157
3158 There is always the first token, which may contain the delta time, or an indicator of
3159 the length of the time (int or long) following this token.
3160
3161 First token: always present,
3162 31 23 15 7 0
3163 â–ˆ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â–ˆ
3164
3165 T: the delta time if it is <= 0x7fffd. Otherwise 0x7fffe indicates an int immediately
3166 follows containing the time, and 0x7ffff indicates a long immediately follows with the
3167 delta time.
3168 A: battery level changed and an int follows with battery data.
3169 B: state changed and an int follows with state change data.
3170 C: state2 has changed and an int follows with state2 change data.
3171 D: wakelock/wakereason has changed and an wakelock/wakereason struct follows.
3172 E: event data has changed and an event struct follows.
3173 F: battery charge in coulombs has changed and an int with the charge follows.
3174 G: state flag denoting that the mobile radio was active.
3175 H: state flag denoting that the wifi radio was active.
3176 I: state flag denoting that a wifi scan occurred.
3177 J: state flag denoting that a wifi full lock was held.
3178 K: state flag denoting that the gps was on.
3179 L: state flag denoting that a wakelock was held.
3180 M: state flag denoting that the cpu was running.
3181
3182 Time int/long: if T in the first token is 0x7ffff or 0x7fffe, then an int or long follows
3183 with the time delta.
3184
3185 Battery level int: if A in the first token is set,
3186 31 23 15 7 0
3187 â–ˆ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â–ˆ
3188
3189 D: indicates that extra history details follow.
3190 V: the battery voltage.
3191 T: the battery temperature.
3192 L: the battery level (out of 100).
3193
3194 State change int: if B in the first token is set,
3195 31 23 15 7 0
3196 â–ˆS|S|S|H|H|H|P|Pâ–ˆF|E|D|C|B| | |Aâ–ˆ | | | | | | | â–ˆ | | | | | | | â–ˆ
3197
3198 A: wifi multicast was on.
3199 B: battery was plugged in.
3200 C: screen was on.
3201 D: phone was scanning for signal.
3202 E: audio was on.
3203 F: a sensor was active.
3204
3205 State2 change int: if C in the first token is set,
3206 31 23 15 7 0
3207 â–ˆM|L|K|J|I|H|H|Gâ–ˆF|E|D|C| | | | â–ˆ | | | | | | | â–ˆ |B|B|B|A|A|A|Aâ–ˆ
3208
3209 A: 4 bits indicating the wifi supplicant state: {@link BatteryStats#WIFI_SUPPL_STATE_NAMES}.
3210 B: 3 bits indicating the wifi signal strength: 0, 1, 2, 3, 4.
3211 C: a bluetooth scan was active.
3212 D: the camera was active.
3213 E: bluetooth was on.
3214 F: a phone call was active.
3215 G: the device was charging.
3216 H: 2 bits indicating the device-idle (doze) state: off, light, full
3217 I: the flashlight was on.
3218 J: wifi was on.
3219 K: wifi was running.
3220 L: video was playing.
3221 M: power save mode was on.
3222
3223 Wakelock/wakereason struct: if D in the first token is set,
3224 TODO(adamlesinski): describe wakelock/wakereason struct.
3225
3226 Event struct: if E in the first token is set,
3227 TODO(adamlesinski): describe the event struct.
3228
3229 History step details struct: if D in the battery level int is set,
3230 TODO(adamlesinski): describe the history step details struct.
3231
3232 Battery charge int: if F in the first token is set, an int representing the battery charge
3233 in coulombs follows.
3234 */
3235
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003236 // Part of initial delta int that specifies the time delta.
Dianne Hackborne13c4c02014-02-11 17:18:35 -08003237 static final int DELTA_TIME_MASK = 0x7ffff;
3238 static final int DELTA_TIME_LONG = 0x7ffff; // The delta is a following long
3239 static final int DELTA_TIME_INT = 0x7fffe; // The delta is a following int
3240 static final int DELTA_TIME_ABS = 0x7fffd; // Following is an entire abs update.
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003241 // Flag in delta int: a new battery level int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003242 static final int DELTA_BATTERY_LEVEL_FLAG = 0x00080000;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003243 // Flag in delta int: a new full state and battery status int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003244 static final int DELTA_STATE_FLAG = 0x00100000;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08003245 // Flag in delta int: a new full state2 int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003246 static final int DELTA_STATE2_FLAG = 0x00200000;
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003247 // Flag in delta int: contains a wakelock or wakeReason tag.
Adam Lesinski926969b2016-04-28 17:31:12 -07003248 static final int DELTA_WAKELOCK_FLAG = 0x00400000;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003249 // Flag in delta int: contains an event description.
Adam Lesinski926969b2016-04-28 17:31:12 -07003250 static final int DELTA_EVENT_FLAG = 0x00800000;
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003251 // Flag in delta int: contains the battery charge count in uAh.
3252 static final int DELTA_BATTERY_CHARGE_FLAG = 0x01000000;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003253 // These upper bits are the frequently changing state bits.
Adam Lesinski926969b2016-04-28 17:31:12 -07003254 static final int DELTA_STATE_MASK = 0xfe000000;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003255
3256 // These are the pieces of battery state that are packed in to the upper bits of
3257 // the state int that have been packed in to the first delta int. They must fit
Adam Lesinski926969b2016-04-28 17:31:12 -07003258 // in STATE_BATTERY_MASK.
3259 static final int STATE_BATTERY_MASK = 0xff000000;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003260 static final int STATE_BATTERY_STATUS_MASK = 0x00000007;
3261 static final int STATE_BATTERY_STATUS_SHIFT = 29;
3262 static final int STATE_BATTERY_HEALTH_MASK = 0x00000007;
3263 static final int STATE_BATTERY_HEALTH_SHIFT = 26;
3264 static final int STATE_BATTERY_PLUG_MASK = 0x00000003;
3265 static final int STATE_BATTERY_PLUG_SHIFT = 24;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003266
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003267 // We use the low bit of the battery state int to indicate that we have full details
3268 // from a battery level change.
3269 static final int BATTERY_DELTA_LEVEL_FLAG = 0x00000001;
3270
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003271 public void writeHistoryDelta(Parcel dest, HistoryItem cur, HistoryItem last) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003272 if (last == null || cur.cmd != HistoryItem.CMD_UPDATE) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003273 dest.writeInt(DELTA_TIME_ABS);
3274 cur.writeToParcel(dest, 0);
3275 return;
3276 }
3277
3278 final long deltaTime = cur.time - last.time;
3279 final int lastBatteryLevelInt = buildBatteryLevelInt(last);
3280 final int lastStateInt = buildStateInt(last);
3281
3282 int deltaTimeToken;
3283 if (deltaTime < 0 || deltaTime > Integer.MAX_VALUE) {
3284 deltaTimeToken = DELTA_TIME_LONG;
3285 } else if (deltaTime >= DELTA_TIME_ABS) {
3286 deltaTimeToken = DELTA_TIME_INT;
3287 } else {
3288 deltaTimeToken = (int)deltaTime;
3289 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003290 int firstToken = deltaTimeToken | (cur.states&DELTA_STATE_MASK);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003291 final int includeStepDetails = mLastHistoryStepLevel > cur.batteryLevel
3292 ? BATTERY_DELTA_LEVEL_FLAG : 0;
3293 final boolean computeStepDetails = includeStepDetails != 0
3294 || mLastHistoryStepDetails == null;
3295 final int batteryLevelInt = buildBatteryLevelInt(cur) | includeStepDetails;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003296 final boolean batteryLevelIntChanged = batteryLevelInt != lastBatteryLevelInt;
3297 if (batteryLevelIntChanged) {
3298 firstToken |= DELTA_BATTERY_LEVEL_FLAG;
3299 }
3300 final int stateInt = buildStateInt(cur);
3301 final boolean stateIntChanged = stateInt != lastStateInt;
3302 if (stateIntChanged) {
3303 firstToken |= DELTA_STATE_FLAG;
3304 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003305 final boolean state2IntChanged = cur.states2 != last.states2;
3306 if (state2IntChanged) {
3307 firstToken |= DELTA_STATE2_FLAG;
3308 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003309 if (cur.wakelockTag != null || cur.wakeReasonTag != null) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003310 firstToken |= DELTA_WAKELOCK_FLAG;
3311 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003312 if (cur.eventCode != HistoryItem.EVENT_NONE) {
3313 firstToken |= DELTA_EVENT_FLAG;
3314 }
Adam Lesinski926969b2016-04-28 17:31:12 -07003315
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003316 final boolean batteryChargeChanged = cur.batteryChargeUAh != last.batteryChargeUAh;
3317 if (batteryChargeChanged) {
3318 firstToken |= DELTA_BATTERY_CHARGE_FLAG;
Adam Lesinski926969b2016-04-28 17:31:12 -07003319 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003320 dest.writeInt(firstToken);
3321 if (DEBUG) Slog.i(TAG, "WRITE DELTA: firstToken=0x" + Integer.toHexString(firstToken)
3322 + " deltaTime=" + deltaTime);
3323
3324 if (deltaTimeToken >= DELTA_TIME_INT) {
3325 if (deltaTimeToken == DELTA_TIME_INT) {
3326 if (DEBUG) Slog.i(TAG, "WRITE DELTA: int deltaTime=" + (int)deltaTime);
3327 dest.writeInt((int)deltaTime);
3328 } else {
3329 if (DEBUG) Slog.i(TAG, "WRITE DELTA: long deltaTime=" + deltaTime);
3330 dest.writeLong(deltaTime);
3331 }
3332 }
3333 if (batteryLevelIntChanged) {
3334 dest.writeInt(batteryLevelInt);
3335 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryToken=0x"
3336 + Integer.toHexString(batteryLevelInt)
3337 + " batteryLevel=" + cur.batteryLevel
3338 + " batteryTemp=" + cur.batteryTemperature
3339 + " batteryVolt=" + (int)cur.batteryVoltage);
3340 }
3341 if (stateIntChanged) {
3342 dest.writeInt(stateInt);
3343 if (DEBUG) Slog.i(TAG, "WRITE DELTA: stateToken=0x"
3344 + Integer.toHexString(stateInt)
3345 + " batteryStatus=" + cur.batteryStatus
3346 + " batteryHealth=" + cur.batteryHealth
3347 + " batteryPlugType=" + cur.batteryPlugType
3348 + " states=0x" + Integer.toHexString(cur.states));
3349 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003350 if (state2IntChanged) {
3351 dest.writeInt(cur.states2);
3352 if (DEBUG) Slog.i(TAG, "WRITE DELTA: states2=0x"
3353 + Integer.toHexString(cur.states2));
3354 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003355 if (cur.wakelockTag != null || cur.wakeReasonTag != null) {
3356 int wakeLockIndex;
3357 int wakeReasonIndex;
3358 if (cur.wakelockTag != null) {
3359 wakeLockIndex = writeHistoryTag(cur.wakelockTag);
3360 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx
3361 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string);
3362 } else {
3363 wakeLockIndex = 0xffff;
3364 }
3365 if (cur.wakeReasonTag != null) {
3366 wakeReasonIndex = writeHistoryTag(cur.wakeReasonTag);
3367 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx
3368 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string);
3369 } else {
3370 wakeReasonIndex = 0xffff;
3371 }
3372 dest.writeInt((wakeReasonIndex<<16) | wakeLockIndex);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003373 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003374 if (cur.eventCode != HistoryItem.EVENT_NONE) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003375 int index = writeHistoryTag(cur.eventTag);
3376 int codeAndIndex = (cur.eventCode&0xffff) | (index<<16);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003377 dest.writeInt(codeAndIndex);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003378 if (DEBUG) Slog.i(TAG, "WRITE DELTA: event=" + cur.eventCode + " tag=#"
3379 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":"
3380 + cur.eventTag.string);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003381 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003382 if (computeStepDetails) {
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07003383 if (mPlatformIdleStateCallback != null) {
3384 mCurHistoryStepDetails.statPlatformIdleState =
3385 mPlatformIdleStateCallback.getPlatformLowPowerStats();
3386 if (DEBUG) Slog.i(TAG, "WRITE PlatformIdleState:" +
3387 mCurHistoryStepDetails.statPlatformIdleState);
Ahmed ElArabawyd8b44112017-05-23 21:25:02 +00003388
3389 mCurHistoryStepDetails.statSubsystemPowerState =
3390 mPlatformIdleStateCallback.getSubsystemLowPowerStats();
3391 if (DEBUG) Slog.i(TAG, "WRITE SubsystemPowerState:" +
3392 mCurHistoryStepDetails.statSubsystemPowerState);
3393
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07003394 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003395 computeHistoryStepDetails(mCurHistoryStepDetails, mLastHistoryStepDetails);
3396 if (includeStepDetails != 0) {
3397 mCurHistoryStepDetails.writeToParcel(dest);
3398 }
3399 cur.stepDetails = mCurHistoryStepDetails;
3400 mLastHistoryStepDetails = mCurHistoryStepDetails;
3401 } else {
3402 cur.stepDetails = null;
3403 }
3404 if (mLastHistoryStepLevel < cur.batteryLevel) {
3405 mLastHistoryStepDetails = null;
3406 }
3407 mLastHistoryStepLevel = cur.batteryLevel;
Adam Lesinski926969b2016-04-28 17:31:12 -07003408
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003409 if (batteryChargeChanged) {
3410 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryChargeUAh=" + cur.batteryChargeUAh);
3411 dest.writeInt(cur.batteryChargeUAh);
Adam Lesinski926969b2016-04-28 17:31:12 -07003412 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003413 }
3414
3415 private int buildBatteryLevelInt(HistoryItem h) {
3416 return ((((int)h.batteryLevel)<<25)&0xfe000000)
Adam Lesinski3944c812015-11-13 15:54:59 -08003417 | ((((int)h.batteryTemperature)<<15)&0x01ff8000)
3418 | ((((int)h.batteryVoltage)<<1)&0x00007ffe);
3419 }
3420
3421 private void readBatteryLevelInt(int batteryLevelInt, HistoryItem out) {
3422 out.batteryLevel = (byte)((batteryLevelInt & 0xfe000000) >>> 25);
3423 out.batteryTemperature = (short)((batteryLevelInt & 0x01ff8000) >>> 15);
3424 out.batteryVoltage = (char)((batteryLevelInt & 0x00007ffe) >>> 1);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003425 }
3426
3427 private int buildStateInt(HistoryItem h) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003428 int plugType = 0;
3429 if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_AC) != 0) {
3430 plugType = 1;
3431 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_USB) != 0) {
3432 plugType = 2;
3433 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_WIRELESS) != 0) {
3434 plugType = 3;
3435 }
3436 return ((h.batteryStatus&STATE_BATTERY_STATUS_MASK)<<STATE_BATTERY_STATUS_SHIFT)
3437 | ((h.batteryHealth&STATE_BATTERY_HEALTH_MASK)<<STATE_BATTERY_HEALTH_SHIFT)
3438 | ((plugType&STATE_BATTERY_PLUG_MASK)<<STATE_BATTERY_PLUG_SHIFT)
Adam Lesinski926969b2016-04-28 17:31:12 -07003439 | (h.states&(~STATE_BATTERY_MASK));
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003440 }
3441
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003442 private void computeHistoryStepDetails(final HistoryStepDetails out,
3443 final HistoryStepDetails last) {
3444 final HistoryStepDetails tmp = last != null ? mTmpHistoryStepDetails : out;
3445
3446 // Perform a CPU update right after we do this collection, so we have started
3447 // collecting good data for the next step.
3448 requestImmediateCpuUpdate();
3449
3450 if (last == null) {
3451 // We are not generating a delta, so all we need to do is reset the stats
3452 // we will later be doing a delta from.
3453 final int NU = mUidStats.size();
3454 for (int i=0; i<NU; i++) {
3455 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
3456 uid.mLastStepUserTime = uid.mCurStepUserTime;
3457 uid.mLastStepSystemTime = uid.mCurStepSystemTime;
3458 }
3459 mLastStepCpuUserTime = mCurStepCpuUserTime;
3460 mLastStepCpuSystemTime = mCurStepCpuSystemTime;
3461 mLastStepStatUserTime = mCurStepStatUserTime;
3462 mLastStepStatSystemTime = mCurStepStatSystemTime;
3463 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime;
3464 mLastStepStatIrqTime = mCurStepStatIrqTime;
3465 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime;
3466 mLastStepStatIdleTime = mCurStepStatIdleTime;
3467 tmp.clear();
3468 return;
3469 }
3470 if (DEBUG) {
3471 Slog.d(TAG, "Step stats last: user=" + mLastStepCpuUserTime + " sys="
3472 + mLastStepStatSystemTime + " io=" + mLastStepStatIOWaitTime
3473 + " irq=" + mLastStepStatIrqTime + " sirq="
3474 + mLastStepStatSoftIrqTime + " idle=" + mLastStepStatIdleTime);
3475 Slog.d(TAG, "Step stats cur: user=" + mCurStepCpuUserTime + " sys="
3476 + mCurStepStatSystemTime + " io=" + mCurStepStatIOWaitTime
3477 + " irq=" + mCurStepStatIrqTime + " sirq="
3478 + mCurStepStatSoftIrqTime + " idle=" + mCurStepStatIdleTime);
3479 }
3480 out.userTime = (int)(mCurStepCpuUserTime - mLastStepCpuUserTime);
3481 out.systemTime = (int)(mCurStepCpuSystemTime - mLastStepCpuSystemTime);
3482 out.statUserTime = (int)(mCurStepStatUserTime - mLastStepStatUserTime);
3483 out.statSystemTime = (int)(mCurStepStatSystemTime - mLastStepStatSystemTime);
3484 out.statIOWaitTime = (int)(mCurStepStatIOWaitTime - mLastStepStatIOWaitTime);
3485 out.statIrqTime = (int)(mCurStepStatIrqTime - mLastStepStatIrqTime);
3486 out.statSoftIrqTime = (int)(mCurStepStatSoftIrqTime - mLastStepStatSoftIrqTime);
3487 out.statIdlTime = (int)(mCurStepStatIdleTime - mLastStepStatIdleTime);
3488 out.appCpuUid1 = out.appCpuUid2 = out.appCpuUid3 = -1;
3489 out.appCpuUTime1 = out.appCpuUTime2 = out.appCpuUTime3 = 0;
3490 out.appCpuSTime1 = out.appCpuSTime2 = out.appCpuSTime3 = 0;
3491 final int NU = mUidStats.size();
3492 for (int i=0; i<NU; i++) {
3493 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
3494 final int totalUTime = (int)(uid.mCurStepUserTime - uid.mLastStepUserTime);
3495 final int totalSTime = (int)(uid.mCurStepSystemTime - uid.mLastStepSystemTime);
3496 final int totalTime = totalUTime + totalSTime;
3497 uid.mLastStepUserTime = uid.mCurStepUserTime;
3498 uid.mLastStepSystemTime = uid.mCurStepSystemTime;
3499 if (totalTime <= (out.appCpuUTime3+out.appCpuSTime3)) {
3500 continue;
3501 }
3502 if (totalTime <= (out.appCpuUTime2+out.appCpuSTime2)) {
3503 out.appCpuUid3 = uid.mUid;
3504 out.appCpuUTime3 = totalUTime;
3505 out.appCpuSTime3 = totalSTime;
3506 } else {
3507 out.appCpuUid3 = out.appCpuUid2;
3508 out.appCpuUTime3 = out.appCpuUTime2;
3509 out.appCpuSTime3 = out.appCpuSTime2;
3510 if (totalTime <= (out.appCpuUTime1+out.appCpuSTime1)) {
3511 out.appCpuUid2 = uid.mUid;
3512 out.appCpuUTime2 = totalUTime;
3513 out.appCpuSTime2 = totalSTime;
3514 } else {
3515 out.appCpuUid2 = out.appCpuUid1;
3516 out.appCpuUTime2 = out.appCpuUTime1;
3517 out.appCpuSTime2 = out.appCpuSTime1;
3518 out.appCpuUid1 = uid.mUid;
3519 out.appCpuUTime1 = totalUTime;
3520 out.appCpuSTime1 = totalSTime;
3521 }
3522 }
3523 }
3524 mLastStepCpuUserTime = mCurStepCpuUserTime;
3525 mLastStepCpuSystemTime = mCurStepCpuSystemTime;
3526 mLastStepStatUserTime = mCurStepStatUserTime;
3527 mLastStepStatSystemTime = mCurStepStatSystemTime;
3528 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime;
3529 mLastStepStatIrqTime = mCurStepStatIrqTime;
3530 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime;
3531 mLastStepStatIdleTime = mCurStepStatIdleTime;
3532 }
3533
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003534 public void readHistoryDelta(Parcel src, HistoryItem cur) {
3535 int firstToken = src.readInt();
3536 int deltaTimeToken = firstToken&DELTA_TIME_MASK;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003537 cur.cmd = HistoryItem.CMD_UPDATE;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003538 cur.numReadInts = 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003539 if (DEBUG) Slog.i(TAG, "READ DELTA: firstToken=0x" + Integer.toHexString(firstToken)
3540 + " deltaTimeToken=" + deltaTimeToken);
3541
3542 if (deltaTimeToken < DELTA_TIME_ABS) {
3543 cur.time += deltaTimeToken;
3544 } else if (deltaTimeToken == DELTA_TIME_ABS) {
3545 cur.time = src.readLong();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003546 cur.numReadInts += 2;
3547 if (DEBUG) Slog.i(TAG, "READ DELTA: ABS time=" + cur.time);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003548 cur.readFromParcel(src);
3549 return;
3550 } else if (deltaTimeToken == DELTA_TIME_INT) {
3551 int delta = src.readInt();
3552 cur.time += delta;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003553 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003554 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time);
3555 } else {
3556 long delta = src.readLong();
3557 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time);
3558 cur.time += delta;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003559 cur.numReadInts += 2;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003560 }
3561
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003562 final int batteryLevelInt;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003563 if ((firstToken&DELTA_BATTERY_LEVEL_FLAG) != 0) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003564 batteryLevelInt = src.readInt();
Adam Lesinski3944c812015-11-13 15:54:59 -08003565 readBatteryLevelInt(batteryLevelInt, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003566 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003567 if (DEBUG) Slog.i(TAG, "READ DELTA: batteryToken=0x"
3568 + Integer.toHexString(batteryLevelInt)
3569 + " batteryLevel=" + cur.batteryLevel
3570 + " batteryTemp=" + cur.batteryTemperature
3571 + " batteryVolt=" + (int)cur.batteryVoltage);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003572 } else {
3573 batteryLevelInt = 0;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003574 }
3575
3576 if ((firstToken&DELTA_STATE_FLAG) != 0) {
3577 int stateInt = src.readInt();
Adam Lesinski926969b2016-04-28 17:31:12 -07003578 cur.states = (firstToken&DELTA_STATE_MASK) | (stateInt&(~STATE_BATTERY_MASK));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003579 cur.batteryStatus = (byte)((stateInt>>STATE_BATTERY_STATUS_SHIFT)
3580 & STATE_BATTERY_STATUS_MASK);
3581 cur.batteryHealth = (byte)((stateInt>>STATE_BATTERY_HEALTH_SHIFT)
3582 & STATE_BATTERY_HEALTH_MASK);
3583 cur.batteryPlugType = (byte)((stateInt>>STATE_BATTERY_PLUG_SHIFT)
3584 & STATE_BATTERY_PLUG_MASK);
3585 switch (cur.batteryPlugType) {
3586 case 1:
3587 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_AC;
3588 break;
3589 case 2:
3590 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_USB;
3591 break;
3592 case 3:
3593 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_WIRELESS;
3594 break;
3595 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003596 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003597 if (DEBUG) Slog.i(TAG, "READ DELTA: stateToken=0x"
3598 + Integer.toHexString(stateInt)
3599 + " batteryStatus=" + cur.batteryStatus
3600 + " batteryHealth=" + cur.batteryHealth
3601 + " batteryPlugType=" + cur.batteryPlugType
3602 + " states=0x" + Integer.toHexString(cur.states));
3603 } else {
Adam Lesinski926969b2016-04-28 17:31:12 -07003604 cur.states = (firstToken&DELTA_STATE_MASK) | (cur.states&(~STATE_BATTERY_MASK));
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003605 }
3606
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003607 if ((firstToken&DELTA_STATE2_FLAG) != 0) {
3608 cur.states2 = src.readInt();
3609 if (DEBUG) Slog.i(TAG, "READ DELTA: states2=0x"
3610 + Integer.toHexString(cur.states2));
3611 }
3612
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003613 if ((firstToken&DELTA_WAKELOCK_FLAG) != 0) {
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003614 int indexes = src.readInt();
3615 int wakeLockIndex = indexes&0xffff;
3616 int wakeReasonIndex = (indexes>>16)&0xffff;
3617 if (wakeLockIndex != 0xffff) {
3618 cur.wakelockTag = cur.localWakelockTag;
3619 readHistoryTag(wakeLockIndex, cur.wakelockTag);
3620 if (DEBUG) Slog.i(TAG, "READ DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx
3621 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string);
3622 } else {
3623 cur.wakelockTag = null;
3624 }
3625 if (wakeReasonIndex != 0xffff) {
3626 cur.wakeReasonTag = cur.localWakeReasonTag;
3627 readHistoryTag(wakeReasonIndex, cur.wakeReasonTag);
3628 if (DEBUG) Slog.i(TAG, "READ DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx
3629 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string);
3630 } else {
3631 cur.wakeReasonTag = null;
3632 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003633 cur.numReadInts += 1;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003634 } else {
3635 cur.wakelockTag = null;
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003636 cur.wakeReasonTag = null;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003637 }
3638
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003639 if ((firstToken&DELTA_EVENT_FLAG) != 0) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003640 cur.eventTag = cur.localEventTag;
3641 final int codeAndIndex = src.readInt();
Dianne Hackborn099bc622014-01-22 13:39:16 -08003642 cur.eventCode = (codeAndIndex&0xffff);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003643 final int index = ((codeAndIndex>>16)&0xffff);
3644 readHistoryTag(index, cur.eventTag);
3645 cur.numReadInts += 1;
3646 if (DEBUG) Slog.i(TAG, "READ DELTA: event=" + cur.eventCode + " tag=#"
3647 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":"
3648 + cur.eventTag.string);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003649 } else {
3650 cur.eventCode = HistoryItem.EVENT_NONE;
3651 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003652
3653 if ((batteryLevelInt&BATTERY_DELTA_LEVEL_FLAG) != 0) {
3654 cur.stepDetails = mReadHistoryStepDetails;
3655 cur.stepDetails.readFromParcel(src);
3656 } else {
3657 cur.stepDetails = null;
3658 }
Adam Lesinski926969b2016-04-28 17:31:12 -07003659
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003660 if ((firstToken&DELTA_BATTERY_CHARGE_FLAG) != 0) {
3661 cur.batteryChargeUAh = src.readInt();
Adam Lesinski926969b2016-04-28 17:31:12 -07003662 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003663 }
3664
Dianne Hackbornfc064132014-06-02 12:42:12 -07003665 @Override
3666 public void commitCurrentHistoryBatchLocked() {
3667 mHistoryLastWritten.cmd = HistoryItem.CMD_NULL;
3668 }
3669
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003670 void addHistoryBufferLocked(long elapsedRealtimeMs, HistoryItem cur) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003671 if (!mHaveBatteryLevel || !mRecordingHistory) {
3672 return;
3673 }
3674
Dianne Hackborn40c87252014-03-19 16:55:40 -07003675 final long timeDiff = (mHistoryBaseTime+elapsedRealtimeMs) - mHistoryLastWritten.time;
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003676 final int diffStates = mHistoryLastWritten.states^(cur.states&mActiveHistoryStates);
3677 final int diffStates2 = mHistoryLastWritten.states2^(cur.states2&mActiveHistoryStates2);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003678 final int lastDiffStates = mHistoryLastWritten.states^mHistoryLastLastWritten.states;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003679 final int lastDiffStates2 = mHistoryLastWritten.states2^mHistoryLastLastWritten.states2;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003680 if (DEBUG) Slog.i(TAG, "ADD: tdelta=" + timeDiff + " diff="
3681 + Integer.toHexString(diffStates) + " lastDiff="
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003682 + Integer.toHexString(lastDiffStates) + " diff2="
3683 + Integer.toHexString(diffStates2) + " lastDiff2="
3684 + Integer.toHexString(lastDiffStates2));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003685 if (mHistoryBufferLastPos >= 0 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003686 && timeDiff < 1000 && (diffStates&lastDiffStates) == 0
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003687 && (diffStates2&lastDiffStates2) == 0
3688 && (mHistoryLastWritten.wakelockTag == null || cur.wakelockTag == null)
3689 && (mHistoryLastWritten.wakeReasonTag == null || cur.wakeReasonTag == null)
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003690 && mHistoryLastWritten.stepDetails == null
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003691 && (mHistoryLastWritten.eventCode == HistoryItem.EVENT_NONE
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003692 || cur.eventCode == HistoryItem.EVENT_NONE)
3693 && mHistoryLastWritten.batteryLevel == cur.batteryLevel
3694 && mHistoryLastWritten.batteryStatus == cur.batteryStatus
3695 && mHistoryLastWritten.batteryHealth == cur.batteryHealth
3696 && mHistoryLastWritten.batteryPlugType == cur.batteryPlugType
3697 && mHistoryLastWritten.batteryTemperature == cur.batteryTemperature
3698 && mHistoryLastWritten.batteryVoltage == cur.batteryVoltage) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003699 // We can merge this new change in with the last one. Merging is
Dianne Hackborn40c87252014-03-19 16:55:40 -07003700 // allowed as long as only the states have changed, and within those states
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003701 // as long as no bit has changed both between now and the last entry, as
3702 // well as the last entry and the one before it (so we capture any toggles).
3703 if (DEBUG) Slog.i(TAG, "ADD: rewinding back to " + mHistoryBufferLastPos);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003704 mHistoryBuffer.setDataSize(mHistoryBufferLastPos);
3705 mHistoryBuffer.setDataPosition(mHistoryBufferLastPos);
3706 mHistoryBufferLastPos = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003707 elapsedRealtimeMs = mHistoryLastWritten.time - mHistoryBaseTime;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003708 // If the last written history had a wakelock tag, we need to retain it.
3709 // Note that the condition above made sure that we aren't in a case where
3710 // both it and the current history item have a wakelock tag.
3711 if (mHistoryLastWritten.wakelockTag != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003712 cur.wakelockTag = cur.localWakelockTag;
3713 cur.wakelockTag.setTo(mHistoryLastWritten.wakelockTag);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003714 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003715 // If the last written history had a wake reason tag, we need to retain it.
3716 // Note that the condition above made sure that we aren't in a case where
3717 // both it and the current history item have a wakelock tag.
3718 if (mHistoryLastWritten.wakeReasonTag != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003719 cur.wakeReasonTag = cur.localWakeReasonTag;
3720 cur.wakeReasonTag.setTo(mHistoryLastWritten.wakeReasonTag);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003721 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003722 // If the last written history had an event, we need to retain it.
3723 // Note that the condition above made sure that we aren't in a case where
3724 // both it and the current history item have an event.
3725 if (mHistoryLastWritten.eventCode != HistoryItem.EVENT_NONE) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003726 cur.eventCode = mHistoryLastWritten.eventCode;
3727 cur.eventTag = cur.localEventTag;
3728 cur.eventTag.setTo(mHistoryLastWritten.eventTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003729 }
Dianne Hackborn1fadab52011-04-14 17:57:33 -07003730 mHistoryLastWritten.setTo(mHistoryLastLastWritten);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003731 }
3732
Adam Lesinski45489782016-12-15 23:45:17 -08003733 boolean recordResetDueToOverflow = false;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003734 final int dataSize = mHistoryBuffer.dataSize();
Adam Lesinski45489782016-12-15 23:45:17 -08003735 if (dataSize >= MAX_MAX_HISTORY_BUFFER*3) {
3736 // Clients can't deal with history buffers this large. This only
3737 // really happens when the device is on charger and interacted with
3738 // for long periods of time, like in retail mode. Since the device is
3739 // most likely charged, when unplugged, stats would have reset anyways.
3740 // Reset the stats and mark that we overflowed.
3741 // b/32540341
3742 resetAllStatsLocked();
3743
3744 // Mark that we want to set *OVERFLOW* event and the RESET:START
3745 // events.
3746 recordResetDueToOverflow = true;
3747
3748 } else if (dataSize >= MAX_HISTORY_BUFFER) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003749 if (!mHistoryOverflow) {
3750 mHistoryOverflow = true;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003751 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, cur);
3752 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_OVERFLOW, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003753 return;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003754 }
3755
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003756 // After overflow, we allow various bit-wise states to settle to 0.
3757 boolean writeAnyway = false;
3758 final int curStates = cur.states & HistoryItem.SETTLE_TO_ZERO_STATES
3759 & mActiveHistoryStates;
3760 if (mHistoryLastWritten.states != curStates) {
3761 // mActiveHistoryStates keeps track of which bits in .states are now being
3762 // forced to 0.
3763 int old = mActiveHistoryStates;
3764 mActiveHistoryStates &= curStates | ~HistoryItem.SETTLE_TO_ZERO_STATES;
3765 writeAnyway |= old != mActiveHistoryStates;
3766 }
3767 final int curStates2 = cur.states2 & HistoryItem.SETTLE_TO_ZERO_STATES2
3768 & mActiveHistoryStates2;
3769 if (mHistoryLastWritten.states2 != curStates2) {
3770 // mActiveHistoryStates2 keeps track of which bits in .states2 are now being
3771 // forced to 0.
3772 int old = mActiveHistoryStates2;
3773 mActiveHistoryStates2 &= curStates2 | ~HistoryItem.SETTLE_TO_ZERO_STATES2;
3774 writeAnyway |= old != mActiveHistoryStates2;
3775 }
3776
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003777 // Once we've reached the maximum number of items, we only
3778 // record changes to the battery level and the most interesting states.
3779 // Once we've reached the maximum maximum number of items, we only
3780 // record changes to the battery level.
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003781 if (!writeAnyway && mHistoryLastWritten.batteryLevel == cur.batteryLevel &&
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003782 (dataSize >= MAX_MAX_HISTORY_BUFFER
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003783 || ((mHistoryLastWritten.states^cur.states)
Dianne Hackborn3251b902014-06-20 14:40:53 -07003784 & HistoryItem.MOST_INTERESTING_STATES) == 0
3785 || ((mHistoryLastWritten.states2^cur.states2)
3786 & HistoryItem.MOST_INTERESTING_STATES2) == 0)) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003787 return;
3788 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003789
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003790 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003791 return;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003792 }
3793
Adam Lesinski45489782016-12-15 23:45:17 -08003794 if (dataSize == 0 || recordResetDueToOverflow) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003795 // The history is currently empty; we need it to start with a time stamp.
3796 cur.currentTime = System.currentTimeMillis();
Adam Lesinski45489782016-12-15 23:45:17 -08003797 if (recordResetDueToOverflow) {
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003798 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_OVERFLOW, cur);
Adam Lesinski45489782016-12-15 23:45:17 -08003799 }
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003800 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_RESET, cur);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003801 }
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003802 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003803 }
3804
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003805 private void addHistoryBufferLocked(long elapsedRealtimeMs, byte cmd, HistoryItem cur) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003806 if (mIteratingHistory) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003807 throw new IllegalStateException("Can't do this while iterating history!");
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003808 }
3809 mHistoryBufferLastPos = mHistoryBuffer.dataPosition();
3810 mHistoryLastLastWritten.setTo(mHistoryLastWritten);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003811 mHistoryLastWritten.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003812 mHistoryLastWritten.states &= mActiveHistoryStates;
3813 mHistoryLastWritten.states2 &= mActiveHistoryStates2;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003814 writeHistoryDelta(mHistoryBuffer, mHistoryLastWritten, mHistoryLastLastWritten);
Dianne Hackborn40c87252014-03-19 16:55:40 -07003815 mLastHistoryElapsedRealtime = elapsedRealtimeMs;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003816 cur.wakelockTag = null;
3817 cur.wakeReasonTag = null;
3818 cur.eventCode = HistoryItem.EVENT_NONE;
3819 cur.eventTag = null;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003820 if (DEBUG_HISTORY) Slog.i(TAG, "Writing history buffer: was " + mHistoryBufferLastPos
3821 + " now " + mHistoryBuffer.dataPosition()
3822 + " size is now " + mHistoryBuffer.dataSize());
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003823 }
3824
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003825 int mChangedStates = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003826 int mChangedStates2 = 0;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003827
Dianne Hackborn40c87252014-03-19 16:55:40 -07003828 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003829 if (mTrackRunningHistoryElapsedRealtime != 0) {
3830 final long diffElapsed = elapsedRealtimeMs - mTrackRunningHistoryElapsedRealtime;
3831 final long diffUptime = uptimeMs - mTrackRunningHistoryUptime;
3832 if (diffUptime < (diffElapsed-20)) {
3833 final long wakeElapsedTime = elapsedRealtimeMs - (diffElapsed - diffUptime);
3834 mHistoryAddTmp.setTo(mHistoryLastWritten);
3835 mHistoryAddTmp.wakelockTag = null;
3836 mHistoryAddTmp.wakeReasonTag = null;
3837 mHistoryAddTmp.eventCode = HistoryItem.EVENT_NONE;
3838 mHistoryAddTmp.states &= ~HistoryItem.STATE_CPU_RUNNING_FLAG;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003839 addHistoryRecordInnerLocked(wakeElapsedTime, mHistoryAddTmp);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003840 }
3841 }
3842 mHistoryCur.states |= HistoryItem.STATE_CPU_RUNNING_FLAG;
3843 mTrackRunningHistoryElapsedRealtime = elapsedRealtimeMs;
3844 mTrackRunningHistoryUptime = uptimeMs;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003845 addHistoryRecordInnerLocked(elapsedRealtimeMs, mHistoryCur);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003846 }
3847
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003848 void addHistoryRecordInnerLocked(long elapsedRealtimeMs, HistoryItem cur) {
3849 addHistoryBufferLocked(elapsedRealtimeMs, cur);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003850
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003851 if (!USE_OLD_HISTORY) {
3852 return;
3853 }
3854
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003855 if (!mHaveBatteryLevel || !mRecordingHistory) {
3856 return;
3857 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003858
3859 // If the current time is basically the same as the last time,
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003860 // and no states have since the last recorded entry changed and
3861 // are now resetting back to their original value, then just collapse
3862 // into one record.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003863 if (mHistoryEnd != null && mHistoryEnd.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn40c87252014-03-19 16:55:40 -07003864 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+1000)
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003865 && ((mHistoryEnd.states^cur.states)&mChangedStates&mActiveHistoryStates) == 0
3866 && ((mHistoryEnd.states2^cur.states2)&mChangedStates2&mActiveHistoryStates2) == 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003867 // If the current is the same as the one before, then we no
3868 // longer need the entry.
3869 if (mHistoryLastEnd != null && mHistoryLastEnd.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn40c87252014-03-19 16:55:40 -07003870 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+500)
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003871 && mHistoryLastEnd.sameNonEvent(cur)) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003872 mHistoryLastEnd.next = null;
3873 mHistoryEnd.next = mHistoryCache;
3874 mHistoryCache = mHistoryEnd;
3875 mHistoryEnd = mHistoryLastEnd;
3876 mHistoryLastEnd = null;
3877 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003878 mChangedStates |= mHistoryEnd.states^(cur.states&mActiveHistoryStates);
3879 mChangedStates2 |= mHistoryEnd.states^(cur.states2&mActiveHistoryStates2);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003880 mHistoryEnd.setTo(mHistoryEnd.time, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003881 }
3882 return;
3883 }
3884
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003885 mChangedStates = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003886 mChangedStates2 = 0;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003887
3888 if (mNumHistoryItems == MAX_HISTORY_ITEMS
3889 || mNumHistoryItems == MAX_MAX_HISTORY_ITEMS) {
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003890 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_OVERFLOW, cur);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07003891 }
3892
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003893 if (mNumHistoryItems >= MAX_HISTORY_ITEMS) {
3894 // Once we've reached the maximum number of items, we only
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003895 // record changes to the battery level and the most interesting states.
3896 // Once we've reached the maximum maximum number of items, we only
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003897 // record changes to the battery level.
3898 if (mHistoryEnd != null && mHistoryEnd.batteryLevel
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003899 == cur.batteryLevel &&
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003900 (mNumHistoryItems >= MAX_MAX_HISTORY_ITEMS
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003901 || ((mHistoryEnd.states^(cur.states&mActiveHistoryStates))
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003902 & HistoryItem.MOST_INTERESTING_STATES) == 0)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003903 return;
3904 }
3905 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003906
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003907 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003908 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003909
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003910 public void addHistoryEventLocked(long elapsedRealtimeMs, long uptimeMs, int code,
Dianne Hackborn40c87252014-03-19 16:55:40 -07003911 String name, int uid) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003912 mHistoryCur.eventCode = code;
3913 mHistoryCur.eventTag = mHistoryCur.localEventTag;
3914 mHistoryCur.eventTag.string = name;
3915 mHistoryCur.eventTag.uid = uid;
Dianne Hackborn4590e522014-03-24 13:36:46 -07003916 addHistoryRecordLocked(elapsedRealtimeMs, uptimeMs);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003917 }
3918
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003919 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs, byte cmd, HistoryItem cur) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003920 HistoryItem rec = mHistoryCache;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003921 if (rec != null) {
3922 mHistoryCache = rec.next;
3923 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003924 rec = new HistoryItem();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003925 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003926 rec.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003927
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003928 addHistoryRecordLocked(rec);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003929 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003930
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003931 void addHistoryRecordLocked(HistoryItem rec) {
3932 mNumHistoryItems++;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003933 rec.next = null;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003934 mHistoryLastEnd = mHistoryEnd;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003935 if (mHistoryEnd != null) {
3936 mHistoryEnd.next = rec;
3937 mHistoryEnd = rec;
3938 } else {
3939 mHistory = mHistoryEnd = rec;
3940 }
3941 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003942
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003943 void clearHistoryLocked() {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003944 if (DEBUG_HISTORY) Slog.i(TAG, "********** CLEARING HISTORY!");
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003945 if (USE_OLD_HISTORY) {
3946 if (mHistory != null) {
3947 mHistoryEnd.next = mHistoryCache;
3948 mHistoryCache = mHistory;
3949 mHistory = mHistoryLastEnd = mHistoryEnd = null;
3950 }
3951 mNumHistoryItems = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003952 }
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003953
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003954 mHistoryBaseTime = 0;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003955 mLastHistoryElapsedRealtime = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003956 mTrackRunningHistoryElapsedRealtime = 0;
3957 mTrackRunningHistoryUptime = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003958
3959 mHistoryBuffer.setDataSize(0);
3960 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003961 mHistoryBuffer.setDataCapacity(MAX_HISTORY_BUFFER / 2);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003962 mHistoryLastLastWritten.clear();
3963 mHistoryLastWritten.clear();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003964 mHistoryTagPool.clear();
3965 mNextHistoryTagIdx = 0;
3966 mNumHistoryTagChars = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003967 mHistoryBufferLastPos = -1;
3968 mHistoryOverflow = false;
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003969 mActiveHistoryStates = 0xffffffff;
3970 mActiveHistoryStates2 = 0xffffffff;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003971 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003972
Andreas Gampe3f24e692018-02-05 13:24:28 -08003973 @GuardedBy("this")
Mike Mac2f518a2017-09-19 16:06:03 -07003974 public void updateTimeBasesLocked(boolean unplugged, int screenState, long uptime,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003975 long realtime) {
Mike Maa7724752017-10-10 15:29:25 -07003976 final boolean screenOff = !isScreenOn(screenState);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003977 final boolean updateOnBatteryTimeBase = unplugged != mOnBatteryTimeBase.isRunning();
3978 final boolean updateOnBatteryScreenOffTimeBase =
3979 (unplugged && screenOff) != mOnBatteryScreenOffTimeBase.isRunning();
Bookatz867c0d72017-03-07 18:23:42 -08003980
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003981 if (updateOnBatteryScreenOffTimeBase || updateOnBatteryTimeBase) {
3982 if (updateOnBatteryScreenOffTimeBase) {
3983 updateKernelWakelocksLocked();
3984 updateBatteryPropertiesLocked();
Bookatz867c0d72017-03-07 18:23:42 -08003985 }
Bookatz82b341172017-09-07 19:06:08 -07003986 // This if{} is only necessary due to SCREEN_OFF_RPM_STATS_ENABLED, which exists because
3987 // updateRpmStatsLocked is too slow to run each screen change. When the speed is
3988 // improved, remove the surrounding if{}.
3989 if (SCREEN_OFF_RPM_STATS_ENABLED || updateOnBatteryTimeBase) {
3990 updateRpmStatsLocked(); // if either OnBattery or OnBatteryScreenOff timebase changes.
3991 }
Adam Lesinski72478f02015-06-17 15:39:43 -07003992 if (DEBUG_ENERGY_CPU) {
Mike Mac2f518a2017-09-19 16:06:03 -07003993 Slog.d(TAG, "Updating cpu time because screen is now "
3994 + Display.stateToString(screenState)
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003995 + " and battery is " + (unplugged ? "on" : "off"));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003996 }
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003997
3998 mOnBatteryTimeBase.setRunning(unplugged, uptime, realtime);
Mike Mac2f518a2017-09-19 16:06:03 -07003999 if (updateOnBatteryTimeBase) {
4000 for (int i = mUidStats.size() - 1; i >= 0; --i) {
4001 mUidStats.valueAt(i).updateOnBatteryBgTimeBase(uptime, realtime);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07004002 }
Mike Mac2f518a2017-09-19 16:06:03 -07004003 }
4004 if (updateOnBatteryScreenOffTimeBase) {
4005 mOnBatteryScreenOffTimeBase.setRunning(unplugged && screenOff, uptime, realtime);
4006 for (int i = mUidStats.size() - 1; i >= 0; --i) {
4007 mUidStats.valueAt(i).updateOnBatteryScreenOffBgTimeBase(uptime, realtime);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07004008 }
Bookatzc8c44962017-05-11 12:12:54 -07004009 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004010 }
4011 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07004012
Adam Lesinskie1f480d2017-02-15 18:51:23 -08004013 private void updateBatteryPropertiesLocked() {
4014 try {
4015 IBatteryPropertiesRegistrar registrar = IBatteryPropertiesRegistrar.Stub.asInterface(
4016 ServiceManager.getService("batteryproperties"));
4017 registrar.scheduleUpdate();
4018 } catch (RemoteException e) {
4019 // Ignore.
4020 }
4021 }
4022
Dianne Hackborn099bc622014-01-22 13:39:16 -08004023 public void addIsolatedUidLocked(int isolatedUid, int appUid) {
4024 mIsolatedUids.put(isolatedUid, appUid);
Bookatz90867622018-01-31 15:05:57 -08004025 StatsLog.write(StatsLog.ISOLATED_UID_CHANGED, appUid, isolatedUid,
4026 StatsLog.ISOLATED_UID_CHANGED__EVENT__CREATED);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08004027 final Uid u = getUidStatsLocked(appUid);
4028 u.addIsolatedUid(isolatedUid);
Dianne Hackborn099bc622014-01-22 13:39:16 -08004029 }
4030
Adam Lesinski61db88f2015-07-01 15:05:07 -07004031 /**
4032 * Schedules a read of the latest cpu times before removing the isolated UID.
4033 * @see #removeIsolatedUidLocked(int)
4034 */
4035 public void scheduleRemoveIsolatedUidLocked(int isolatedUid, int appUid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004036 int curUid = mIsolatedUids.get(isolatedUid, -1);
4037 if (curUid == appUid) {
Adam Lesinski61db88f2015-07-01 15:05:07 -07004038 if (mExternalSync != null) {
4039 mExternalSync.scheduleCpuSyncDueToRemovedUid(isolatedUid);
4040 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08004041 }
4042 }
4043
Adam Lesinski61db88f2015-07-01 15:05:07 -07004044 /**
4045 * This should only be called after the cpu times have been read.
4046 * @see #scheduleRemoveIsolatedUidLocked(int, int)
4047 */
Andreas Gampe3f24e692018-02-05 13:24:28 -08004048 @GuardedBy("this")
Adam Lesinski61db88f2015-07-01 15:05:07 -07004049 public void removeIsolatedUidLocked(int isolatedUid) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08004050 StatsLog.write(
Bookatz90867622018-01-31 15:05:57 -08004051 StatsLog.ISOLATED_UID_CHANGED, mIsolatedUids.get(isolatedUid, -1),
4052 isolatedUid, StatsLog.ISOLATED_UID_CHANGED__EVENT__REMOVED);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08004053 final int idx = mIsolatedUids.indexOfKey(isolatedUid);
4054 if (idx >= 0) {
4055 final int ownerUid = mIsolatedUids.valueAt(idx);
4056 final Uid u = getUidStatsLocked(ownerUid);
4057 u.removeIsolatedUid(isolatedUid);
4058 mIsolatedUids.removeAt(idx);
4059 }
Mike Ma234d1822018-03-13 18:53:21 -07004060 mPendingRemovedUids.add(new UidToRemove(isolatedUid, mClocks.elapsedRealtime()));
Adam Lesinski61db88f2015-07-01 15:05:07 -07004061 }
4062
Dianne Hackborn099bc622014-01-22 13:39:16 -08004063 public int mapUid(int uid) {
4064 int isolated = mIsolatedUids.get(uid, -1);
4065 return isolated > 0 ? isolated : uid;
4066 }
4067
4068 public void noteEventLocked(int code, String name, int uid) {
4069 uid = mapUid(uid);
Dianne Hackborn37de0982014-05-09 09:32:18 -07004070 if (!mActiveEvents.updateState(code, name, uid, 0)) {
4071 return;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08004072 }
Joe Onoratoabded112016-02-08 16:49:39 -08004073 final long elapsedRealtime = mClocks.elapsedRealtime();
4074 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -07004075 addHistoryEventLocked(elapsedRealtime, uptime, code, name, uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -08004076 }
4077
Dianne Hackbornd48954f2015-07-22 17:20:33 -07004078 boolean ensureStartClockTime(final long currentTime) {
4079 final long ABOUT_ONE_YEAR = 365*24*60*60*1000L;
4080 if (currentTime > ABOUT_ONE_YEAR && mStartClockTime < (currentTime-ABOUT_ONE_YEAR)) {
4081 // If the start clock time has changed by more than a year, then presumably
4082 // the previous time was completely bogus. So we are going to figure out a
4083 // new time based on how much time has elapsed since we started counting.
Joe Onoratoabded112016-02-08 16:49:39 -08004084 mStartClockTime = currentTime - (mClocks.elapsedRealtime()-(mRealtimeStart/1000));
Dianne Hackbornd48954f2015-07-22 17:20:33 -07004085 return true;
4086 }
4087 return false;
4088 }
4089
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07004090 public void noteCurrentTimeChangedLocked() {
4091 final long currentTime = System.currentTimeMillis();
Joe Onoratoabded112016-02-08 16:49:39 -08004092 final long elapsedRealtime = mClocks.elapsedRealtime();
4093 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07004094 recordCurrentTimeChangeLocked(currentTime, elapsedRealtime, uptime);
Dianne Hackbornd48954f2015-07-22 17:20:33 -07004095 ensureStartClockTime(currentTime);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07004096 }
4097
Dianne Hackborn61659e52014-07-09 16:13:01 -07004098 public void noteProcessStartLocked(String name, int uid) {
4099 uid = mapUid(uid);
4100 if (isOnBattery()) {
4101 Uid u = getUidStatsLocked(uid);
4102 u.getProcessStatsLocked(name).incStartsLocked();
4103 }
4104 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_START, name, uid, 0)) {
4105 return;
4106 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004107 if (!mRecordAllHistory) {
4108 return;
4109 }
Joe Onoratoabded112016-02-08 16:49:39 -08004110 final long elapsedRealtime = mClocks.elapsedRealtime();
4111 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn61659e52014-07-09 16:13:01 -07004112 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_START, name, uid);
4113 }
4114
Dianne Hackborn1e01d162014-12-04 17:46:42 -08004115 public void noteProcessCrashLocked(String name, int uid) {
4116 uid = mapUid(uid);
4117 if (isOnBattery()) {
4118 Uid u = getUidStatsLocked(uid);
4119 u.getProcessStatsLocked(name).incNumCrashesLocked();
4120 }
4121 }
4122
4123 public void noteProcessAnrLocked(String name, int uid) {
4124 uid = mapUid(uid);
4125 if (isOnBattery()) {
4126 Uid u = getUidStatsLocked(uid);
4127 u.getProcessStatsLocked(name).incNumAnrsLocked();
4128 }
4129 }
4130
Dianne Hackborna8d10942015-11-19 17:55:19 -08004131 public void noteUidProcessStateLocked(int uid, int state) {
Amith Yamasanifd3caf62017-07-26 11:48:35 -07004132 int parentUid = mapUid(uid);
4133 if (uid != parentUid) {
4134 // Isolated UIDs process state is already rolled up into parent, so no need to track
4135 // Otherwise the parent's process state will get downgraded incorrectly
4136 return;
4137 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08004138 getUidStatsLocked(uid).updateUidProcessStateLocked(state);
Dianne Hackborn61659e52014-07-09 16:13:01 -07004139 }
4140
4141 public void noteProcessFinishLocked(String name, int uid) {
4142 uid = mapUid(uid);
4143 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_FINISH, name, uid, 0)) {
4144 return;
4145 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004146 if (!mRecordAllHistory) {
4147 return;
4148 }
Joe Onoratoabded112016-02-08 16:49:39 -08004149 final long elapsedRealtime = mClocks.elapsedRealtime();
4150 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004151 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_FINISH, name, uid);
Dianne Hackborn61659e52014-07-09 16:13:01 -07004152 }
4153
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004154 public void noteSyncStartLocked(String name, int uid) {
4155 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004156 final long elapsedRealtime = mClocks.elapsedRealtime();
4157 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004158 getUidStatsLocked(uid).noteStartSyncLocked(name, elapsedRealtime);
4159 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_START, name, uid, 0)) {
4160 return;
4161 }
4162 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_START, name, uid);
4163 }
4164
4165 public void noteSyncFinishLocked(String name, int uid) {
4166 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004167 final long elapsedRealtime = mClocks.elapsedRealtime();
4168 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004169 getUidStatsLocked(uid).noteStopSyncLocked(name, elapsedRealtime);
4170 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_FINISH, name, uid, 0)) {
4171 return;
4172 }
4173 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_FINISH, name, uid);
4174 }
4175
4176 public void noteJobStartLocked(String name, int uid) {
4177 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004178 final long elapsedRealtime = mClocks.elapsedRealtime();
4179 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004180 getUidStatsLocked(uid).noteStartJobLocked(name, elapsedRealtime);
4181 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_START, name, uid, 0)) {
4182 return;
4183 }
4184 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_START, name, uid);
4185 }
4186
Dianne Hackborn94326cb2017-06-28 16:17:20 -07004187 public void noteJobFinishLocked(String name, int uid, int stopReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004188 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004189 final long elapsedRealtime = mClocks.elapsedRealtime();
4190 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07004191 getUidStatsLocked(uid).noteStopJobLocked(name, elapsedRealtime, stopReason);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004192 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_FINISH, name, uid, 0)) {
4193 return;
4194 }
4195 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_FINISH, name, uid);
4196 }
4197
Amith Yamasani977e11f2018-02-16 11:29:54 -08004198 public void noteJobsDeferredLocked(int uid, int numDeferred, long sinceLast) {
4199 uid = mapUid(uid);
4200 getUidStatsLocked(uid).noteJobsDeferredLocked(numDeferred, sinceLast);
4201 }
4202
Narayan Kamath695cf722017-12-21 18:32:47 +00004203 public void noteAlarmStartLocked(String name, WorkSource workSource, int uid) {
4204 noteAlarmStartOrFinishLocked(HistoryItem.EVENT_ALARM_START, name, workSource, uid);
Dianne Hackborn1e383822015-04-10 14:02:33 -07004205 }
4206
Narayan Kamath695cf722017-12-21 18:32:47 +00004207 public void noteAlarmFinishLocked(String name, WorkSource workSource, int uid) {
4208 noteAlarmStartOrFinishLocked(HistoryItem.EVENT_ALARM_FINISH, name, workSource, uid);
4209 }
4210
4211 private void noteAlarmStartOrFinishLocked(int historyItem, String name, WorkSource workSource,
4212 int uid) {
Dianne Hackborn1e383822015-04-10 14:02:33 -07004213 if (!mRecordAllHistory) {
4214 return;
4215 }
Narayan Kamath695cf722017-12-21 18:32:47 +00004216
Joe Onoratoabded112016-02-08 16:49:39 -08004217 final long elapsedRealtime = mClocks.elapsedRealtime();
4218 final long uptime = mClocks.uptimeMillis();
Narayan Kamath695cf722017-12-21 18:32:47 +00004219
4220 if (workSource != null) {
4221 for (int i = 0; i < workSource.size(); ++i) {
4222 uid = mapUid(workSource.get(i));
4223 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4224 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4225 }
4226 }
4227
4228 List<WorkChain> workChains = workSource.getWorkChains();
4229 if (workChains != null) {
4230 for (int i = 0; i < workChains.size(); ++i) {
4231 uid = mapUid(workChains.get(i).getAttributionUid());
4232 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4233 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4234 }
4235 }
4236 }
4237 } else {
4238 uid = mapUid(uid);
4239
4240 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4241 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4242 }
4243 }
4244 }
4245
4246 public void noteWakupAlarmLocked(String packageName, int uid, WorkSource workSource,
4247 String tag) {
Narayan Kamath695cf722017-12-21 18:32:47 +00004248 if (workSource != null) {
4249 for (int i = 0; i < workSource.size(); ++i) {
4250 uid = workSource.get(i);
4251 final String workSourceName = workSource.getName(i);
4252
Tej Singh6f724c42018-01-03 20:02:03 -08004253 if (isOnBattery()) {
4254 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid,
4255 workSourceName != null ? workSourceName : packageName);
4256 pkg.noteWakeupAlarmLocked(tag);
4257 }
Yangster-mac2f5daec2018-01-16 10:23:15 -08004258 StatsLog.write_non_chained(StatsLog.WAKEUP_ALARM_OCCURRED, workSource.get(i),
4259 workSource.getName(i), tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004260 }
4261
4262 ArrayList<WorkChain> workChains = workSource.getWorkChains();
4263 if (workChains != null) {
4264 for (int i = 0; i < workChains.size(); ++i) {
4265 final WorkChain wc = workChains.get(i);
4266 uid = wc.getAttributionUid();
4267
Tej Singh6f724c42018-01-03 20:02:03 -08004268 if (isOnBattery()) {
4269 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid, packageName);
4270 pkg.noteWakeupAlarmLocked(tag);
4271 }
Yangster-macafad8c62018-01-05 22:30:49 -08004272 StatsLog.write(StatsLog.WAKEUP_ALARM_OCCURRED, wc.getUids(), wc.getTags(), tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004273 }
4274 }
4275 } else {
Tej Singh6f724c42018-01-03 20:02:03 -08004276 if (isOnBattery()) {
4277 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid, packageName);
4278 pkg.noteWakeupAlarmLocked(tag);
4279 }
Yangster-mac2f5daec2018-01-16 10:23:15 -08004280 StatsLog.write_non_chained(StatsLog.WAKEUP_ALARM_OCCURRED, uid, null, tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004281 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07004282 }
4283
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004284 private void requestWakelockCpuUpdate() {
Sudheer Shankac57729a2018-02-09 15:44:42 -08004285 mExternalSync.scheduleCpuSyncDueToWakelockChange(DELAY_UPDATE_WAKELOCKS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004286 }
4287
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004288 private void requestImmediateCpuUpdate() {
Sudheer Shankac57729a2018-02-09 15:44:42 -08004289 mExternalSync.scheduleCpuSyncDueToWakelockChange(0 /* delayMillis */);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004290 }
4291
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004292 public void setRecordAllHistoryLocked(boolean enabled) {
4293 mRecordAllHistory = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004294 if (!enabled) {
4295 // Clear out any existing state.
4296 mActiveEvents.removeEvents(HistoryItem.EVENT_WAKE_LOCK);
Dianne Hackborn1e383822015-04-10 14:02:33 -07004297 mActiveEvents.removeEvents(HistoryItem.EVENT_ALARM);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004298 // Record the currently running processes as stopping, now that we are no
4299 // longer tracking them.
4300 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
4301 HistoryItem.EVENT_PROC);
4302 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08004303 long mSecRealtime = mClocks.elapsedRealtime();
4304 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004305 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
4306 SparseIntArray uids = ent.getValue();
4307 for (int j=0; j<uids.size(); j++) {
4308 addHistoryEventLocked(mSecRealtime, mSecUptime,
4309 HistoryItem.EVENT_PROC_FINISH, ent.getKey(), uids.keyAt(j));
4310 }
4311 }
4312 }
4313 } else {
4314 // Record the currently running processes as starting, now that we are tracking them.
4315 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
4316 HistoryItem.EVENT_PROC);
4317 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08004318 long mSecRealtime = mClocks.elapsedRealtime();
4319 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004320 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
4321 SparseIntArray uids = ent.getValue();
4322 for (int j=0; j<uids.size(); j++) {
4323 addHistoryEventLocked(mSecRealtime, mSecUptime,
4324 HistoryItem.EVENT_PROC_START, ent.getKey(), uids.keyAt(j));
4325 }
4326 }
4327 }
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004328 }
4329 }
4330
Dianne Hackborn9a755432014-05-15 17:05:22 -07004331 public void setNoAutoReset(boolean enabled) {
4332 mNoAutoReset = enabled;
4333 }
4334
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004335 public void setPretendScreenOff(boolean pretendScreenOff) {
Mike Mac2f518a2017-09-19 16:06:03 -07004336 if (mPretendScreenOff != pretendScreenOff) {
4337 mPretendScreenOff = pretendScreenOff;
4338 noteScreenStateLocked(pretendScreenOff ? Display.STATE_OFF : Display.STATE_ON);
4339 }
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004340 }
4341
Dianne Hackborn9a755432014-05-15 17:05:22 -07004342 private String mInitialAcquireWakeName;
4343 private int mInitialAcquireWakeUid = -1;
4344
Narayan Kamath81822022017-12-08 11:56:01 +00004345 public void noteStartWakeLocked(int uid, int pid, WorkChain wc, String name, String historyName,
4346 int type, boolean unimportantForLogging, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004347 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004348 if (type == WAKE_TYPE_PARTIAL) {
4349 // Only care about partial wake locks, since full wake locks
4350 // will be canceled when the user puts the screen to sleep.
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004351 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07004352 if (historyName == null) {
4353 historyName = name;
4354 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004355 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07004356 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_START, historyName,
4357 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07004358 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07004359 HistoryItem.EVENT_WAKE_LOCK_START, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07004360 }
4361 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004362 if (mWakeLockNesting == 0) {
4363 mHistoryCur.states |= HistoryItem.STATE_WAKE_LOCK_FLAG;
4364 if (DEBUG_HISTORY) Slog.v(TAG, "Start wake lock to: "
4365 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08004366 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004367 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07004368 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004369 mWakeLockImportant = !unimportantForLogging;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004370 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07004371 } else if (!mWakeLockImportant && !unimportantForLogging
4372 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004373 if (mHistoryLastWritten.wakelockTag != null) {
4374 // We'll try to update the last tag.
4375 mHistoryLastWritten.wakelockTag = null;
4376 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004377 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07004378 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004379 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004380 }
4381 mWakeLockImportant = true;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004382 }
4383 mWakeLockNesting++;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004384 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004385 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07004386 if (mOnBatteryScreenOffTimeBase.isRunning()) {
4387 // We only update the cpu time when a wake lock is acquired if the screen is off.
4388 // If the screen is on, we don't distribute the power amongst partial wakelocks.
4389 if (DEBUG_ENERGY_CPU) {
4390 Slog.d(TAG, "Updating cpu time because of +wake_lock");
4391 }
4392 requestWakelockCpuUpdate();
4393 }
Narayan Kamath81822022017-12-08 11:56:01 +00004394
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004395 getUidStatsLocked(uid).noteStartWakeLocked(pid, name, type, elapsedRealtime);
Narayan Kamath81822022017-12-08 11:56:01 +00004396
Yangster-mac20877162017-12-22 17:19:39 -08004397 if (wc != null) {
Bookatz1a1b0462018-01-12 11:47:03 -08004398 StatsLog.write(StatsLog.WAKELOCK_STATE_CHANGED, wc.getUids(), wc.getTags(),
Bookatz90867622018-01-31 15:05:57 -08004399 getPowerManagerWakeLockLevel(type), name,
4400 StatsLog.WAKELOCK_STATE_CHANGED__STATE__ACQUIRE);
Yangster-macafad8c62018-01-05 22:30:49 -08004401 } else {
Bookatz1a1b0462018-01-12 11:47:03 -08004402 StatsLog.write_non_chained(StatsLog.WAKELOCK_STATE_CHANGED, uid, null,
Bookatz90867622018-01-31 15:05:57 -08004403 getPowerManagerWakeLockLevel(type), name,
4404 StatsLog.WAKELOCK_STATE_CHANGED__STATE__ACQUIRE);
Narayan Kamath81822022017-12-08 11:56:01 +00004405 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004406 }
4407 }
4408
Narayan Kamath81822022017-12-08 11:56:01 +00004409 public void noteStopWakeLocked(int uid, int pid, WorkChain wc, String name, String historyName,
4410 int type, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004411 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004412 if (type == WAKE_TYPE_PARTIAL) {
4413 mWakeLockNesting--;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004414 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07004415 if (historyName == null) {
4416 historyName = name;
4417 }
4418 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName,
4419 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07004420 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07004421 HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07004422 }
4423 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004424 if (mWakeLockNesting == 0) {
4425 mHistoryCur.states &= ~HistoryItem.STATE_WAKE_LOCK_FLAG;
4426 if (DEBUG_HISTORY) Slog.v(TAG, "Stop wake lock to: "
4427 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn37de0982014-05-09 09:32:18 -07004428 mInitialAcquireWakeName = null;
4429 mInitialAcquireWakeUid = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004430 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004431 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004432 }
4433 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07004434 if (mOnBatteryScreenOffTimeBase.isRunning()) {
4435 if (DEBUG_ENERGY_CPU) {
4436 Slog.d(TAG, "Updating cpu time because of -wake_lock");
4437 }
4438 requestWakelockCpuUpdate();
4439 }
Narayan Kamath81822022017-12-08 11:56:01 +00004440
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004441 getUidStatsLocked(uid).noteStopWakeLocked(pid, name, type, elapsedRealtime);
Yangster-mac20877162017-12-22 17:19:39 -08004442 if (wc != null) {
Bookatz1a1b0462018-01-12 11:47:03 -08004443 StatsLog.write(StatsLog.WAKELOCK_STATE_CHANGED, wc.getUids(), wc.getTags(),
Bookatz90867622018-01-31 15:05:57 -08004444 getPowerManagerWakeLockLevel(type), name,
4445 StatsLog.WAKELOCK_STATE_CHANGED__STATE__RELEASE);
Yangster-macafad8c62018-01-05 22:30:49 -08004446 } else {
Bookatz1a1b0462018-01-12 11:47:03 -08004447 StatsLog.write_non_chained(StatsLog.WAKELOCK_STATE_CHANGED, uid, null,
Bookatz90867622018-01-31 15:05:57 -08004448 getPowerManagerWakeLockLevel(type), name,
4449 StatsLog.WAKELOCK_STATE_CHANGED__STATE__RELEASE);
Narayan Kamath81822022017-12-08 11:56:01 +00004450 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004451 }
4452 }
4453
Bookatz1a1b0462018-01-12 11:47:03 -08004454 /**
4455 * Converts BatteryStats wakelock types back into PowerManager wakelock levels.
4456 * This is the inverse map of Notifier.getBatteryStatsWakeLockMonitorType().
4457 * These are estimations, since batterystats loses some of the original data.
4458 * TODO: Delete this. Instead, StatsLog.write should be called from PowerManager's Notifier.
4459 */
4460 private int getPowerManagerWakeLockLevel(int battertStatsWakelockType) {
4461 switch (battertStatsWakelockType) {
4462 // PowerManager.PARTIAL_WAKE_LOCK or PROXIMITY_SCREEN_OFF_WAKE_LOCK
4463 case BatteryStats.WAKE_TYPE_PARTIAL:
4464 return PowerManager.PARTIAL_WAKE_LOCK;
4465
4466 // PowerManager.SCREEN_DIM_WAKE_LOCK or SCREEN_BRIGHT_WAKE_LOCK
4467 case BatteryStats.WAKE_TYPE_FULL:
4468 return PowerManager.FULL_WAKE_LOCK;
4469
4470 case BatteryStats.WAKE_TYPE_DRAW:
4471 return PowerManager.DRAW_WAKE_LOCK;
4472
4473 // It appears that nothing can ever make a Window and PowerManager lacks an equivalent.
4474 case BatteryStats.WAKE_TYPE_WINDOW:
4475 Slog.e(TAG, "Illegal window wakelock type observed in batterystats.");
4476 return -1;
4477
4478 default:
4479 Slog.e(TAG, "Illegal wakelock type in batterystats: " + battertStatsWakelockType);
4480 return -1;
4481 }
4482 }
4483
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004484 public void noteStartWakeFromSourceLocked(WorkSource ws, int pid, String name,
4485 String historyName, int type, boolean unimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08004486 final long elapsedRealtime = mClocks.elapsedRealtime();
4487 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004488 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004489 for (int i=0; i<N; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004490 noteStartWakeLocked(ws.get(i), pid, null, name, historyName, type,
4491 unimportantForLogging, elapsedRealtime, uptime);
4492 }
4493
4494 List<WorkChain> wcs = ws.getWorkChains();
4495 if (wcs != null) {
4496 for (int i = 0; i < wcs.size(); ++i) {
4497 final WorkChain wc = wcs.get(i);
4498 noteStartWakeLocked(wc.getAttributionUid(), pid, wc, name, historyName, type,
4499 unimportantForLogging, elapsedRealtime, uptime);
4500 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004501 }
4502 }
4503
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004504 public void noteChangeWakelockFromSourceLocked(WorkSource ws, int pid, String name,
4505 String historyName, int type, WorkSource newWs, int newPid, String newName,
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004506 String newHistoryName, int newType, boolean newUnimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08004507 final long elapsedRealtime = mClocks.elapsedRealtime();
4508 final long uptime = mClocks.uptimeMillis();
Narayan Kamath81822022017-12-08 11:56:01 +00004509
4510 List<WorkChain>[] wcs = WorkSource.diffChains(ws, newWs);
4511
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004512 // For correct semantics, we start the need worksources first, so that we won't
4513 // make inappropriate history items as if all wake locks went away and new ones
4514 // appeared. This is okay because tracking of wake locks allows nesting.
Narayan Kamath81822022017-12-08 11:56:01 +00004515 //
4516 // First the starts :
Dianne Hackborn40c87252014-03-19 16:55:40 -07004517 final int NN = newWs.size();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004518 for (int i=0; i<NN; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004519 noteStartWakeLocked(newWs.get(i), newPid, null, newName, newHistoryName, newType,
Dianne Hackborn40c87252014-03-19 16:55:40 -07004520 newUnimportantForLogging, elapsedRealtime, uptime);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004521 }
Narayan Kamath81822022017-12-08 11:56:01 +00004522 if (wcs != null) {
4523 List<WorkChain> newChains = wcs[0];
4524 if (newChains != null) {
4525 for (int i = 0; i < newChains.size(); ++i) {
4526 final WorkChain newChain = newChains.get(i);
4527 noteStartWakeLocked(newChain.getAttributionUid(), newPid, newChain, newName,
4528 newHistoryName, newType, newUnimportantForLogging, elapsedRealtime,
4529 uptime);
4530 }
4531 }
4532 }
4533
4534 // Then the stops :
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004535 final int NO = ws.size();
4536 for (int i=0; i<NO; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004537 noteStopWakeLocked(ws.get(i), pid, null, name, historyName, type, elapsedRealtime,
4538 uptime);
4539 }
4540 if (wcs != null) {
4541 List<WorkChain> goneChains = wcs[1];
4542 if (goneChains != null) {
4543 for (int i = 0; i < goneChains.size(); ++i) {
4544 final WorkChain goneChain = goneChains.get(i);
4545 noteStopWakeLocked(goneChain.getAttributionUid(), pid, goneChain, name,
4546 historyName, type, elapsedRealtime, uptime);
4547 }
4548 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004549 }
4550 }
4551
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004552 public void noteStopWakeFromSourceLocked(WorkSource ws, int pid, String name,
4553 String historyName, int type) {
Joe Onoratoabded112016-02-08 16:49:39 -08004554 final long elapsedRealtime = mClocks.elapsedRealtime();
4555 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004556 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004557 for (int i=0; i<N; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004558 noteStopWakeLocked(ws.get(i), pid, null, name, historyName, type, elapsedRealtime,
4559 uptime);
4560 }
4561
4562 List<WorkChain> wcs = ws.getWorkChains();
4563 if (wcs != null) {
4564 for (int i = 0; i < wcs.size(); ++i) {
4565 final WorkChain wc = wcs.get(i);
4566 noteStopWakeLocked(wc.getAttributionUid(), pid, wc, name, historyName, type,
4567 elapsedRealtime, uptime);
4568 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004569 }
4570 }
4571
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004572 public void noteLongPartialWakelockStart(String name, String historyName, int uid) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08004573 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004574 uid, null, name, historyName,
4575 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
Yangster-macafad8c62018-01-05 22:30:49 -08004576
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004577 uid = mapUid(uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004578 noteLongPartialWakeLockStartInternal(name, historyName, uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004579 }
4580
4581 public void noteLongPartialWakelockStartFromSource(String name, String historyName,
4582 WorkSource workSource) {
4583 final int N = workSource.size();
4584 for (int i = 0; i < N; ++i) {
4585 final int uid = mapUid(workSource.get(i));
4586 noteLongPartialWakeLockStartInternal(name, historyName, uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08004587 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004588 workSource.get(i), workSource.getName(i), name, historyName,
4589 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath96a92562018-01-02 18:57:17 +00004590 }
4591
4592 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
4593 if (workChains != null) {
4594 for (int i = 0; i < workChains.size(); ++i) {
4595 final WorkChain workChain = workChains.get(i);
4596 final int uid = workChain.getAttributionUid();
4597 noteLongPartialWakeLockStartInternal(name, historyName, uid);
4598
Yangster-macafad8c62018-01-05 22:30:49 -08004599 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004600 workChain.getUids(), workChain.getTags(), name, historyName,
4601 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath96a92562018-01-02 18:57:17 +00004602 }
4603 }
4604 }
4605
4606 private void noteLongPartialWakeLockStartInternal(String name, String historyName, int uid) {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004607 final long elapsedRealtime = mClocks.elapsedRealtime();
4608 final long uptime = mClocks.uptimeMillis();
4609 if (historyName == null) {
4610 historyName = name;
4611 }
4612 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_START, historyName, uid,
4613 0)) {
4614 return;
4615 }
4616 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_START,
4617 historyName, uid);
4618 }
4619
4620 public void noteLongPartialWakelockFinish(String name, String historyName, int uid) {
Bookatz90867622018-01-31 15:05:57 -08004621 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED, uid, null,
4622 name, historyName, StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
Yangster-macafad8c62018-01-05 22:30:49 -08004623
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004624 uid = mapUid(uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004625 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004626 }
4627
4628 public void noteLongPartialWakelockFinishFromSource(String name, String historyName,
4629 WorkSource workSource) {
4630 final int N = workSource.size();
4631 for (int i = 0; i < N; ++i) {
4632 final int uid = mapUid(workSource.get(i));
4633 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08004634 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004635 workSource.get(i), workSource.getName(i), name, historyName,
4636 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath96a92562018-01-02 18:57:17 +00004637 }
4638
4639 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
4640 if (workChains != null) {
4641 for (int i = 0; i < workChains.size(); ++i) {
4642 final WorkChain workChain = workChains.get(i);
4643 final int uid = workChain.getAttributionUid();
Narayan Kamath96a92562018-01-02 18:57:17 +00004644 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Yangster-macafad8c62018-01-05 22:30:49 -08004645 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004646 workChain.getUids(), workChain.getTags(), name, historyName,
4647 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath96a92562018-01-02 18:57:17 +00004648 }
4649 }
4650 }
4651
4652 private void noteLongPartialWakeLockFinishInternal(String name, String historyName, int uid) {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004653 final long elapsedRealtime = mClocks.elapsedRealtime();
4654 final long uptime = mClocks.uptimeMillis();
4655 if (historyName == null) {
4656 historyName = name;
4657 }
4658 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH, historyName, uid,
4659 0)) {
4660 return;
4661 }
4662 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH,
4663 historyName, uid);
4664 }
4665
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004666 void aggregateLastWakeupUptimeLocked(long uptimeMs) {
4667 if (mLastWakeupReason != null) {
4668 long deltaUptime = uptimeMs - mLastWakeupUptimeMs;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004669 SamplingTimer timer = getWakeupReasonTimerLocked(mLastWakeupReason);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07004670 timer.add(deltaUptime * 1000, 1); // time in in microseconds
Bookatz90867622018-01-31 15:05:57 -08004671 StatsLog.write(StatsLog.KERNEL_WAKEUP_REPORTED, mLastWakeupReason,
4672 /* duration_usec */ deltaUptime * 1000);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004673 mLastWakeupReason = null;
4674 }
4675 }
4676
4677 public void noteWakeupReasonLocked(String reason) {
Joe Onoratoabded112016-02-08 16:49:39 -08004678 final long elapsedRealtime = mClocks.elapsedRealtime();
4679 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004680 if (DEBUG_HISTORY) Slog.v(TAG, "Wakeup reason \"" + reason +"\": "
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004681 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004682 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004683 mHistoryCur.wakeReasonTag = mHistoryCur.localWakeReasonTag;
4684 mHistoryCur.wakeReasonTag.string = reason;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004685 mHistoryCur.wakeReasonTag.uid = 0;
4686 mLastWakeupReason = reason;
4687 mLastWakeupUptimeMs = uptime;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004688 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004689 }
4690
Adam Lesinski72478f02015-06-17 15:39:43 -07004691 public boolean startAddingCpuLocked() {
Sudheer Shankac57729a2018-02-09 15:44:42 -08004692 mExternalSync.cancelCpuSyncDueToWakelockChange();
Adam Lesinski72478f02015-06-17 15:39:43 -07004693 return mOnBatteryInternal;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004694 }
4695
Adam Lesinski72478f02015-06-17 15:39:43 -07004696 public void finishAddingCpuLocked(int totalUTime, int totalSTime, int statUserTime,
4697 int statSystemTime, int statIOWaitTime, int statIrqTime,
4698 int statSoftIrqTime, int statIdleTime) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004699 if (DEBUG) Slog.d(TAG, "Adding cpu: tuser=" + totalUTime + " tsys=" + totalSTime
4700 + " user=" + statUserTime + " sys=" + statSystemTime
4701 + " io=" + statIOWaitTime + " irq=" + statIrqTime
4702 + " sirq=" + statSoftIrqTime + " idle=" + statIdleTime);
4703 mCurStepCpuUserTime += totalUTime;
4704 mCurStepCpuSystemTime += totalSTime;
4705 mCurStepStatUserTime += statUserTime;
4706 mCurStepStatSystemTime += statSystemTime;
4707 mCurStepStatIOWaitTime += statIOWaitTime;
4708 mCurStepStatIrqTime += statIrqTime;
4709 mCurStepStatSoftIrqTime += statSoftIrqTime;
4710 mCurStepStatIdleTime += statIdleTime;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004711 }
4712
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004713 public void noteProcessDiedLocked(int uid, int pid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004714 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004715 Uid u = mUidStats.get(uid);
4716 if (u != null) {
4717 u.mPids.remove(pid);
4718 }
4719 }
4720
4721 public long getProcessWakeTime(int uid, int pid, long realtime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004722 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004723 Uid u = mUidStats.get(uid);
4724 if (u != null) {
4725 Uid.Pid p = u.mPids.get(pid);
4726 if (p != null) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004727 return p.mWakeSumMs + (p.mWakeNesting > 0 ? (realtime - p.mWakeStartMs) : 0);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004728 }
4729 }
4730 return 0;
4731 }
4732
Dianne Hackborn287952c2010-09-22 22:34:31 -07004733 public void reportExcessiveCpuLocked(int uid, String proc, long overTime, long usedTime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004734 uid = mapUid(uid);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004735 Uid u = mUidStats.get(uid);
4736 if (u != null) {
4737 u.reportExcessiveCpuLocked(proc, overTime, usedTime);
4738 }
4739 }
4740
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004741 int mSensorNesting;
4742
4743 public void noteStartSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004744 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004745 final long elapsedRealtime = mClocks.elapsedRealtime();
4746 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004747 if (mSensorNesting == 0) {
4748 mHistoryCur.states |= HistoryItem.STATE_SENSOR_ON_FLAG;
4749 if (DEBUG_HISTORY) Slog.v(TAG, "Start sensor to: "
4750 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004751 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004752 }
4753 mSensorNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004754 getUidStatsLocked(uid).noteStartSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004755 }
4756
4757 public void noteStopSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004758 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004759 final long elapsedRealtime = mClocks.elapsedRealtime();
4760 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004761 mSensorNesting--;
4762 if (mSensorNesting == 0) {
4763 mHistoryCur.states &= ~HistoryItem.STATE_SENSOR_ON_FLAG;
4764 if (DEBUG_HISTORY) Slog.v(TAG, "Stop sensor to: "
4765 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004766 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004767 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004768 getUidStatsLocked(uid).noteStopSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004769 }
4770
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004771 int mGpsNesting;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004772
Narayan Kamath32684dd2018-01-08 17:32:51 +00004773 public void noteGpsChangedLocked(WorkSource oldWs, WorkSource newWs) {
4774 for (int i = 0; i < newWs.size(); ++i) {
4775 noteStartGpsLocked(newWs.get(i), null);
4776 }
4777
4778 for (int i = 0; i < oldWs.size(); ++i) {
4779 noteStopGpsLocked((oldWs.get(i)), null);
4780 }
4781
4782 List<WorkChain>[] wcs = WorkSource.diffChains(oldWs, newWs);
4783 if (wcs != null) {
4784 if (wcs[0] != null) {
4785 final List<WorkChain> newChains = wcs[0];
4786 for (int i = 0; i < newChains.size(); ++i) {
4787 noteStartGpsLocked(-1, newChains.get(i));
4788 }
4789 }
4790
4791 if (wcs[1] != null) {
4792 final List<WorkChain> goneChains = wcs[1];
4793 for (int i = 0; i < goneChains.size(); ++i) {
4794 noteStopGpsLocked(-1, goneChains.get(i));
4795 }
4796 }
4797 }
4798 }
4799
4800 private void noteStartGpsLocked(int uid, WorkChain workChain) {
4801 uid = getAttributionUid(uid, workChain);
Joe Onoratoabded112016-02-08 16:49:39 -08004802 final long elapsedRealtime = mClocks.elapsedRealtime();
4803 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004804 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004805 mHistoryCur.states |= HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004806 if (DEBUG_HISTORY) Slog.v(TAG, "Start GPS to: "
4807 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004808 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004809 }
4810 mGpsNesting++;
Narayan Kamath32684dd2018-01-08 17:32:51 +00004811
4812 if (workChain == null) {
Bookatz90867622018-01-31 15:05:57 -08004813 StatsLog.write_non_chained(StatsLog.GPS_SCAN_STATE_CHANGED, uid, null,
4814 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004815 } else {
4816 StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004817 workChain.getUids(), workChain.getTags(),
4818 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004819 }
4820
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004821 getUidStatsLocked(uid).noteStartGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004822 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004823
Narayan Kamath32684dd2018-01-08 17:32:51 +00004824 private void noteStopGpsLocked(int uid, WorkChain workChain) {
4825 uid = getAttributionUid(uid, workChain);
Joe Onoratoabded112016-02-08 16:49:39 -08004826 final long elapsedRealtime = mClocks.elapsedRealtime();
4827 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004828 mGpsNesting--;
4829 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004830 mHistoryCur.states &= ~HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004831 if (DEBUG_HISTORY) Slog.v(TAG, "Stop GPS to: "
4832 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004833 addHistoryRecordLocked(elapsedRealtime, uptime);
Siddharth Ray78ccaf52017-12-23 16:16:21 -08004834 stopAllGpsSignalQualityTimersLocked(-1);
4835 mGpsSignalQualityBin = -1;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004836 }
Narayan Kamath32684dd2018-01-08 17:32:51 +00004837
4838 if (workChain == null) {
Bookatz90867622018-01-31 15:05:57 -08004839 StatsLog.write_non_chained(StatsLog.GPS_SCAN_STATE_CHANGED, uid, null,
4840 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004841 } else {
4842 StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED, workChain.getUids(),
Bookatz90867622018-01-31 15:05:57 -08004843 workChain.getTags(), StatsLog.GPS_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004844 }
4845
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004846 getUidStatsLocked(uid).noteStopGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004847 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07004848
Siddharth Ray78ccaf52017-12-23 16:16:21 -08004849 public void noteGpsSignalQualityLocked(int signalLevel) {
4850 if (mGpsNesting == 0) {
4851 return;
4852 }
4853 if (signalLevel < 0 || signalLevel >= GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS) {
4854 stopAllGpsSignalQualityTimersLocked(-1);
4855 return;
4856 }
4857 final long elapsedRealtime = mClocks.elapsedRealtime();
4858 final long uptime = mClocks.uptimeMillis();
4859 if (mGpsSignalQualityBin != signalLevel) {
4860 if (mGpsSignalQualityBin >= 0) {
4861 mGpsSignalQualityTimer[mGpsSignalQualityBin].stopRunningLocked(elapsedRealtime);
4862 }
4863 if(!mGpsSignalQualityTimer[signalLevel].isRunningLocked()) {
4864 mGpsSignalQualityTimer[signalLevel].startRunningLocked(elapsedRealtime);
4865 }
4866 mHistoryCur.states2 = (mHistoryCur.states2&~HistoryItem.STATE2_GPS_SIGNAL_QUALITY_MASK)
4867 | (signalLevel << HistoryItem.STATE2_GPS_SIGNAL_QUALITY_SHIFT);
4868 addHistoryRecordLocked(elapsedRealtime, uptime);
4869 mGpsSignalQualityBin = signalLevel;
4870 }
4871 return;
4872 }
4873
Andreas Gampe3f24e692018-02-05 13:24:28 -08004874 @GuardedBy("this")
Jeff Browne95c3cd2014-05-02 16:59:26 -07004875 public void noteScreenStateLocked(int state) {
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004876 state = mPretendScreenOff ? Display.STATE_OFF : state;
Santos Cordone94f0502017-02-24 12:31:20 -08004877
4878 // Battery stats relies on there being 4 states. To accommodate this, new states beyond the
4879 // original 4 are mapped to one of the originals.
4880 if (state > MAX_TRACKED_SCREEN_STATE) {
4881 switch (state) {
4882 case Display.STATE_VR:
4883 state = Display.STATE_ON;
4884 break;
4885 default:
4886 Slog.wtf(TAG, "Unknown screen state (not mapped): " + state);
4887 break;
4888 }
4889 }
4890
Jeff Browne95c3cd2014-05-02 16:59:26 -07004891 if (mScreenState != state) {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08004892 recordDailyStatsIfNeededLocked(true);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004893 final int oldState = mScreenState;
4894 mScreenState = state;
4895 if (DEBUG) Slog.v(TAG, "Screen state: oldState=" + Display.stateToString(oldState)
4896 + ", newState=" + Display.stateToString(state));
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004897
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004898 if (state != Display.STATE_UNKNOWN) {
4899 int stepState = state-1;
Santos Cordone94f0502017-02-24 12:31:20 -08004900 if ((stepState & STEP_LEVEL_MODE_SCREEN_STATE) == stepState) {
4901 mModStepMode |= (mCurStepMode & STEP_LEVEL_MODE_SCREEN_STATE) ^ stepState;
4902 mCurStepMode = (mCurStepMode & ~STEP_LEVEL_MODE_SCREEN_STATE) | stepState;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004903 } else {
4904 Slog.wtf(TAG, "Unexpected screen state: " + state);
4905 }
4906 }
4907
Mike Mac2f518a2017-09-19 16:06:03 -07004908 final long elapsedRealtime = mClocks.elapsedRealtime();
4909 final long uptime = mClocks.uptimeMillis();
4910
4911 boolean updateHistory = false;
4912 if (isScreenDoze(state)) {
4913 mHistoryCur.states |= HistoryItem.STATE_SCREEN_DOZE_FLAG;
4914 mScreenDozeTimer.startRunningLocked(elapsedRealtime);
4915 updateHistory = true;
4916 } else if (isScreenDoze(oldState)) {
4917 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_DOZE_FLAG;
4918 mScreenDozeTimer.stopRunningLocked(elapsedRealtime);
4919 updateHistory = true;
4920 }
4921 if (isScreenOn(state)) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07004922 mHistoryCur.states |= HistoryItem.STATE_SCREEN_ON_FLAG;
4923 if (DEBUG_HISTORY) Slog.v(TAG, "Screen on to: "
4924 + Integer.toHexString(mHistoryCur.states));
Jeff Browne95c3cd2014-05-02 16:59:26 -07004925 mScreenOnTimer.startRunningLocked(elapsedRealtime);
4926 if (mScreenBrightnessBin >= 0) {
4927 mScreenBrightnessTimer[mScreenBrightnessBin].startRunningLocked(elapsedRealtime);
4928 }
Mike Mac2f518a2017-09-19 16:06:03 -07004929 updateHistory = true;
4930 } else if (isScreenOn(oldState)) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07004931 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_ON_FLAG;
4932 if (DEBUG_HISTORY) Slog.v(TAG, "Screen off to: "
4933 + Integer.toHexString(mHistoryCur.states));
Jeff Browne95c3cd2014-05-02 16:59:26 -07004934 mScreenOnTimer.stopRunningLocked(elapsedRealtime);
4935 if (mScreenBrightnessBin >= 0) {
4936 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
4937 }
Mike Mac2f518a2017-09-19 16:06:03 -07004938 updateHistory = true;
4939 }
4940 if (updateHistory) {
4941 if (DEBUG_HISTORY) Slog.v(TAG, "Screen state to: "
4942 + Display.stateToString(state));
4943 addHistoryRecordLocked(elapsedRealtime, uptime);
4944 }
Sudheer Shankac57729a2018-02-09 15:44:42 -08004945 mExternalSync.scheduleCpuSyncDueToScreenStateChange(
4946 mOnBatteryTimeBase.isRunning(), mOnBatteryScreenOffTimeBase.isRunning());
Mike Mac2f518a2017-09-19 16:06:03 -07004947 if (isScreenOn(state)) {
4948 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), state,
4949 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
4950 // Fake a wake lock, so we consider the device waked as long as the screen is on.
Narayan Kamath81822022017-12-08 11:56:01 +00004951 noteStartWakeLocked(-1, -1, null, "screen", null, WAKE_TYPE_PARTIAL, false,
Mike Mac2f518a2017-09-19 16:06:03 -07004952 elapsedRealtime, uptime);
4953 } else if (isScreenOn(oldState)) {
Narayan Kamath81822022017-12-08 11:56:01 +00004954 noteStopWakeLocked(-1, -1, null, "screen", "screen", WAKE_TYPE_PARTIAL,
Jeff Browne95c3cd2014-05-02 16:59:26 -07004955 elapsedRealtime, uptime);
Mike Mac2f518a2017-09-19 16:06:03 -07004956 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), state,
Joe Onoratoabded112016-02-08 16:49:39 -08004957 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
Mike Mac2f518a2017-09-19 16:06:03 -07004958 }
4959 // Update discharge amounts.
4960 if (mOnBatteryInternal) {
4961 updateDischargeScreenLevelsLocked(oldState, state);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08004962 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07004963 }
4964 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004965
Dianne Hackborn617f8772009-03-31 15:04:46 -07004966 public void noteScreenBrightnessLocked(int brightness) {
4967 // Bin the brightness.
4968 int bin = brightness / (256/NUM_SCREEN_BRIGHTNESS_BINS);
4969 if (bin < 0) bin = 0;
4970 else if (bin >= NUM_SCREEN_BRIGHTNESS_BINS) bin = NUM_SCREEN_BRIGHTNESS_BINS-1;
4971 if (mScreenBrightnessBin != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08004972 final long elapsedRealtime = mClocks.elapsedRealtime();
4973 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004974 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_BRIGHTNESS_MASK)
4975 | (bin << HistoryItem.STATE_BRIGHTNESS_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004976 if (DEBUG_HISTORY) Slog.v(TAG, "Screen brightness " + bin + " to: "
4977 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004978 addHistoryRecordLocked(elapsedRealtime, uptime);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004979 if (mScreenState == Display.STATE_ON) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07004980 if (mScreenBrightnessBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004981 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07004982 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004983 mScreenBrightnessTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07004984 }
4985 mScreenBrightnessBin = bin;
4986 }
4987 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004988
Dianne Hackborn617f8772009-03-31 15:04:46 -07004989 public void noteUserActivityLocked(int uid, int event) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08004990 if (mOnBatteryInternal) {
4991 uid = mapUid(uid);
4992 getUidStatsLocked(uid).noteUserActivityLocked(event);
4993 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004994 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004995
Dianne Hackborn280a64e2015-07-13 14:48:08 -07004996 public void noteWakeUpLocked(String reason, int reasonUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004997 final long elapsedRealtime = mClocks.elapsedRealtime();
4998 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn280a64e2015-07-13 14:48:08 -07004999 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SCREEN_WAKE_UP,
5000 reason, reasonUid);
5001 }
5002
Jeff Browne95c3cd2014-05-02 16:59:26 -07005003 public void noteInteractiveLocked(boolean interactive) {
5004 if (mInteractive != interactive) {
Joe Onoratoabded112016-02-08 16:49:39 -08005005 final long elapsedRealtime = mClocks.elapsedRealtime();
Jeff Browne95c3cd2014-05-02 16:59:26 -07005006 mInteractive = interactive;
5007 if (DEBUG) Slog.v(TAG, "Interactive: " + interactive);
5008 if (interactive) {
5009 mInteractiveTimer.startRunningLocked(elapsedRealtime);
5010 } else {
5011 mInteractiveTimer.stopRunningLocked(elapsedRealtime);
5012 }
5013 }
5014 }
5015
Dianne Hackborn1e01d162014-12-04 17:46:42 -08005016 public void noteConnectivityChangedLocked(int type, String extra) {
Joe Onoratoabded112016-02-08 16:49:39 -08005017 final long elapsedRealtime = mClocks.elapsedRealtime();
5018 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08005019 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_CONNECTIVITY_CHANGED,
5020 extra, type);
5021 mNumConnectivityChange++;
5022 }
5023
Adam Lesinski5f056f62016-07-14 16:56:08 -07005024 private void noteMobileRadioApWakeupLocked(final long elapsedRealtimeMillis,
5025 final long uptimeMillis, int uid) {
5026 uid = mapUid(uid);
5027 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
5028 uid);
5029 getUidStatsLocked(uid).noteMobileRadioApWakeupLocked();
5030 }
5031
Adam Lesinski14ae39a2017-05-26 11:50:40 -07005032 /**
5033 * Updates the radio power state and returns true if an external stats collection should occur.
5034 */
5035 public boolean noteMobileRadioPowerStateLocked(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005036 final long elapsedRealtime = mClocks.elapsedRealtime();
5037 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005038 if (mMobileRadioPowerState != powerState) {
5039 long realElapsedRealtimeMs;
5040 final boolean active =
5041 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
5042 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
5043 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07005044 if (uid > 0) {
5045 noteMobileRadioApWakeupLocked(elapsedRealtime, uptime, uid);
5046 }
5047
Adam Lesinski9acfd812016-04-19 18:29:50 -07005048 mMobileRadioActiveStartTime = realElapsedRealtimeMs = timestampNs / (1000 * 1000);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005049 mHistoryCur.states |= HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
5050 } else {
5051 realElapsedRealtimeMs = timestampNs / (1000*1000);
Dianne Hackbornf7097a52014-05-13 09:56:14 -07005052 long lastUpdateTimeMs = mMobileRadioActiveStartTime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005053 if (realElapsedRealtimeMs < lastUpdateTimeMs) {
5054 Slog.wtf(TAG, "Data connection inactive timestamp " + realElapsedRealtimeMs
5055 + " is before start time " + lastUpdateTimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005056 realElapsedRealtimeMs = elapsedRealtime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005057 } else if (realElapsedRealtimeMs < elapsedRealtime) {
5058 mMobileRadioActiveAdjustedTime.addCountLocked(elapsedRealtime
5059 - realElapsedRealtimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005060 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005061 mHistoryCur.states &= ~HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
5062 }
5063 if (DEBUG_HISTORY) Slog.v(TAG, "Mobile network active " + active + " to: "
5064 + Integer.toHexString(mHistoryCur.states));
5065 addHistoryRecordLocked(elapsedRealtime, uptime);
5066 mMobileRadioPowerState = powerState;
Bookatzddccf0a2017-11-28 16:48:14 -08005067 StatsLog.write(StatsLog.MOBILE_RADIO_POWER_STATE_CHANGED, uid, powerState);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005068 if (active) {
5069 mMobileRadioActiveTimer.startRunningLocked(elapsedRealtime);
5070 mMobileRadioActivePerAppTimer.startRunningLocked(elapsedRealtime);
5071 } else {
5072 mMobileRadioActiveTimer.stopRunningLocked(realElapsedRealtimeMs);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005073 mMobileRadioActivePerAppTimer.stopRunningLocked(realElapsedRealtimeMs);
Adam Lesinski14ae39a2017-05-26 11:50:40 -07005074 // Tell the caller to collect radio network/power stats.
5075 return true;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08005076 }
Dianne Hackborne13c4c02014-02-11 17:18:35 -08005077 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -07005078 return false;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08005079 }
5080
Adam Lesinski14ae39a2017-05-26 11:50:40 -07005081 public void notePowerSaveModeLocked(boolean enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005082 if (mPowerSaveModeEnabled != enabled) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07005083 int stepState = enabled ? STEP_LEVEL_MODE_POWER_SAVE : 0;
5084 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_POWER_SAVE) ^ stepState;
5085 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_POWER_SAVE) | stepState;
Joe Onoratoabded112016-02-08 16:49:39 -08005086 final long elapsedRealtime = mClocks.elapsedRealtime();
5087 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005088 mPowerSaveModeEnabled = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005089 if (enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005090 mHistoryCur.states2 |= HistoryItem.STATE2_POWER_SAVE_FLAG;
5091 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode enabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005092 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005093 mPowerSaveModeEnabledTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005094 } else {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005095 mHistoryCur.states2 &= ~HistoryItem.STATE2_POWER_SAVE_FLAG;
5096 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode disabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005097 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005098 mPowerSaveModeEnabledTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005099 }
5100 addHistoryRecordLocked(elapsedRealtime, uptime);
Bookatz90867622018-01-31 15:05:57 -08005101 StatsLog.write(StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED, enabled ?
5102 StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED__STATE__ON :
5103 StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED__STATE__OFF);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005104 }
5105 }
5106
Bookatzddccf0a2017-11-28 16:48:14 -08005107 public void noteDeviceIdleModeLocked(final int mode, String activeReason, int activeUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005108 final long elapsedRealtime = mClocks.elapsedRealtime();
5109 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005110 boolean nowIdling = mode == DEVICE_IDLE_MODE_DEEP;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005111 if (mDeviceIdling && !nowIdling && activeReason == null) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005112 // We don't go out of general idling mode until explicitly taken out of
5113 // device idle through going active or significant motion.
5114 nowIdling = true;
5115 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005116 boolean nowLightIdling = mode == DEVICE_IDLE_MODE_LIGHT;
5117 if (mDeviceLightIdling && !nowLightIdling && !nowIdling && activeReason == null) {
5118 // We don't go out of general light idling mode until explicitly taken out of
5119 // device idle through going active or significant motion.
5120 nowLightIdling = true;
5121 }
5122 if (activeReason != null && (mDeviceIdling || mDeviceLightIdling)) {
5123 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_ACTIVE,
5124 activeReason, activeUid);
5125 }
Bookatzddccf0a2017-11-28 16:48:14 -08005126 if (mDeviceIdling != nowIdling || mDeviceLightIdling != nowLightIdling) {
5127 int statsmode;
5128 if (nowIdling) statsmode = DEVICE_IDLE_MODE_DEEP;
5129 else if (nowLightIdling) statsmode = DEVICE_IDLE_MODE_LIGHT;
5130 else statsmode = DEVICE_IDLE_MODE_OFF;
5131 StatsLog.write(StatsLog.DEVICE_IDLING_MODE_STATE_CHANGED, statsmode);
5132 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005133 if (mDeviceIdling != nowIdling) {
5134 mDeviceIdling = nowIdling;
5135 int stepState = nowIdling ? STEP_LEVEL_MODE_DEVICE_IDLE : 0;
5136 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_DEVICE_IDLE) ^ stepState;
5137 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_DEVICE_IDLE) | stepState;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005138 if (nowIdling) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005139 mDeviceIdlingTimer.startRunningLocked(elapsedRealtime);
5140 } else {
5141 mDeviceIdlingTimer.stopRunningLocked(elapsedRealtime);
5142 }
5143 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005144 if (mDeviceLightIdling != nowLightIdling) {
5145 mDeviceLightIdling = nowLightIdling;
5146 if (nowLightIdling) {
5147 mDeviceLightIdlingTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005148 } else {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005149 mDeviceLightIdlingTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005150 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005151 }
5152 if (mDeviceIdleMode != mode) {
5153 mHistoryCur.states2 = (mHistoryCur.states2 & ~HistoryItem.STATE2_DEVICE_IDLE_MASK)
5154 | (mode << HistoryItem.STATE2_DEVICE_IDLE_SHIFT);
5155 if (DEBUG_HISTORY) Slog.v(TAG, "Device idle mode changed to: "
5156 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005157 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005158 long lastDuration = elapsedRealtime - mLastIdleTimeStart;
5159 mLastIdleTimeStart = elapsedRealtime;
5160 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
5161 if (lastDuration > mLongestLightIdleTime) {
5162 mLongestLightIdleTime = lastDuration;
5163 }
5164 mDeviceIdleModeLightTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005165 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005166 if (lastDuration > mLongestFullIdleTime) {
5167 mLongestFullIdleTime = lastDuration;
5168 }
5169 mDeviceIdleModeFullTimer.stopRunningLocked(elapsedRealtime);
5170 }
5171 if (mode == DEVICE_IDLE_MODE_LIGHT) {
5172 mDeviceIdleModeLightTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005173 } else if (mode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005174 mDeviceIdleModeFullTimer.startRunningLocked(elapsedRealtime);
5175 }
5176 mDeviceIdleMode = mode;
Bookatzddccf0a2017-11-28 16:48:14 -08005177 StatsLog.write(StatsLog.DEVICE_IDLE_MODE_STATE_CHANGED, mode);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005178 }
5179 }
5180
Dianne Hackborn3accca02013-09-20 09:32:11 -07005181 public void notePackageInstalledLocked(String pkgName, long versionCode) {
Joe Onoratoabded112016-02-08 16:49:39 -08005182 final long elapsedRealtime = mClocks.elapsedRealtime();
5183 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3accca02013-09-20 09:32:11 -07005184 // XXX need to figure out what to do with long version codes.
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005185 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_INSTALLED,
Dianne Hackborn3accca02013-09-20 09:32:11 -07005186 pkgName, (int)versionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005187 PackageChange pc = new PackageChange();
5188 pc.mPackageName = pkgName;
5189 pc.mUpdate = true;
5190 pc.mVersionCode = versionCode;
5191 addPackageChange(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005192 }
5193
5194 public void notePackageUninstalledLocked(String pkgName) {
Joe Onoratoabded112016-02-08 16:49:39 -08005195 final long elapsedRealtime = mClocks.elapsedRealtime();
5196 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005197 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_UNINSTALLED,
5198 pkgName, 0);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005199 PackageChange pc = new PackageChange();
5200 pc.mPackageName = pkgName;
5201 pc.mUpdate = true;
5202 addPackageChange(pc);
5203 }
5204
5205 private void addPackageChange(PackageChange pc) {
5206 if (mDailyPackageChanges == null) {
5207 mDailyPackageChanges = new ArrayList<>();
5208 }
5209 mDailyPackageChanges.add(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005210 }
5211
Siddharth Ray78ccaf52017-12-23 16:16:21 -08005212 void stopAllGpsSignalQualityTimersLocked(int except) {
5213 final long elapsedRealtime = mClocks.elapsedRealtime();
5214 for (int i = 0; i < GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
5215 if (i == except) {
5216 continue;
5217 }
5218 while (mGpsSignalQualityTimer[i].isRunningLocked()) {
5219 mGpsSignalQualityTimer[i].stopRunningLocked(elapsedRealtime);
5220 }
5221 }
5222 }
5223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005224 public void notePhoneOnLocked() {
5225 if (!mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005226 final long elapsedRealtime = mClocks.elapsedRealtime();
5227 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005228 mHistoryCur.states2 |= HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005229 if (DEBUG_HISTORY) Slog.v(TAG, "Phone on to: "
5230 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005231 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005232 mPhoneOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005233 mPhoneOnTimer.startRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005234 }
5235 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005237 public void notePhoneOffLocked() {
5238 if (mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005239 final long elapsedRealtime = mClocks.elapsedRealtime();
5240 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005241 mHistoryCur.states2 &= ~HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005242 if (DEBUG_HISTORY) Slog.v(TAG, "Phone off to: "
5243 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005244 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005245 mPhoneOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005246 mPhoneOnTimer.stopRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005247 }
5248 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07005249
Mike Mafbc01fc2018-04-02 10:28:28 -07005250 private void registerUsbStateReceiver(Context context) {
5251 final IntentFilter usbStateFilter = new IntentFilter();
5252 usbStateFilter.addAction(UsbManager.ACTION_USB_STATE);
5253 context.registerReceiver(new BroadcastReceiver() {
5254 @Override
5255 public void onReceive(Context context, Intent intent) {
5256 final boolean state = intent.getBooleanExtra(UsbManager.USB_CONNECTED, false);
5257 synchronized (BatteryStatsImpl.this) {
5258 noteUsbConnectionStateLocked(state);
5259 }
5260 }
5261 }, usbStateFilter);
5262 synchronized (this) {
5263 if (mUsbDataState == USB_DATA_UNKNOWN) {
5264 final Intent usbState = context.registerReceiver(null, usbStateFilter);
5265 final boolean initState = usbState != null && usbState.getBooleanExtra(
5266 UsbManager.USB_CONNECTED, false);
5267 noteUsbConnectionStateLocked(initState);
5268 }
5269 }
5270 }
5271
5272 private void noteUsbConnectionStateLocked(boolean connected) {
5273 int newState = connected ? USB_DATA_CONNECTED : USB_DATA_DISCONNECTED;
Mike Ma926a97c2018-03-25 02:32:35 -07005274 if (mUsbDataState != newState) {
5275 mUsbDataState = newState;
5276 if (connected) {
5277 mHistoryCur.states2 |= HistoryItem.STATE2_USB_DATA_LINK_FLAG;
5278 } else {
5279 mHistoryCur.states2 &= ~HistoryItem.STATE2_USB_DATA_LINK_FLAG;
5280 }
5281 addHistoryRecordLocked(mClocks.elapsedRealtime(), mClocks.uptimeMillis());
5282 }
5283 }
5284
Dianne Hackborn3251b902014-06-20 14:40:53 -07005285 void stopAllPhoneSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005286 final long elapsedRealtime = mClocks.elapsedRealtime();
Wink Saville52840902011-02-18 12:40:47 -08005287 for (int i = 0; i < SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005288 if (i == except) {
5289 continue;
5290 }
5291 while (mPhoneSignalStrengthsTimer[i].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005292 mPhoneSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005293 }
5294 }
5295 }
5296
Dianne Hackborne4a59512010-12-07 11:08:07 -08005297 private int fixPhoneServiceState(int state, int signalBin) {
5298 if (mPhoneSimStateRaw == TelephonyManager.SIM_STATE_ABSENT) {
5299 // In this case we will always be STATE_OUT_OF_SERVICE, so need
5300 // to infer that we are scanning from other data.
5301 if (state == ServiceState.STATE_OUT_OF_SERVICE
Wink Saville52840902011-02-18 12:40:47 -08005302 && signalBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005303 state = ServiceState.STATE_IN_SERVICE;
5304 }
5305 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005306
Dianne Hackborne4a59512010-12-07 11:08:07 -08005307 return state;
5308 }
5309
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005310 private void updateAllPhoneStateLocked(int state, int simState, int strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005311 boolean scanning = false;
5312 boolean newHistory = false;
5313
5314 mPhoneServiceStateRaw = state;
5315 mPhoneSimStateRaw = simState;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005316 mPhoneSignalStrengthBinRaw = strengthBin;
5317
Joe Onoratoabded112016-02-08 16:49:39 -08005318 final long elapsedRealtime = mClocks.elapsedRealtime();
5319 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne4a59512010-12-07 11:08:07 -08005320
5321 if (simState == TelephonyManager.SIM_STATE_ABSENT) {
5322 // In this case we will always be STATE_OUT_OF_SERVICE, so need
5323 // to infer that we are scanning from other data.
5324 if (state == ServiceState.STATE_OUT_OF_SERVICE
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005325 && strengthBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005326 state = ServiceState.STATE_IN_SERVICE;
5327 }
5328 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005329
5330 // If the phone is powered off, stop all timers.
5331 if (state == ServiceState.STATE_POWER_OFF) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005332 strengthBin = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -07005333
Dianne Hackborne4a59512010-12-07 11:08:07 -08005334 // If we are in service, make sure the correct signal string timer is running.
5335 } else if (state == ServiceState.STATE_IN_SERVICE) {
5336 // Bin will be changed below.
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005337
5338 // If we're out of service, we are in the lowest signal strength
5339 // bin and have the scanning bit set.
Amith Yamasanif37447b2009-10-08 18:28:01 -07005340 } else if (state == ServiceState.STATE_OUT_OF_SERVICE) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005341 scanning = true;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005342 strengthBin = SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN;
Amith Yamasanif37447b2009-10-08 18:28:01 -07005343 if (!mPhoneSignalScanningTimer.isRunningLocked()) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005344 mHistoryCur.states |= HistoryItem.STATE_PHONE_SCANNING_FLAG;
Dianne Hackborne4a59512010-12-07 11:08:07 -08005345 newHistory = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005346 if (DEBUG_HISTORY) Slog.v(TAG, "Phone started scanning to: "
5347 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005348 mPhoneSignalScanningTimer.startRunningLocked(elapsedRealtime);
Amith Yamasanif37447b2009-10-08 18:28:01 -07005349 }
5350 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005351
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005352 if (!scanning) {
5353 // If we are no longer scanning, then stop the scanning timer.
5354 if (mPhoneSignalScanningTimer.isRunningLocked()) {
5355 mHistoryCur.states &= ~HistoryItem.STATE_PHONE_SCANNING_FLAG;
5356 if (DEBUG_HISTORY) Slog.v(TAG, "Phone stopped scanning to: "
5357 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08005358 newHistory = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005359 mPhoneSignalScanningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005360 }
5361 }
5362
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005363 if (mPhoneServiceState != state) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005364 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_STATE_MASK)
5365 | (state << HistoryItem.STATE_PHONE_STATE_SHIFT);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005366 if (DEBUG_HISTORY) Slog.v(TAG, "Phone state " + state + " to: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005367 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08005368 newHistory = true;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005369 mPhoneServiceState = state;
5370 }
Dianne Hackborne4a59512010-12-07 11:08:07 -08005371
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005372 if (mPhoneSignalStrengthBin != strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005373 if (mPhoneSignalStrengthBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005374 mPhoneSignalStrengthsTimer[mPhoneSignalStrengthBin].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005375 elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005376 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005377 if (strengthBin >= 0) {
5378 if (!mPhoneSignalStrengthsTimer[strengthBin].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005379 mPhoneSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005380 }
Dianne Hackborn3251b902014-06-20 14:40:53 -07005381 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_MASK)
5382 | (strengthBin << HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_SHIFT);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005383 if (DEBUG_HISTORY) Slog.v(TAG, "Signal strength " + strengthBin + " to: "
Dianne Hackborne4a59512010-12-07 11:08:07 -08005384 + Integer.toHexString(mHistoryCur.states));
5385 newHistory = true;
Bookatze5885242017-10-24 20:10:31 -07005386 StatsLog.write(StatsLog.PHONE_SIGNAL_STRENGTH_CHANGED, strengthBin);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005387 } else {
Dianne Hackborn3251b902014-06-20 14:40:53 -07005388 stopAllPhoneSignalStrengthTimersLocked(-1);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005389 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005390 mPhoneSignalStrengthBin = strengthBin;
Dianne Hackborne4a59512010-12-07 11:08:07 -08005391 }
5392
5393 if (newHistory) {
Dianne Hackborn40c87252014-03-19 16:55:40 -07005394 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005395 }
5396 }
5397
5398 /**
5399 * Telephony stack updates the phone state.
5400 * @param state phone state from ServiceState.getState()
5401 */
5402 public void notePhoneStateLocked(int state, int simState) {
5403 updateAllPhoneStateLocked(state, simState, mPhoneSignalStrengthBinRaw);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07005404 }
5405
Wink Savillee9b06d72009-05-18 21:47:50 -07005406 public void notePhoneSignalStrengthLocked(SignalStrength signalStrength) {
Dianne Hackborn627bba72009-03-24 22:32:56 -07005407 // Bin the strength.
Wink Saville52840902011-02-18 12:40:47 -08005408 int bin = signalStrength.getLevel();
Dianne Hackborne4a59512010-12-07 11:08:07 -08005409 updateAllPhoneStateLocked(mPhoneServiceStateRaw, mPhoneSimStateRaw, bin);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005410 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005411
Dianne Hackborn627bba72009-03-24 22:32:56 -07005412 public void notePhoneDataConnectionStateLocked(int dataType, boolean hasData) {
Tej Singheee317b2018-03-07 19:28:05 -08005413 // BatteryStats uses 0 to represent no network type.
5414 // Telephony does not have a concept of no network type, and uses 0 to represent unknown.
5415 // Unknown is included in DATA_CONNECTION_OTHER.
Dianne Hackborn627bba72009-03-24 22:32:56 -07005416 int bin = DATA_CONNECTION_NONE;
5417 if (hasData) {
Tej Singheee317b2018-03-07 19:28:05 -08005418 if (dataType > 0 && dataType <= TelephonyManager.MAX_NETWORK_TYPE) {
5419 bin = dataType;
5420 } else {
5421 bin = DATA_CONNECTION_OTHER;
Dianne Hackborn627bba72009-03-24 22:32:56 -07005422 }
5423 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07005424 if (DEBUG) Log.i(TAG, "Phone Data Connection -> " + dataType + " = " + hasData);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005425 if (mPhoneDataConnectionType != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005426 final long elapsedRealtime = mClocks.elapsedRealtime();
5427 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005428 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_DATA_CONNECTION_MASK)
5429 | (bin << HistoryItem.STATE_DATA_CONNECTION_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005430 if (DEBUG_HISTORY) Slog.v(TAG, "Data connection " + bin + " to: "
5431 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005432 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005433 if (mPhoneDataConnectionType >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005434 mPhoneDataConnectionsTimer[mPhoneDataConnectionType].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005435 elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005436 }
5437 mPhoneDataConnectionType = bin;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005438 mPhoneDataConnectionsTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005439 }
5440 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005441
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005442 public void noteWifiOnLocked() {
The Android Open Source Project10592532009-03-18 17:39:46 -07005443 if (!mWifiOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005444 final long elapsedRealtime = mClocks.elapsedRealtime();
5445 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005446 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005447 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI on to: "
5448 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005449 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005450 mWifiOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005451 mWifiOnTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005452 scheduleSyncExternalStatsLocked("wifi-off", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07005453 }
5454 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005455
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005456 public void noteWifiOffLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08005457 final long elapsedRealtime = mClocks.elapsedRealtime();
5458 final long uptime = mClocks.uptimeMillis();
The Android Open Source Project10592532009-03-18 17:39:46 -07005459 if (mWifiOn) {
Dianne Hackborn3251b902014-06-20 14:40:53 -07005460 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005461 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI off to: "
5462 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005463 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005464 mWifiOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005465 mWifiOnTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005466 scheduleSyncExternalStatsLocked("wifi-on", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07005467 }
5468 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005469
5470 public void noteAudioOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005471 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005472 final long elapsedRealtime = mClocks.elapsedRealtime();
5473 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005474 if (mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005475 mHistoryCur.states |= HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005476 if (DEBUG_HISTORY) Slog.v(TAG, "Audio on to: "
5477 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005478 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005479 mAudioOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005480 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005481 mAudioOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005482 getUidStatsLocked(uid).noteAudioTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005483 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005484
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005485 public void noteAudioOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005486 if (mAudioOnNesting == 0) {
5487 return;
5488 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08005489 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005490 final long elapsedRealtime = mClocks.elapsedRealtime();
5491 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005492 if (--mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005493 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005494 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
5495 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005496 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005497 mAudioOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005498 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005499 getUidStatsLocked(uid).noteAudioTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005500 }
5501
5502 public void noteVideoOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005503 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005504 final long elapsedRealtime = mClocks.elapsedRealtime();
5505 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005506 if (mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005507 mHistoryCur.states2 |= HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005508 if (DEBUG_HISTORY) Slog.v(TAG, "Video on to: "
5509 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005510 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005511 mVideoOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005512 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005513 mVideoOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005514 getUidStatsLocked(uid).noteVideoTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005515 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005516
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005517 public void noteVideoOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005518 if (mVideoOnNesting == 0) {
5519 return;
5520 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08005521 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005522 final long elapsedRealtime = mClocks.elapsedRealtime();
5523 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005524 if (--mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005525 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005526 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
5527 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005528 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005529 mVideoOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005530 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005531 getUidStatsLocked(uid).noteVideoTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005532 }
5533
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005534 public void noteResetAudioLocked() {
5535 if (mAudioOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005536 final long elapsedRealtime = mClocks.elapsedRealtime();
5537 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005538 mAudioOnNesting = 0;
5539 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
5540 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
5541 + Integer.toHexString(mHistoryCur.states));
5542 addHistoryRecordLocked(elapsedRealtime, uptime);
5543 mAudioOnTimer.stopAllRunningLocked(elapsedRealtime);
5544 for (int i=0; i<mUidStats.size(); i++) {
5545 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5546 uid.noteResetAudioLocked(elapsedRealtime);
5547 }
5548 }
5549 }
5550
5551 public void noteResetVideoLocked() {
5552 if (mVideoOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005553 final long elapsedRealtime = mClocks.elapsedRealtime();
5554 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005555 mAudioOnNesting = 0;
5556 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
5557 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
5558 + Integer.toHexString(mHistoryCur.states));
5559 addHistoryRecordLocked(elapsedRealtime, uptime);
5560 mVideoOnTimer.stopAllRunningLocked(elapsedRealtime);
5561 for (int i=0; i<mUidStats.size(); i++) {
5562 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5563 uid.noteResetVideoLocked(elapsedRealtime);
5564 }
5565 }
5566 }
5567
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005568 public void noteActivityResumedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005569 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005570 getUidStatsLocked(uid).noteActivityResumedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005571 }
5572
5573 public void noteActivityPausedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005574 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005575 getUidStatsLocked(uid).noteActivityPausedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005576 }
5577
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005578 public void noteVibratorOnLocked(int uid, long durationMillis) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005579 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005580 getUidStatsLocked(uid).noteVibratorOnLocked(durationMillis);
5581 }
5582
5583 public void noteVibratorOffLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005584 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005585 getUidStatsLocked(uid).noteVibratorOffLocked();
5586 }
5587
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005588 public void noteFlashlightOnLocked(int uid) {
5589 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005590 final long elapsedRealtime = mClocks.elapsedRealtime();
5591 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005592 if (mFlashlightOnNesting++ == 0) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005593 mHistoryCur.states2 |= HistoryItem.STATE2_FLASHLIGHT_FLAG;
5594 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight on to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005595 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005596 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005597 mFlashlightOnTimer.startRunningLocked(elapsedRealtime);
5598 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005599 getUidStatsLocked(uid).noteFlashlightTurnedOnLocked(elapsedRealtime);
5600 }
5601
5602 public void noteFlashlightOffLocked(int uid) {
5603 if (mFlashlightOnNesting == 0) {
5604 return;
5605 }
5606 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005607 final long elapsedRealtime = mClocks.elapsedRealtime();
5608 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005609 if (--mFlashlightOnNesting == 0) {
5610 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
5611 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
5612 + Integer.toHexString(mHistoryCur.states2));
5613 addHistoryRecordLocked(elapsedRealtime, uptime);
5614 mFlashlightOnTimer.stopRunningLocked(elapsedRealtime);
5615 }
5616 getUidStatsLocked(uid).noteFlashlightTurnedOffLocked(elapsedRealtime);
5617 }
5618
5619 public void noteCameraOnLocked(int uid) {
5620 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005621 final long elapsedRealtime = mClocks.elapsedRealtime();
5622 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005623 if (mCameraOnNesting++ == 0) {
5624 mHistoryCur.states2 |= HistoryItem.STATE2_CAMERA_FLAG;
5625 if (DEBUG_HISTORY) Slog.v(TAG, "Camera on to: "
5626 + Integer.toHexString(mHistoryCur.states2));
5627 addHistoryRecordLocked(elapsedRealtime, uptime);
5628 mCameraOnTimer.startRunningLocked(elapsedRealtime);
5629 }
5630 getUidStatsLocked(uid).noteCameraTurnedOnLocked(elapsedRealtime);
5631 }
5632
5633 public void noteCameraOffLocked(int uid) {
5634 if (mCameraOnNesting == 0) {
5635 return;
5636 }
5637 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005638 final long elapsedRealtime = mClocks.elapsedRealtime();
5639 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005640 if (--mCameraOnNesting == 0) {
5641 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
5642 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
5643 + Integer.toHexString(mHistoryCur.states2));
5644 addHistoryRecordLocked(elapsedRealtime, uptime);
5645 mCameraOnTimer.stopRunningLocked(elapsedRealtime);
5646 }
5647 getUidStatsLocked(uid).noteCameraTurnedOffLocked(elapsedRealtime);
5648 }
5649
5650 public void noteResetCameraLocked() {
5651 if (mCameraOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005652 final long elapsedRealtime = mClocks.elapsedRealtime();
5653 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005654 mCameraOnNesting = 0;
5655 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
5656 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
5657 + Integer.toHexString(mHistoryCur.states2));
5658 addHistoryRecordLocked(elapsedRealtime, uptime);
5659 mCameraOnTimer.stopAllRunningLocked(elapsedRealtime);
5660 for (int i=0; i<mUidStats.size(); i++) {
5661 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5662 uid.noteResetCameraLocked(elapsedRealtime);
5663 }
5664 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005665 }
5666
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005667 public void noteResetFlashlightLocked() {
5668 if (mFlashlightOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005669 final long elapsedRealtime = mClocks.elapsedRealtime();
5670 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005671 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005672 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
5673 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005674 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005675 addHistoryRecordLocked(elapsedRealtime, uptime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005676 mFlashlightOnTimer.stopAllRunningLocked(elapsedRealtime);
5677 for (int i=0; i<mUidStats.size(); i++) {
5678 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5679 uid.noteResetFlashlightLocked(elapsedRealtime);
5680 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005681 }
5682 }
5683
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005684 private void noteBluetoothScanStartedLocked(WorkChain workChain, int uid,
5685 boolean isUnoptimized) {
5686 uid = getAttributionUid(uid, workChain);
Bookatz867c0d72017-03-07 18:23:42 -08005687 final long elapsedRealtime = mClocks.elapsedRealtime();
5688 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005689 if (mBluetoothScanNesting == 0) {
5690 mHistoryCur.states2 |= HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5691 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan started for: "
5692 + Integer.toHexString(mHistoryCur.states2));
5693 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005694 mBluetoothScanTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005695 }
5696 mBluetoothScanNesting++;
Bookatzb1f04f32017-05-19 13:57:32 -07005697 getUidStatsLocked(uid).noteBluetoothScanStartedLocked(elapsedRealtime, isUnoptimized);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005698 }
5699
Bookatzb1f04f32017-05-19 13:57:32 -07005700 public void noteBluetoothScanStartedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005701 final int N = ws.size();
5702 for (int i = 0; i < N; i++) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005703 noteBluetoothScanStartedLocked(null, ws.get(i), isUnoptimized);
5704 }
5705
5706 final List<WorkChain> workChains = ws.getWorkChains();
5707 if (workChains != null) {
5708 for (int i = 0; i < workChains.size(); ++i) {
5709 noteBluetoothScanStartedLocked(workChains.get(i), -1, isUnoptimized);
5710 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005711 }
5712 }
5713
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005714 private void noteBluetoothScanStoppedLocked(WorkChain workChain, int uid,
5715 boolean isUnoptimized) {
5716 uid = getAttributionUid(uid, workChain);
Bookatz867c0d72017-03-07 18:23:42 -08005717 final long elapsedRealtime = mClocks.elapsedRealtime();
5718 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005719 mBluetoothScanNesting--;
5720 if (mBluetoothScanNesting == 0) {
5721 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5722 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan stopped for: "
5723 + Integer.toHexString(mHistoryCur.states2));
5724 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005725 mBluetoothScanTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005726 }
Bookatz94c5a312017-07-11 16:49:17 -07005727 getUidStatsLocked(uid).noteBluetoothScanStoppedLocked(elapsedRealtime, isUnoptimized);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005728 }
5729
5730 private int getAttributionUid(int uid, WorkChain workChain) {
5731 if (workChain != null) {
5732 return mapUid(workChain.getAttributionUid());
5733 }
5734
5735 return mapUid(uid);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005736 }
5737
Bookatz94c5a312017-07-11 16:49:17 -07005738 public void noteBluetoothScanStoppedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005739 final int N = ws.size();
5740 for (int i = 0; i < N; i++) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005741 noteBluetoothScanStoppedLocked(null, ws.get(i), isUnoptimized);
5742 }
5743
5744 final List<WorkChain> workChains = ws.getWorkChains();
5745 if (workChains != null) {
5746 for (int i = 0; i < workChains.size(); ++i) {
5747 noteBluetoothScanStoppedLocked(workChains.get(i), -1, isUnoptimized);
5748 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005749 }
5750 }
5751
5752 public void noteResetBluetoothScanLocked() {
5753 if (mBluetoothScanNesting > 0) {
Bookatz867c0d72017-03-07 18:23:42 -08005754 final long elapsedRealtime = mClocks.elapsedRealtime();
5755 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005756 mBluetoothScanNesting = 0;
5757 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5758 if (DEBUG_HISTORY) Slog.v(TAG, "BLE can stopped for: "
5759 + Integer.toHexString(mHistoryCur.states2));
5760 addHistoryRecordLocked(elapsedRealtime, uptime);
5761 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtime);
5762 for (int i=0; i<mUidStats.size(); i++) {
5763 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5764 uid.noteResetBluetoothScanLocked(elapsedRealtime);
5765 }
5766 }
5767 }
5768
Bookatz4ebc0642017-05-11 12:21:19 -07005769 public void noteBluetoothScanResultsFromSourceLocked(WorkSource ws, int numNewResults) {
Bookatz956f36bf2017-04-28 09:48:17 -07005770 final int N = ws.size();
5771 for (int i = 0; i < N; i++) {
5772 int uid = mapUid(ws.get(i));
Bookatz4ebc0642017-05-11 12:21:19 -07005773 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Yangster-mac2f5daec2018-01-16 10:23:15 -08005774 StatsLog.write_non_chained(StatsLog.BLE_SCAN_RESULT_RECEIVED, ws.get(i), ws.getName(i),
5775 numNewResults);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005776 }
5777
5778 final List<WorkChain> workChains = ws.getWorkChains();
5779 if (workChains != null) {
5780 for (int i = 0; i < workChains.size(); ++i) {
5781 final WorkChain wc = workChains.get(i);
5782 int uid = mapUid(wc.getAttributionUid());
5783 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Yangster-macafad8c62018-01-05 22:30:49 -08005784 StatsLog.write(StatsLog.BLE_SCAN_RESULT_RECEIVED,
5785 wc.getUids(), wc.getTags(), numNewResults);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005786 }
Bookatz956f36bf2017-04-28 09:48:17 -07005787 }
5788 }
5789
Adam Lesinski5f056f62016-07-14 16:56:08 -07005790 private void noteWifiRadioApWakeupLocked(final long elapsedRealtimeMillis,
5791 final long uptimeMillis, int uid) {
5792 uid = mapUid(uid);
5793 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
5794 uid);
5795 getUidStatsLocked(uid).noteWifiRadioApWakeupLocked();
5796 }
5797
5798 public void noteWifiRadioPowerState(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005799 final long elapsedRealtime = mClocks.elapsedRealtime();
5800 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005801 if (mWifiRadioPowerState != powerState) {
5802 final boolean active =
5803 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
5804 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
5805 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07005806 if (uid > 0) {
5807 noteWifiRadioApWakeupLocked(elapsedRealtime, uptime, uid);
5808 }
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005809 mHistoryCur.states |= HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
Siddharth Rayb50a6842017-12-14 15:15:28 -08005810 mWifiActiveTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005811 } else {
5812 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
Siddharth Rayb50a6842017-12-14 15:15:28 -08005813 mWifiActiveTimer.stopRunningLocked(
5814 timestampNs / (1000 * 1000));
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005815 }
5816 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi network active " + active + " to: "
5817 + Integer.toHexString(mHistoryCur.states));
5818 addHistoryRecordLocked(elapsedRealtime, uptime);
5819 mWifiRadioPowerState = powerState;
Bookatzddccf0a2017-11-28 16:48:14 -08005820 StatsLog.write(StatsLog.WIFI_RADIO_POWER_STATE_CHANGED, uid, powerState);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005821 }
5822 }
5823
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005824 public void noteWifiRunningLocked(WorkSource ws) {
5825 if (!mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005826 final long elapsedRealtime = mClocks.elapsedRealtime();
5827 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005828 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005829 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI running to: "
5830 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005831 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005832 mGlobalWifiRunning = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005833 mGlobalWifiRunningTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005834 int N = ws.size();
5835 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005836 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005837 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005838 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005839
5840 List<WorkChain> workChains = ws.getWorkChains();
5841 if (workChains != null) {
5842 for (int i = 0; i < workChains.size(); ++i) {
5843 int uid = mapUid(workChains.get(i).getAttributionUid());
5844 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
5845 }
5846 }
5847
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005848 scheduleSyncExternalStatsLocked("wifi-running", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005849 } else {
5850 Log.w(TAG, "noteWifiRunningLocked -- called while WIFI running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005851 }
5852 }
5853
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005854 public void noteWifiRunningChangedLocked(WorkSource oldWs, WorkSource newWs) {
5855 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005856 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005857 int N = oldWs.size();
5858 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005859 int uid = mapUid(oldWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005860 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005861 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005862
5863 List<WorkChain> workChains = oldWs.getWorkChains();
5864 if (workChains != null) {
5865 for (int i = 0; i < workChains.size(); ++i) {
5866 int uid = mapUid(workChains.get(i).getAttributionUid());
5867 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
5868 }
5869 }
5870
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005871 N = newWs.size();
5872 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005873 int uid = mapUid(newWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005874 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005875 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005876
5877 workChains = newWs.getWorkChains();
5878 if (workChains != null) {
5879 for (int i = 0; i < workChains.size(); ++i) {
5880 int uid = mapUid(workChains.get(i).getAttributionUid());
5881 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
5882 }
5883 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005884 } else {
5885 Log.w(TAG, "noteWifiRunningChangedLocked -- called while WIFI not running");
5886 }
5887 }
5888
5889 public void noteWifiStoppedLocked(WorkSource ws) {
5890 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005891 final long elapsedRealtime = mClocks.elapsedRealtime();
5892 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005893 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005894 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI stopped to: "
5895 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005896 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005897 mGlobalWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005898 mGlobalWifiRunningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005899 int N = ws.size();
5900 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005901 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005902 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005903 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005904
5905 List<WorkChain> workChains = ws.getWorkChains();
5906 if (workChains != null) {
5907 for (int i = 0; i < workChains.size(); ++i) {
5908 int uid = mapUid(workChains.get(i).getAttributionUid());
5909 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
5910 }
5911 }
5912
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005913 scheduleSyncExternalStatsLocked("wifi-stopped", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005914 } else {
5915 Log.w(TAG, "noteWifiStoppedLocked -- called while WIFI not running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005916 }
5917 }
5918
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005919 public void noteWifiStateLocked(int wifiState, String accessPoint) {
5920 if (DEBUG) Log.i(TAG, "WiFi state -> " + wifiState);
5921 if (mWifiState != wifiState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005922 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005923 if (mWifiState >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005924 mWifiStateTimer[mWifiState].stopRunningLocked(elapsedRealtime);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005925 }
5926 mWifiState = wifiState;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005927 mWifiStateTimer[wifiState].startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005928 scheduleSyncExternalStatsLocked("wifi-state", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005929 }
5930 }
5931
Dianne Hackborn3251b902014-06-20 14:40:53 -07005932 public void noteWifiSupplicantStateChangedLocked(int supplState, boolean failedAuth) {
5933 if (DEBUG) Log.i(TAG, "WiFi suppl state -> " + supplState);
5934 if (mWifiSupplState != supplState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005935 final long elapsedRealtime = mClocks.elapsedRealtime();
5936 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005937 if (mWifiSupplState >= 0) {
5938 mWifiSupplStateTimer[mWifiSupplState].stopRunningLocked(elapsedRealtime);
5939 }
5940 mWifiSupplState = supplState;
5941 mWifiSupplStateTimer[supplState].startRunningLocked(elapsedRealtime);
5942 mHistoryCur.states2 =
5943 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SUPPL_STATE_MASK)
5944 | (supplState << HistoryItem.STATE2_WIFI_SUPPL_STATE_SHIFT);
5945 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi suppl state " + supplState + " to: "
5946 + Integer.toHexString(mHistoryCur.states2));
5947 addHistoryRecordLocked(elapsedRealtime, uptime);
5948 }
5949 }
5950
5951 void stopAllWifiSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005952 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005953 for (int i = 0; i < NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
5954 if (i == except) {
5955 continue;
5956 }
5957 while (mWifiSignalStrengthsTimer[i].isRunningLocked()) {
5958 mWifiSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
5959 }
5960 }
5961 }
5962
5963 public void noteWifiRssiChangedLocked(int newRssi) {
5964 int strengthBin = WifiManager.calculateSignalLevel(newRssi, NUM_WIFI_SIGNAL_STRENGTH_BINS);
5965 if (DEBUG) Log.i(TAG, "WiFi rssi -> " + newRssi + " bin=" + strengthBin);
5966 if (mWifiSignalStrengthBin != strengthBin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005967 final long elapsedRealtime = mClocks.elapsedRealtime();
5968 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005969 if (mWifiSignalStrengthBin >= 0) {
5970 mWifiSignalStrengthsTimer[mWifiSignalStrengthBin].stopRunningLocked(
5971 elapsedRealtime);
5972 }
5973 if (strengthBin >= 0) {
5974 if (!mWifiSignalStrengthsTimer[strengthBin].isRunningLocked()) {
5975 mWifiSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
5976 }
5977 mHistoryCur.states2 =
5978 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_MASK)
5979 | (strengthBin << HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_SHIFT);
5980 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi signal strength " + strengthBin + " to: "
5981 + Integer.toHexString(mHistoryCur.states2));
5982 addHistoryRecordLocked(elapsedRealtime, uptime);
5983 } else {
5984 stopAllWifiSignalStrengthTimersLocked(-1);
5985 }
Bookatz235343d2018-03-26 13:03:50 -07005986 StatsLog.write(StatsLog.WIFI_SIGNAL_STRENGTH_CHANGED, strengthBin);
Dianne Hackborn3251b902014-06-20 14:40:53 -07005987 mWifiSignalStrengthBin = strengthBin;
5988 }
5989 }
5990
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005991 int mWifiFullLockNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005992
The Android Open Source Project10592532009-03-18 17:39:46 -07005993 public void noteFullWifiLockAcquiredLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005994 final long elapsedRealtime = mClocks.elapsedRealtime();
5995 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005996 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005997 mHistoryCur.states |= HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005998 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock on to: "
5999 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006000 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006001 }
6002 mWifiFullLockNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006003 getUidStatsLocked(uid).noteFullWifiLockAcquiredLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006004 }
6005
6006 public void noteFullWifiLockReleasedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006007 final long elapsedRealtime = mClocks.elapsedRealtime();
6008 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006009 mWifiFullLockNesting--;
6010 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006011 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006012 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock off to: "
6013 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006014 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006015 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006016 getUidStatsLocked(uid).noteFullWifiLockReleasedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006017 }
6018
Nick Pelly6ccaa542012-06-15 15:22:47 -07006019 int mWifiScanNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006020
Nick Pelly6ccaa542012-06-15 15:22:47 -07006021 public void noteWifiScanStartedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006022 final long elapsedRealtime = mClocks.elapsedRealtime();
6023 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07006024 if (mWifiScanNesting == 0) {
6025 mHistoryCur.states |= HistoryItem.STATE_WIFI_SCAN_FLAG;
6026 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan started for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006027 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006028 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006029 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07006030 mWifiScanNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006031 getUidStatsLocked(uid).noteWifiScanStartedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006032 }
6033
Nick Pelly6ccaa542012-06-15 15:22:47 -07006034 public void noteWifiScanStoppedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006035 final long elapsedRealtime = mClocks.elapsedRealtime();
6036 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07006037 mWifiScanNesting--;
6038 if (mWifiScanNesting == 0) {
6039 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_SCAN_FLAG;
6040 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan stopped for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006041 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006042 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006043 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006044 getUidStatsLocked(uid).noteWifiScanStoppedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006045 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006046
Robert Greenwalta029ea12013-09-25 16:38:12 -07006047 public void noteWifiBatchedScanStartedLocked(int uid, int csph) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006048 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006049 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006050 getUidStatsLocked(uid).noteWifiBatchedScanStartedLocked(csph, elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006051 }
6052
6053 public void noteWifiBatchedScanStoppedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006054 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006055 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006056 getUidStatsLocked(uid).noteWifiBatchedScanStoppedLocked(elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006057 }
6058
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006059 int mWifiMulticastNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006060
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006061 public void noteWifiMulticastEnabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006062 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006063 final long elapsedRealtime = mClocks.elapsedRealtime();
6064 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006065 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006066 mHistoryCur.states |= HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006067 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast on to: "
6068 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006069 addHistoryRecordLocked(elapsedRealtime, uptime);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006070
6071 // Start Wifi Multicast overall timer
6072 if (!mWifiMulticastWakelockTimer.isRunningLocked()) {
6073 if (DEBUG_HISTORY) Slog.v(TAG, "WiFi Multicast Overall Timer Started");
6074 mWifiMulticastWakelockTimer.startRunningLocked(elapsedRealtime);
6075 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006076 }
6077 mWifiMulticastNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006078 getUidStatsLocked(uid).noteWifiMulticastEnabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006079 }
6080
6081 public void noteWifiMulticastDisabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006082 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006083 final long elapsedRealtime = mClocks.elapsedRealtime();
6084 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006085 mWifiMulticastNesting--;
6086 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006087 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006088 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast off to: "
6089 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006090 addHistoryRecordLocked(elapsedRealtime, uptime);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006091
6092 // Stop Wifi Multicast overall timer
6093 if (mWifiMulticastWakelockTimer.isRunningLocked()) {
6094 if (DEBUG_HISTORY) Slog.v(TAG, "Multicast Overall Timer Stopped");
6095 mWifiMulticastWakelockTimer.stopRunningLocked(elapsedRealtime);
6096 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006097 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006098 getUidStatsLocked(uid).noteWifiMulticastDisabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006099 }
6100
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006101 public void noteFullWifiLockAcquiredFromSourceLocked(WorkSource ws) {
6102 int N = ws.size();
6103 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006104 final int uid = mapUid(ws.get(i));
6105 noteFullWifiLockAcquiredLocked(uid);
Bookatz90867622018-01-31 15:05:57 -08006106 StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, ws.get(i), ws.getName(i),
6107 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006108 }
6109
6110 final List<WorkChain> workChains = ws.getWorkChains();
6111 if (workChains != null) {
6112 for (int i = 0; i < workChains.size(); ++i) {
6113 final WorkChain workChain = workChains.get(i);
6114 final int uid = mapUid(workChain.getAttributionUid());
6115 noteFullWifiLockAcquiredLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006116 StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006117 workChain.getUids(), workChain.getTags(),
6118 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006119 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006120 }
6121 }
6122
6123 public void noteFullWifiLockReleasedFromSourceLocked(WorkSource ws) {
6124 int N = ws.size();
6125 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006126 final int uid = mapUid(ws.get(i));
6127 noteFullWifiLockReleasedLocked(uid);
Bookatz90867622018-01-31 15:05:57 -08006128 StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, ws.get(i), ws.getName(i),
6129 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006130 }
6131
6132 final List<WorkChain> workChains = ws.getWorkChains();
6133 if (workChains != null) {
6134 for (int i = 0; i < workChains.size(); ++i) {
6135 final WorkChain workChain = workChains.get(i);
6136 final int uid = mapUid(workChain.getAttributionUid());
6137 noteFullWifiLockReleasedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006138 StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006139 workChain.getUids(), workChain.getTags(),
6140 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006141 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006142 }
6143 }
6144
Nick Pelly6ccaa542012-06-15 15:22:47 -07006145 public void noteWifiScanStartedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006146 int N = ws.size();
6147 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006148 final int uid = mapUid(ws.get(i));
6149 noteWifiScanStartedLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08006150 StatsLog.write_non_chained(StatsLog.WIFI_SCAN_STATE_CHANGED, ws.get(i), ws.getName(i),
Bookatz90867622018-01-31 15:05:57 -08006151 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006152 }
6153
6154 final List<WorkChain> workChains = ws.getWorkChains();
6155 if (workChains != null) {
6156 for (int i = 0; i < workChains.size(); ++i) {
6157 final WorkChain workChain = workChains.get(i);
6158 final int uid = mapUid(workChain.getAttributionUid());
6159 noteWifiScanStartedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006160 StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED, workChain.getUids(),
Bookatz90867622018-01-31 15:05:57 -08006161 workChain.getTags(), StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006162 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006163 }
6164 }
6165
Nick Pelly6ccaa542012-06-15 15:22:47 -07006166 public void noteWifiScanStoppedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006167 int N = ws.size();
6168 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006169 final int uid = mapUid(ws.get(i));
6170 noteWifiScanStoppedLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08006171 StatsLog.write_non_chained(StatsLog.WIFI_SCAN_STATE_CHANGED, ws.get(i), ws.getName(i),
Bookatz90867622018-01-31 15:05:57 -08006172 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006173 }
6174
6175 final List<WorkChain> workChains = ws.getWorkChains();
6176 if (workChains != null) {
6177 for (int i = 0; i < workChains.size(); ++i) {
6178 final WorkChain workChain = workChains.get(i);
6179 final int uid = mapUid(workChain.getAttributionUid());
6180 noteWifiScanStoppedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006181 StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006182 workChain.getUids(), workChain.getTags(),
6183 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006184 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006185 }
6186 }
6187
Robert Greenwalta029ea12013-09-25 16:38:12 -07006188 public void noteWifiBatchedScanStartedFromSourceLocked(WorkSource ws, int csph) {
6189 int N = ws.size();
6190 for (int i=0; i<N; i++) {
6191 noteWifiBatchedScanStartedLocked(ws.get(i), csph);
6192 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00006193
6194 final List<WorkChain> workChains = ws.getWorkChains();
6195 if (workChains != null) {
6196 for (int i = 0; i < workChains.size(); ++i) {
6197 noteWifiBatchedScanStartedLocked(workChains.get(i).getAttributionUid(), csph);
6198 }
6199 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006200 }
6201
6202 public void noteWifiBatchedScanStoppedFromSourceLocked(WorkSource ws) {
6203 int N = ws.size();
6204 for (int i=0; i<N; i++) {
6205 noteWifiBatchedScanStoppedLocked(ws.get(i));
6206 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00006207
6208 final List<WorkChain> workChains = ws.getWorkChains();
6209 if (workChains != null) {
6210 for (int i = 0; i < workChains.size(); ++i) {
6211 noteWifiBatchedScanStoppedLocked(workChains.get(i).getAttributionUid());
6212 }
6213 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006214 }
6215
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08006216 private static String[] includeInStringArray(String[] array, String str) {
6217 if (ArrayUtils.indexOf(array, str) >= 0) {
6218 return array;
6219 }
6220 String[] newArray = new String[array.length+1];
6221 System.arraycopy(array, 0, newArray, 0, array.length);
6222 newArray[array.length] = str;
6223 return newArray;
6224 }
6225
6226 private static String[] excludeFromStringArray(String[] array, String str) {
6227 int index = ArrayUtils.indexOf(array, str);
6228 if (index >= 0) {
6229 String[] newArray = new String[array.length-1];
6230 if (index > 0) {
6231 System.arraycopy(array, 0, newArray, 0, index);
6232 }
6233 if (index < array.length-1) {
6234 System.arraycopy(array, index+1, newArray, index, array.length-index-1);
6235 }
6236 return newArray;
6237 }
6238 return array;
6239 }
6240
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07006241 public void noteNetworkInterfaceTypeLocked(String iface, int networkType) {
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07006242 if (TextUtils.isEmpty(iface)) return;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006243
Adam Lesinski14ae39a2017-05-26 11:50:40 -07006244 synchronized (mModemNetworkLock) {
6245 if (ConnectivityManager.isNetworkTypeMobile(networkType)) {
6246 mModemIfaces = includeInStringArray(mModemIfaces, iface);
6247 if (DEBUG) Slog.d(TAG, "Note mobile iface " + iface + ": " + mModemIfaces);
6248 } else {
6249 mModemIfaces = excludeFromStringArray(mModemIfaces, iface);
6250 if (DEBUG) Slog.d(TAG, "Note non-mobile iface " + iface + ": " + mModemIfaces);
6251 }
6252 }
6253
6254 synchronized (mWifiNetworkLock) {
6255 if (ConnectivityManager.isNetworkTypeWifi(networkType)) {
6256 mWifiIfaces = includeInStringArray(mWifiIfaces, iface);
6257 if (DEBUG) Slog.d(TAG, "Note wifi iface " + iface + ": " + mWifiIfaces);
6258 } else {
6259 mWifiIfaces = excludeFromStringArray(mWifiIfaces, iface);
6260 if (DEBUG) Slog.d(TAG, "Note non-wifi iface " + iface + ": " + mWifiIfaces);
6261 }
6262 }
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07006263 }
6264
David Chenc8a43242017-10-17 16:23:28 -07006265 public String[] getWifiIfaces() {
6266 synchronized (mWifiNetworkLock) {
6267 return mWifiIfaces;
6268 }
6269 }
6270
6271 public String[] getMobileIfaces() {
6272 synchronized (mModemNetworkLock) {
6273 return mModemIfaces;
6274 }
6275 }
6276
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006277 @Override public long getScreenOnTime(long elapsedRealtimeUs, int which) {
6278 return mScreenOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006279 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006280
Dianne Hackborn77b987f2014-02-26 16:20:52 -08006281 @Override public int getScreenOnCount(int which) {
6282 return mScreenOnTimer.getCountLocked(which);
6283 }
6284
Mike Mac2f518a2017-09-19 16:06:03 -07006285 @Override public long getScreenDozeTime(long elapsedRealtimeUs, int which) {
6286 return mScreenDozeTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6287 }
6288
6289 @Override public int getScreenDozeCount(int which) {
6290 return mScreenDozeTimer.getCountLocked(which);
6291 }
6292
Dianne Hackborn617f8772009-03-31 15:04:46 -07006293 @Override public long getScreenBrightnessTime(int brightnessBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006294 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006295 return mScreenBrightnessTimer[brightnessBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006296 elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006297 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006298
Kweku Adams87b19ec2017-10-09 12:40:03 -07006299 @Override public Timer getScreenBrightnessTimer(int brightnessBin) {
6300 return mScreenBrightnessTimer[brightnessBin];
6301 }
6302
Jeff Browne95c3cd2014-05-02 16:59:26 -07006303 @Override public long getInteractiveTime(long elapsedRealtimeUs, int which) {
6304 return mInteractiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006305 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006306
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006307 @Override public long getPowerSaveModeEnabledTime(long elapsedRealtimeUs, int which) {
6308 return mPowerSaveModeEnabledTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07006309 }
6310
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006311 @Override public int getPowerSaveModeEnabledCount(int which) {
6312 return mPowerSaveModeEnabledTimer.getCountLocked(which);
6313 }
6314
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006315 @Override public long getDeviceIdleModeTime(int mode, long elapsedRealtimeUs,
6316 int which) {
6317 switch (mode) {
6318 case DEVICE_IDLE_MODE_LIGHT:
6319 return mDeviceIdleModeLightTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006320 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006321 return mDeviceIdleModeFullTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6322 }
6323 return 0;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006324 }
6325
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006326 @Override public int getDeviceIdleModeCount(int mode, int which) {
6327 switch (mode) {
6328 case DEVICE_IDLE_MODE_LIGHT:
6329 return mDeviceIdleModeLightTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006330 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006331 return mDeviceIdleModeFullTimer.getCountLocked(which);
6332 }
6333 return 0;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07006334 }
6335
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006336 @Override public long getLongestDeviceIdleModeTime(int mode) {
6337 switch (mode) {
6338 case DEVICE_IDLE_MODE_LIGHT:
6339 return mLongestLightIdleTime;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006340 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006341 return mLongestFullIdleTime;
6342 }
6343 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07006344 }
6345
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006346 @Override public long getDeviceIdlingTime(int mode, long elapsedRealtimeUs, int which) {
6347 switch (mode) {
6348 case DEVICE_IDLE_MODE_LIGHT:
6349 return mDeviceLightIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006350 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006351 return mDeviceIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6352 }
6353 return 0;
6354 }
6355
6356 @Override public int getDeviceIdlingCount(int mode, int which) {
6357 switch (mode) {
6358 case DEVICE_IDLE_MODE_LIGHT:
6359 return mDeviceLightIdlingTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006360 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006361 return mDeviceIdlingTimer.getCountLocked(which);
6362 }
6363 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07006364 }
6365
Dianne Hackborn1e01d162014-12-04 17:46:42 -08006366 @Override public int getNumConnectivityChange(int which) {
6367 int val = mNumConnectivityChange;
6368 if (which == STATS_CURRENT) {
6369 val -= mLoadedNumConnectivityChange;
6370 } else if (which == STATS_SINCE_UNPLUGGED) {
6371 val -= mUnpluggedNumConnectivityChange;
6372 }
6373 return val;
6374 }
6375
Siddharth Ray78ccaf52017-12-23 16:16:21 -08006376 @Override public long getGpsSignalQualityTime(int strengthBin,
6377 long elapsedRealtimeUs, int which) {
6378 if (strengthBin < 0 || strengthBin >= GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS) {
6379 return 0;
6380 }
6381 return mGpsSignalQualityTimer[strengthBin].getTotalTimeLocked(
6382 elapsedRealtimeUs, which);
6383 }
6384
6385 @Override public long getGpsBatteryDrainMaMs() {
Siddharth Ray0ed2e952018-01-22 11:32:14 -08006386 final double opVolt = mPowerProfile.getAveragePower(
6387 PowerProfile.POWER_GPS_OPERATING_VOLTAGE) / 1000.0;
6388 if (opVolt == 0) {
6389 return 0;
6390 }
6391 double energyUsedMaMs = 0.0;
6392 final int which = STATS_SINCE_CHARGED;
6393 final long rawRealtime = SystemClock.elapsedRealtime() * 1000;
6394 for(int i=0; i < GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
6395 energyUsedMaMs
6396 += mPowerProfile.getAveragePower(PowerProfile.POWER_GPS_SIGNAL_QUALITY_BASED, i)
6397 * (getGpsSignalQualityTime(i, rawRealtime, which) / 1000);
6398 }
6399 return (long) energyUsedMaMs;
Siddharth Ray78ccaf52017-12-23 16:16:21 -08006400 }
6401
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006402 @Override public long getPhoneOnTime(long elapsedRealtimeUs, int which) {
6403 return mPhoneOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006404 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006405
Dianne Hackborn77b987f2014-02-26 16:20:52 -08006406 @Override public int getPhoneOnCount(int which) {
6407 return mPhoneOnTimer.getCountLocked(which);
6408 }
6409
Dianne Hackborn627bba72009-03-24 22:32:56 -07006410 @Override public long getPhoneSignalStrengthTime(int strengthBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006411 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006412 return mPhoneSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006413 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07006414 }
Amith Yamasanif37447b2009-10-08 18:28:01 -07006415
6416 @Override public long getPhoneSignalScanningTime(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006417 long elapsedRealtimeUs, int which) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07006418 return mPhoneSignalScanningTimer.getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006419 elapsedRealtimeUs, which);
Amith Yamasanif37447b2009-10-08 18:28:01 -07006420 }
6421
Kweku Adams87b19ec2017-10-09 12:40:03 -07006422 @Override public Timer getPhoneSignalScanningTimer() {
6423 return mPhoneSignalScanningTimer;
6424 }
6425
Catherine Liufb900812012-07-17 14:12:56 -05006426 @Override public int getPhoneSignalStrengthCount(int strengthBin, int which) {
6427 return mPhoneSignalStrengthsTimer[strengthBin].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006428 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006429
Kweku Adams87b19ec2017-10-09 12:40:03 -07006430 @Override public Timer getPhoneSignalStrengthTimer(int strengthBin) {
6431 return mPhoneSignalStrengthsTimer[strengthBin];
6432 }
6433
Dianne Hackborn627bba72009-03-24 22:32:56 -07006434 @Override public long getPhoneDataConnectionTime(int dataType,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006435 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006436 return mPhoneDataConnectionsTimer[dataType].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006437 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07006438 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006439
Dianne Hackborn617f8772009-03-31 15:04:46 -07006440 @Override public int getPhoneDataConnectionCount(int dataType, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006441 return mPhoneDataConnectionsTimer[dataType].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006442 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006443
Kweku Adams87b19ec2017-10-09 12:40:03 -07006444 @Override public Timer getPhoneDataConnectionTimer(int dataType) {
6445 return mPhoneDataConnectionsTimer[dataType];
6446 }
6447
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006448 @Override public long getMobileRadioActiveTime(long elapsedRealtimeUs, int which) {
6449 return mMobileRadioActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborne13c4c02014-02-11 17:18:35 -08006450 }
6451
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006452 @Override public int getMobileRadioActiveCount(int which) {
6453 return mMobileRadioActiveTimer.getCountLocked(which);
6454 }
6455
Dianne Hackborna1bd7922014-03-21 11:07:11 -07006456 @Override public long getMobileRadioActiveAdjustedTime(int which) {
6457 return mMobileRadioActiveAdjustedTime.getCountLocked(which);
6458 }
6459
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006460 @Override public long getMobileRadioActiveUnknownTime(int which) {
6461 return mMobileRadioActiveUnknownTime.getCountLocked(which);
6462 }
6463
6464 @Override public int getMobileRadioActiveUnknownCount(int which) {
6465 return (int)mMobileRadioActiveUnknownCount.getCountLocked(which);
6466 }
6467
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006468 @Override public long getWifiMulticastWakelockTime(
6469 long elapsedRealtimeUs, int which) {
6470 return mWifiMulticastWakelockTimer.getTotalTimeLocked(
6471 elapsedRealtimeUs, which);
6472 }
6473
6474 @Override public int getWifiMulticastWakelockCount(int which) {
6475 return mWifiMulticastWakelockTimer.getCountLocked(which);
6476 }
6477
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006478 @Override public long getWifiOnTime(long elapsedRealtimeUs, int which) {
6479 return mWifiOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07006480 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006481
Siddharth Rayb50a6842017-12-14 15:15:28 -08006482 @Override public long getWifiActiveTime(long elapsedRealtimeUs, int which) {
6483 return mWifiActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6484 }
6485
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006486 @Override public long getGlobalWifiRunningTime(long elapsedRealtimeUs, int which) {
6487 return mGlobalWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07006488 }
6489
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006490 @Override public long getWifiStateTime(int wifiState,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006491 long elapsedRealtimeUs, int which) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006492 return mWifiStateTimer[wifiState].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006493 elapsedRealtimeUs, which);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006494 }
6495
6496 @Override public int getWifiStateCount(int wifiState, int which) {
6497 return mWifiStateTimer[wifiState].getCountLocked(which);
6498 }
6499
Kweku Adams87b19ec2017-10-09 12:40:03 -07006500 @Override public Timer getWifiStateTimer(int wifiState) {
6501 return mWifiStateTimer[wifiState];
6502 }
6503
Dianne Hackborn3251b902014-06-20 14:40:53 -07006504 @Override public long getWifiSupplStateTime(int state,
6505 long elapsedRealtimeUs, int which) {
6506 return mWifiSupplStateTimer[state].getTotalTimeLocked(
6507 elapsedRealtimeUs, which);
6508 }
6509
6510 @Override public int getWifiSupplStateCount(int state, int which) {
6511 return mWifiSupplStateTimer[state].getCountLocked(which);
6512 }
6513
Kweku Adams87b19ec2017-10-09 12:40:03 -07006514 @Override public Timer getWifiSupplStateTimer(int state) {
6515 return mWifiSupplStateTimer[state];
6516 }
6517
Dianne Hackborn3251b902014-06-20 14:40:53 -07006518 @Override public long getWifiSignalStrengthTime(int strengthBin,
6519 long elapsedRealtimeUs, int which) {
6520 return mWifiSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
6521 elapsedRealtimeUs, which);
6522 }
6523
6524 @Override public int getWifiSignalStrengthCount(int strengthBin, int which) {
6525 return mWifiSignalStrengthsTimer[strengthBin].getCountLocked(which);
6526 }
6527
Kweku Adams87b19ec2017-10-09 12:40:03 -07006528 @Override public Timer getWifiSignalStrengthTimer(int strengthBin) {
6529 return mWifiSignalStrengthsTimer[strengthBin];
6530 }
6531
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006532 @Override
6533 public ControllerActivityCounter getBluetoothControllerActivity() {
6534 return mBluetoothActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07006535 }
6536
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006537 @Override
6538 public ControllerActivityCounter getWifiControllerActivity() {
6539 return mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -07006540 }
6541
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006542 @Override
6543 public ControllerActivityCounter getModemControllerActivity() {
6544 return mModemActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07006545 }
6546
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006547 @Override
6548 public boolean hasBluetoothActivityReporting() {
6549 return mHasBluetoothReporting;
6550 }
6551
6552 @Override
6553 public boolean hasWifiActivityReporting() {
6554 return mHasWifiReporting;
6555 }
6556
6557 @Override
6558 public boolean hasModemActivityReporting() {
6559 return mHasModemReporting;
Adam Lesinski33dac552015-03-09 15:24:48 -07006560 }
6561
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006562 @Override
6563 public long getFlashlightOnTime(long elapsedRealtimeUs, int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07006564 return mFlashlightOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6565 }
6566
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006567 @Override
6568 public long getFlashlightOnCount(int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07006569 return mFlashlightOnTimer.getCountLocked(which);
6570 }
6571
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006572 @Override
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006573 public long getCameraOnTime(long elapsedRealtimeUs, int which) {
6574 return mCameraOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6575 }
6576
6577 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006578 public long getBluetoothScanTime(long elapsedRealtimeUs, int which) {
6579 return mBluetoothScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6580 }
6581
6582 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006583 public long getNetworkActivityBytes(int type, int which) {
6584 if (type >= 0 && type < mNetworkByteActivityCounters.length) {
6585 return mNetworkByteActivityCounters[type].getCountLocked(which);
6586 } else {
6587 return 0;
6588 }
6589 }
6590
6591 @Override
6592 public long getNetworkActivityPackets(int type, int which) {
6593 if (type >= 0 && type < mNetworkPacketActivityCounters.length) {
6594 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006595 } else {
6596 return 0;
6597 }
6598 }
6599
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08006600 @Override public long getStartClockTime() {
Dianne Hackbornd48954f2015-07-22 17:20:33 -07006601 final long currentTime = System.currentTimeMillis();
6602 if (ensureStartClockTime(currentTime)) {
Joe Onoratoabded112016-02-08 16:49:39 -08006603 recordCurrentTimeChangeLocked(currentTime, mClocks.elapsedRealtime(),
6604 mClocks.uptimeMillis());
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07006605 }
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08006606 return mStartClockTime;
6607 }
6608
Dianne Hackborncd0e3352014-08-07 17:08:09 -07006609 @Override public String getStartPlatformVersion() {
6610 return mStartPlatformVersion;
6611 }
6612
6613 @Override public String getEndPlatformVersion() {
6614 return mEndPlatformVersion;
6615 }
6616
6617 @Override public int getParcelVersion() {
6618 return VERSION;
6619 }
6620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006621 @Override public boolean getIsOnBattery() {
6622 return mOnBattery;
6623 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006625 @Override public SparseArray<? extends BatteryStats.Uid> getUidStats() {
6626 return mUidStats;
6627 }
6628
Adam Lesinski5f056f62016-07-14 16:56:08 -07006629 private static void detachTimerIfNotNull(BatteryStatsImpl.Timer timer) {
6630 if (timer != null) {
6631 timer.detach();
6632 }
6633 }
6634
6635 private static boolean resetTimerIfNotNull(BatteryStatsImpl.Timer timer,
6636 boolean detachIfReset) {
6637 if (timer != null) {
6638 return timer.reset(detachIfReset);
6639 }
6640 return true;
6641 }
6642
Bookatz867c0d72017-03-07 18:23:42 -08006643 private static boolean resetTimerIfNotNull(DualTimer timer, boolean detachIfReset) {
6644 if (timer != null) {
6645 return timer.reset(detachIfReset);
6646 }
6647 return true;
6648 }
6649
Adam Lesinski5f056f62016-07-14 16:56:08 -07006650 private static void detachLongCounterIfNotNull(LongSamplingCounter counter) {
6651 if (counter != null) {
6652 counter.detach();
6653 }
6654 }
6655
6656 private static void resetLongCounterIfNotNull(LongSamplingCounter counter,
6657 boolean detachIfReset) {
6658 if (counter != null) {
6659 counter.reset(detachIfReset);
6660 }
6661 }
6662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006663 /**
6664 * The statistics associated with a particular uid.
6665 */
Joe Onoratoabded112016-02-08 16:49:39 -08006666 public static class Uid extends BatteryStats.Uid {
6667 /**
6668 * BatteryStatsImpl that we are associated with.
6669 */
6670 protected BatteryStatsImpl mBsi;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006672 final int mUid;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006673
Bookatz867c0d72017-03-07 18:23:42 -08006674 /** TimeBase for when uid is in background and device is on battery. */
6675 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6676 public final TimeBase mOnBatteryBackgroundTimeBase;
Bookatzc8c44962017-05-11 12:12:54 -07006677 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6678 public final TimeBase mOnBatteryScreenOffBackgroundTimeBase;
Bookatz867c0d72017-03-07 18:23:42 -08006679
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006680 boolean mWifiRunning;
6681 StopwatchTimer mWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006682
The Android Open Source Project10592532009-03-18 17:39:46 -07006683 boolean mFullWifiLockOut;
Evan Millarc64edde2009-04-18 12:26:32 -07006684 StopwatchTimer mFullWifiLockTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006685
Nick Pelly6ccaa542012-06-15 15:22:47 -07006686 boolean mWifiScanStarted;
Bookatz867c0d72017-03-07 18:23:42 -08006687 DualTimer mWifiScanTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006688
Dianne Hackborn61659e52014-07-09 16:13:01 -07006689 static final int NO_BATCHED_SCAN_STARTED = -1;
Robert Greenwalta029ea12013-09-25 16:38:12 -07006690 int mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
6691 StopwatchTimer[] mWifiBatchedScanTimer;
6692
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006693 boolean mWifiMulticastEnabled;
6694 StopwatchTimer mWifiMulticastTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006695
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006696 StopwatchTimer mAudioTurnedOnTimer;
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006697 StopwatchTimer mVideoTurnedOnTimer;
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006698 StopwatchTimer mFlashlightTurnedOnTimer;
6699 StopwatchTimer mCameraTurnedOnTimer;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006700 StopwatchTimer mForegroundActivityTimer;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006701 StopwatchTimer mForegroundServiceTimer;
Bookatzc8c44962017-05-11 12:12:54 -07006702 /** Total time spent by the uid holding any partial wakelocks. */
6703 DualTimer mAggregatedPartialWakelockTimer;
Bookatz867c0d72017-03-07 18:23:42 -08006704 DualTimer mBluetoothScanTimer;
Bookatzb1f04f32017-05-19 13:57:32 -07006705 DualTimer mBluetoothUnoptimizedScanTimer;
Bookatz956f36bf2017-04-28 09:48:17 -07006706 Counter mBluetoothScanResultCounter;
Bookatzb1f04f32017-05-19 13:57:32 -07006707 Counter mBluetoothScanResultBgCounter;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006708
Dianne Hackborna8d10942015-11-19 17:55:19 -08006709 int mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07006710 StopwatchTimer[] mProcessStateTimer;
6711
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006712 boolean mInForegroundService = false;
6713
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006714 BatchTimer mVibratorOnTimer;
6715
Dianne Hackborn617f8772009-03-31 15:04:46 -07006716 Counter[] mUserActivityCounters;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006717
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006718 LongSamplingCounter[] mNetworkByteActivityCounters;
6719 LongSamplingCounter[] mNetworkPacketActivityCounters;
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006720 LongSamplingCounter mMobileRadioActiveTime;
6721 LongSamplingCounter mMobileRadioActiveCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006723 /**
Adam Lesinski5f056f62016-07-14 16:56:08 -07006724 * How many times this UID woke up the Application Processor due to a Mobile radio packet.
6725 */
6726 private LongSamplingCounter mMobileRadioApWakeupCount;
6727
6728 /**
6729 * How many times this UID woke up the Application Processor due to a Wifi packet.
6730 */
6731 private LongSamplingCounter mWifiRadioApWakeupCount;
6732
6733 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07006734 * The amount of time this uid has kept the WiFi controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006735 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07006736 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006737 private ControllerActivityCounterImpl mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006738
6739 /**
6740 * The amount of time this uid has kept the Bluetooth controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006741 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07006742 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006743 private ControllerActivityCounterImpl mBluetoothControllerActivity;
6744
6745 /**
6746 * The amount of time this uid has kept the Modem controller in idle, tx, and rx mode.
6747 * Can be null if the UID has had no such activity.
6748 */
6749 private ControllerActivityCounterImpl mModemControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006750
6751 /**
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006752 * The CPU times we had at the last history details update.
6753 */
6754 long mLastStepUserTime;
6755 long mLastStepSystemTime;
6756 long mCurStepUserTime;
6757 long mCurStepSystemTime;
6758
Joe Onoratoabded112016-02-08 16:49:39 -08006759 LongSamplingCounter mUserCpuTime;
6760 LongSamplingCounter mSystemCpuTime;
Sudheer Shankaaf857412017-07-21 00:14:24 -07006761 LongSamplingCounter[][] mCpuClusterSpeedTimesUs;
Mike Ma3d422c32017-10-25 11:08:57 -07006762 LongSamplingCounter mCpuActiveTimeMs;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006763
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006764 LongSamplingCounterArray mCpuFreqTimeMs;
6765 LongSamplingCounterArray mScreenOffCpuFreqTimeMs;
Mike Ma3d422c32017-10-25 11:08:57 -07006766 LongSamplingCounterArray mCpuClusterTimesMs;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006767
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006768 LongSamplingCounterArray[] mProcStateTimeMs;
6769 LongSamplingCounterArray[] mProcStateScreenOffTimeMs;
6770
6771 IntArray mChildUids;
6772
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006773 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006774 * The statistics we have collected for this uid's wake locks.
6775 */
Joe Onoratoabded112016-02-08 16:49:39 -08006776 final OverflowArrayMap<Wakelock> mWakelockStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006777
6778 /**
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006779 * The statistics we have collected for this uid's syncs.
6780 */
Bookatz2bffb5b2017-04-13 11:59:33 -07006781 final OverflowArrayMap<DualTimer> mSyncStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006782
6783 /**
6784 * The statistics we have collected for this uid's jobs.
6785 */
Bookatzaa4594a2017-03-24 12:39:56 -07006786 final OverflowArrayMap<DualTimer> mJobStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006787
6788 /**
Dianne Hackborn94326cb2017-06-28 16:17:20 -07006789 * Count of the jobs that have completed and the reasons why they completed.
6790 */
6791 final ArrayMap<String, SparseIntArray> mJobCompletions = new ArrayMap<>();
6792
6793 /**
Amith Yamasani977e11f2018-02-16 11:29:54 -08006794 * Count of app launch events that had associated deferred job counts or info about
6795 * last time a job was run.
6796 */
6797 Counter mJobsDeferredEventCount;
6798
6799 /**
6800 * Count of deferred jobs that were pending when the app was launched or brought to
6801 * the foreground through a user interaction.
6802 */
6803 Counter mJobsDeferredCount;
6804
6805 /**
6806 * Sum of time since the last time a job was run for this app before it was launched.
6807 */
6808 LongSamplingCounter mJobsFreshnessTimeMs;
6809
6810 /**
6811 * Array of counts of instances where the time since the last job was run for the app
6812 * fell within one of the thresholds in {@link #JOB_FRESHNESS_BUCKETS}.
6813 */
6814 final Counter[] mJobsFreshnessBuckets;
6815
6816 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006817 * The statistics we have collected for this uid's sensor activations.
6818 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006819 final SparseArray<Sensor> mSensorStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006820
6821 /**
6822 * The statistics we have collected for this uid's processes.
6823 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006824 final ArrayMap<String, Proc> mProcessStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006825
6826 /**
6827 * The statistics we have collected for this uid's processes.
6828 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006829 final ArrayMap<String, Pkg> mPackageStats = new ArrayMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006830
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006831 /**
6832 * The transient wake stats we have collected for this uid's pids.
6833 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006834 final SparseArray<Pid> mPids = new SparseArray<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006835
Joe Onoratoabded112016-02-08 16:49:39 -08006836 public Uid(BatteryStatsImpl bsi, int uid) {
6837 mBsi = bsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006838 mUid = uid;
Joe Onoratoabded112016-02-08 16:49:39 -08006839
Bookatz867c0d72017-03-07 18:23:42 -08006840 mOnBatteryBackgroundTimeBase = new TimeBase();
6841 mOnBatteryBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
6842 mBsi.mClocks.elapsedRealtime() * 1000);
6843
Bookatzc8c44962017-05-11 12:12:54 -07006844 mOnBatteryScreenOffBackgroundTimeBase = new TimeBase();
6845 mOnBatteryScreenOffBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
6846 mBsi.mClocks.elapsedRealtime() * 1000);
6847
Joe Onoratoabded112016-02-08 16:49:39 -08006848 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6849 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Mike Ma3d422c32017-10-25 11:08:57 -07006850 mCpuActiveTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6851 mCpuClusterTimesMs = new LongSamplingCounterArray(mBsi.mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006852
Dianne Hackborn657153b2016-07-29 14:54:14 -07006853 mWakelockStats = mBsi.new OverflowArrayMap<Wakelock>(uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006854 @Override public Wakelock instantiateObject() {
6855 return new Wakelock(mBsi, Uid.this);
6856 }
6857 };
Bookatz2bffb5b2017-04-13 11:59:33 -07006858 mSyncStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
6859 @Override public DualTimer instantiateObject() {
6860 return new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
6861 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006862 }
6863 };
Bookatzaa4594a2017-03-24 12:39:56 -07006864 mJobStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
6865 @Override public DualTimer instantiateObject() {
6866 return new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
6867 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006868 }
6869 };
6870
6871 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_RUNNING,
6872 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
6873 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, this, FULL_WIFI_LOCK,
6874 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Bookatz867c0d72017-03-07 18:23:42 -08006875 mWifiScanTimer = new DualTimer(mBsi.mClocks, this, WIFI_SCAN,
6876 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006877 mWifiBatchedScanTimer = new StopwatchTimer[NUM_WIFI_BATCHED_SCAN_BINS];
Joe Onoratoabded112016-02-08 16:49:39 -08006878 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_MULTICAST_ENABLED,
6879 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006880 mProcessStateTimer = new StopwatchTimer[NUM_PROCESS_STATE];
Amith Yamasani977e11f2018-02-16 11:29:54 -08006881 mJobsDeferredEventCount = new Counter(mBsi.mOnBatteryTimeBase);
6882 mJobsDeferredCount = new Counter(mBsi.mOnBatteryTimeBase);
6883 mJobsFreshnessTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6884 mJobsFreshnessBuckets = new Counter[JOB_FRESHNESS_BUCKETS.length];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006885 }
6886
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006887 @VisibleForTesting
6888 public void setProcessStateForTest(int procState) {
6889 mProcessState = procState;
6890 }
6891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006892 @Override
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006893 public long[] getCpuFreqTimes(int which) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006894 return nullIfAllZeros(mCpuFreqTimeMs, which);
6895 }
6896
6897 @Override
6898 public long[] getScreenOffCpuFreqTimes(int which) {
6899 return nullIfAllZeros(mScreenOffCpuFreqTimeMs, which);
6900 }
6901
6902 @Override
Mike Ma3d422c32017-10-25 11:08:57 -07006903 public long getCpuActiveTime() {
6904 return mCpuActiveTimeMs.getCountLocked(STATS_SINCE_CHARGED);
6905 }
6906
6907 @Override
6908 public long[] getCpuClusterTimes() {
6909 return nullIfAllZeros(mCpuClusterTimesMs, STATS_SINCE_CHARGED);
6910 }
6911
6912
6913 @Override
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006914 public long[] getCpuFreqTimes(int which, int procState) {
6915 if (which < 0 || which >= NUM_PROCESS_STATE) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006916 return null;
6917 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006918 if (mProcStateTimeMs == null) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006919 return null;
6920 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006921 if (!mBsi.mPerProcStateCpuTimesAvailable) {
6922 mProcStateTimeMs = null;
6923 return null;
6924 }
6925 return nullIfAllZeros(mProcStateTimeMs[procState], which);
6926 }
6927
6928 @Override
6929 public long[] getScreenOffCpuFreqTimes(int which, int procState) {
6930 if (which < 0 || which >= NUM_PROCESS_STATE) {
6931 return null;
6932 }
6933 if (mProcStateScreenOffTimeMs == null) {
6934 return null;
6935 }
6936 if (!mBsi.mPerProcStateCpuTimesAvailable) {
6937 mProcStateScreenOffTimeMs = null;
6938 return null;
6939 }
6940 return nullIfAllZeros(mProcStateScreenOffTimeMs[procState], which);
6941 }
6942
6943 public void addIsolatedUid(int isolatedUid) {
6944 if (mChildUids == null) {
6945 mChildUids = new IntArray();
6946 } else if (mChildUids.indexOf(isolatedUid) >= 0) {
6947 return;
6948 }
6949 mChildUids.add(isolatedUid);
6950 }
6951
6952 public void removeIsolatedUid(int isolatedUid) {
6953 final int idx = mChildUids == null ? -1 : mChildUids.indexOf(isolatedUid);
6954 if (idx < 0) {
6955 return;
6956 }
6957 mChildUids.remove(idx);
6958 }
6959
6960 private long[] nullIfAllZeros(LongSamplingCounterArray cpuTimesMs, int which) {
6961 if (cpuTimesMs == null) {
6962 return null;
6963 }
6964 final long[] counts = cpuTimesMs.getCountsLocked(which);
6965 if (counts == null) {
6966 return null;
6967 }
6968 // Return counts only if at least one of the elements is non-zero.
6969 for (int i = counts.length - 1; i >= 0; --i) {
6970 if (counts[i] != 0) {
6971 return counts;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006972 }
6973 }
6974 return null;
6975 }
6976
Sudheer Shankae544d162017-12-28 17:06:20 -08006977 private void addProcStateTimesMs(int procState, long[] cpuTimesMs, boolean onBattery) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006978 if (mProcStateTimeMs == null) {
6979 mProcStateTimeMs = new LongSamplingCounterArray[NUM_PROCESS_STATE];
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006980 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006981 if (mProcStateTimeMs[procState] == null
6982 || mProcStateTimeMs[procState].getSize() != cpuTimesMs.length) {
6983 mProcStateTimeMs[procState] = new LongSamplingCounterArray(
6984 mBsi.mOnBatteryTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006985 }
Sudheer Shankae544d162017-12-28 17:06:20 -08006986 mProcStateTimeMs[procState].addCountLocked(cpuTimesMs, onBattery);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006987 }
6988
Sudheer Shankae544d162017-12-28 17:06:20 -08006989 private void addProcStateScreenOffTimesMs(int procState, long[] cpuTimesMs,
6990 boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006991 if (mProcStateScreenOffTimeMs == null) {
6992 mProcStateScreenOffTimeMs = new LongSamplingCounterArray[NUM_PROCESS_STATE];
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006993 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006994 if (mProcStateScreenOffTimeMs[procState] == null
6995 || mProcStateScreenOffTimeMs[procState].getSize() != cpuTimesMs.length) {
6996 mProcStateScreenOffTimeMs[procState] = new LongSamplingCounterArray(
6997 mBsi.mOnBatteryScreenOffTimeBase);
6998 }
Sudheer Shankae544d162017-12-28 17:06:20 -08006999 mProcStateScreenOffTimeMs[procState].addCountLocked(cpuTimesMs, onBatteryScreenOff);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007000 }
7001
7002 @Override
Bookatzc8c44962017-05-11 12:12:54 -07007003 public Timer getAggregatedPartialWakelockTimer() {
7004 return mAggregatedPartialWakelockTimer;
7005 }
7006
7007 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007008 public ArrayMap<String, ? extends BatteryStats.Uid.Wakelock> getWakelockStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007009 return mWakelockStats.getMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007010 }
7011
7012 @Override
Ahmed ElArabawyddd09692017-10-30 17:58:29 -07007013 public Timer getMulticastWakelockStats() {
7014 return mWifiMulticastTimer;
7015 }
7016
7017 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007018 public ArrayMap<String, ? extends BatteryStats.Timer> getSyncStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007019 return mSyncStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007020 }
7021
7022 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007023 public ArrayMap<String, ? extends BatteryStats.Timer> getJobStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007024 return mJobStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007025 }
7026
7027 @Override
Dianne Hackborn94326cb2017-06-28 16:17:20 -07007028 public ArrayMap<String, SparseIntArray> getJobCompletionStats() {
7029 return mJobCompletions;
7030 }
7031
7032 @Override
Dianne Hackborn61659e52014-07-09 16:13:01 -07007033 public SparseArray<? extends BatteryStats.Uid.Sensor> getSensorStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007034 return mSensorStats;
7035 }
7036
7037 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007038 public ArrayMap<String, ? extends BatteryStats.Uid.Proc> getProcessStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007039 return mProcessStats;
7040 }
7041
7042 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007043 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg> getPackageStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007044 return mPackageStats;
7045 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007046
7047 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007048 public int getUid() {
7049 return mUid;
7050 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007051
7052 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007053 public void noteWifiRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007054 if (!mWifiRunning) {
7055 mWifiRunning = true;
7056 if (mWifiRunningTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007057 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
7058 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007059 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007060 mWifiRunningTimer.startRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007061 }
7062 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007063
Dianne Hackborn617f8772009-03-31 15:04:46 -07007064 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007065 public void noteWifiStoppedLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007066 if (mWifiRunning) {
7067 mWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007068 mWifiRunningTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007069 }
7070 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007071
Dianne Hackborn617f8772009-03-31 15:04:46 -07007072 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007073 public void noteFullWifiLockAcquiredLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07007074 if (!mFullWifiLockOut) {
7075 mFullWifiLockOut = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007076 if (mFullWifiLockTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007077 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
7078 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007079 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007080 mFullWifiLockTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007081 }
7082 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007083
The Android Open Source Project10592532009-03-18 17:39:46 -07007084 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007085 public void noteFullWifiLockReleasedLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07007086 if (mFullWifiLockOut) {
7087 mFullWifiLockOut = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007088 mFullWifiLockTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007089 }
7090 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007091
The Android Open Source Project10592532009-03-18 17:39:46 -07007092 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007093 public void noteWifiScanStartedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007094 if (!mWifiScanStarted) {
7095 mWifiScanStarted = true;
7096 if (mWifiScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007097 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
7098 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase,
7099 mOnBatteryBackgroundTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007100 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007101 mWifiScanTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007102 }
7103 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007104
The Android Open Source Project10592532009-03-18 17:39:46 -07007105 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007106 public void noteWifiScanStoppedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007107 if (mWifiScanStarted) {
7108 mWifiScanStarted = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007109 mWifiScanTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007110 }
7111 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007112
7113 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007114 public void noteWifiBatchedScanStartedLocked(int csph, long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007115 int bin = 0;
Navtej Singh Mann3c0ce5c2015-06-11 16:53:11 -07007116 while (csph > 8 && bin < NUM_WIFI_BATCHED_SCAN_BINS-1) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007117 csph = csph >> 3;
7118 bin++;
7119 }
7120
7121 if (mWifiBatchedScanBinStarted == bin) return;
7122
7123 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
7124 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007125 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007126 }
7127 mWifiBatchedScanBinStarted = bin;
7128 if (mWifiBatchedScanTimer[bin] == null) {
7129 makeWifiBatchedScanBin(bin, null);
7130 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007131 mWifiBatchedScanTimer[bin].startRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007132 }
7133
7134 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007135 public void noteWifiBatchedScanStoppedLocked(long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007136 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
7137 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007138 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007139 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
7140 }
7141 }
7142
7143 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007144 public void noteWifiMulticastEnabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007145 if (!mWifiMulticastEnabled) {
7146 mWifiMulticastEnabled = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007147 if (mWifiMulticastTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007148 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7149 WIFI_MULTICAST_ENABLED, mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007150 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007151 mWifiMulticastTimer.startRunningLocked(elapsedRealtimeMs);
Tej Singh4503e102018-01-04 14:35:01 -08007152 StatsLog.write_non_chained(
Bookatz90867622018-01-31 15:05:57 -08007153 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED, getUid(), null,
7154 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED__STATE__ON);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007155 }
7156 }
7157
7158 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007159 public void noteWifiMulticastDisabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007160 if (mWifiMulticastEnabled) {
7161 mWifiMulticastEnabled = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007162 mWifiMulticastTimer.stopRunningLocked(elapsedRealtimeMs);
Tej Singh4503e102018-01-04 14:35:01 -08007163 StatsLog.write_non_chained(
Bookatz90867622018-01-31 15:05:57 -08007164 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED, getUid(), null,
7165 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED__STATE__OFF);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007166 }
7167 }
7168
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007169 @Override
7170 public ControllerActivityCounter getWifiControllerActivity() {
7171 return mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07007172 }
7173
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007174 @Override
7175 public ControllerActivityCounter getBluetoothControllerActivity() {
7176 return mBluetoothControllerActivity;
7177 }
7178
7179 @Override
7180 public ControllerActivityCounter getModemControllerActivity() {
7181 return mModemControllerActivity;
7182 }
7183
7184 public ControllerActivityCounterImpl getOrCreateWifiControllerActivityLocked() {
7185 if (mWifiControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007186 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007187 NUM_BT_TX_LEVELS);
Adam Lesinski50e47602015-12-04 17:04:54 -08007188 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007189 return mWifiControllerActivity;
7190 }
7191
7192 public ControllerActivityCounterImpl getOrCreateBluetoothControllerActivityLocked() {
7193 if (mBluetoothControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007194 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007195 NUM_BT_TX_LEVELS);
7196 }
7197 return mBluetoothControllerActivity;
7198 }
7199
7200 public ControllerActivityCounterImpl getOrCreateModemControllerActivityLocked() {
7201 if (mModemControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007202 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007203 ModemActivityInfo.TX_POWER_LEVELS);
7204 }
7205 return mModemControllerActivity;
Adam Lesinski50e47602015-12-04 17:04:54 -08007206 }
7207
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007208 public StopwatchTimer createAudioTurnedOnTimerLocked() {
7209 if (mAudioTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007210 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
7211 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007212 }
7213 return mAudioTurnedOnTimer;
7214 }
7215
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007216 public void noteAudioTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007217 createAudioTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
7218 }
7219
7220 public void noteAudioTurnedOffLocked(long elapsedRealtimeMs) {
7221 if (mAudioTurnedOnTimer != null) {
7222 mAudioTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007223 }
7224 }
7225
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007226 public void noteResetAudioLocked(long elapsedRealtimeMs) {
7227 if (mAudioTurnedOnTimer != null) {
7228 mAudioTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007229 }
7230 }
7231
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007232 public StopwatchTimer createVideoTurnedOnTimerLocked() {
7233 if (mVideoTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007234 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
7235 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007236 }
7237 return mVideoTurnedOnTimer;
7238 }
7239
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007240 public void noteVideoTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007241 createVideoTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
7242 }
7243
7244 public void noteVideoTurnedOffLocked(long elapsedRealtimeMs) {
7245 if (mVideoTurnedOnTimer != null) {
7246 mVideoTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007247 }
7248 }
7249
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007250 public void noteResetVideoLocked(long elapsedRealtimeMs) {
7251 if (mVideoTurnedOnTimer != null) {
7252 mVideoTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007253 }
7254 }
7255
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007256 public StopwatchTimer createFlashlightTurnedOnTimerLocked() {
7257 if (mFlashlightTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007258 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7259 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007260 }
7261 return mFlashlightTurnedOnTimer;
7262 }
7263
7264 public void noteFlashlightTurnedOnLocked(long elapsedRealtimeMs) {
7265 createFlashlightTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
7266 }
7267
7268 public void noteFlashlightTurnedOffLocked(long elapsedRealtimeMs) {
7269 if (mFlashlightTurnedOnTimer != null) {
7270 mFlashlightTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
7271 }
7272 }
7273
7274 public void noteResetFlashlightLocked(long elapsedRealtimeMs) {
7275 if (mFlashlightTurnedOnTimer != null) {
7276 mFlashlightTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
7277 }
7278 }
7279
7280 public StopwatchTimer createCameraTurnedOnTimerLocked() {
7281 if (mCameraTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007282 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
7283 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007284 }
7285 return mCameraTurnedOnTimer;
7286 }
7287
7288 public void noteCameraTurnedOnLocked(long elapsedRealtimeMs) {
7289 createCameraTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
7290 }
7291
7292 public void noteCameraTurnedOffLocked(long elapsedRealtimeMs) {
7293 if (mCameraTurnedOnTimer != null) {
7294 mCameraTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
7295 }
7296 }
7297
7298 public void noteResetCameraLocked(long elapsedRealtimeMs) {
7299 if (mCameraTurnedOnTimer != null) {
7300 mCameraTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
7301 }
7302 }
7303
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007304 public StopwatchTimer createForegroundActivityTimerLocked() {
7305 if (mForegroundActivityTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007306 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7307 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007308 }
7309 return mForegroundActivityTimer;
7310 }
7311
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007312 public StopwatchTimer createForegroundServiceTimerLocked() {
7313 if (mForegroundServiceTimer == null) {
7314 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7315 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase);
7316 }
7317 return mForegroundServiceTimer;
7318 }
7319
Bookatzc8c44962017-05-11 12:12:54 -07007320 public DualTimer createAggregatedPartialWakelockTimerLocked() {
7321 if (mAggregatedPartialWakelockTimer == null) {
7322 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
7323 AGGREGATED_WAKE_TYPE_PARTIAL, null,
7324 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase);
7325 }
7326 return mAggregatedPartialWakelockTimer;
7327 }
7328
Bookatz867c0d72017-03-07 18:23:42 -08007329 public DualTimer createBluetoothScanTimerLocked() {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007330 if (mBluetoothScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007331 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
7332 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
7333 mOnBatteryBackgroundTimeBase);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007334 }
7335 return mBluetoothScanTimer;
7336 }
7337
Bookatzb1f04f32017-05-19 13:57:32 -07007338 public DualTimer createBluetoothUnoptimizedScanTimerLocked() {
7339 if (mBluetoothUnoptimizedScanTimer == null) {
7340 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
7341 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
7342 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
7343 }
7344 return mBluetoothUnoptimizedScanTimer;
7345 }
7346
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00007347 public void noteBluetoothScanStartedLocked(long elapsedRealtimeMs,
7348 boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007349 createBluetoothScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatzb1f04f32017-05-19 13:57:32 -07007350 if (isUnoptimized) {
7351 createBluetoothUnoptimizedScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
7352 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007353 }
7354
Bookatz94c5a312017-07-11 16:49:17 -07007355 public void noteBluetoothScanStoppedLocked(long elapsedRealtimeMs, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007356 if (mBluetoothScanTimer != null) {
7357 mBluetoothScanTimer.stopRunningLocked(elapsedRealtimeMs);
7358 }
Bookatz94c5a312017-07-11 16:49:17 -07007359 if (isUnoptimized && mBluetoothUnoptimizedScanTimer != null) {
Bookatzb1f04f32017-05-19 13:57:32 -07007360 mBluetoothUnoptimizedScanTimer.stopRunningLocked(elapsedRealtimeMs);
7361 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007362 }
7363
7364 public void noteResetBluetoothScanLocked(long elapsedRealtimeMs) {
7365 if (mBluetoothScanTimer != null) {
7366 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
7367 }
Bookatzb1f04f32017-05-19 13:57:32 -07007368 if (mBluetoothUnoptimizedScanTimer != null) {
7369 mBluetoothUnoptimizedScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
7370 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007371 }
7372
Bookatz956f36bf2017-04-28 09:48:17 -07007373 public Counter createBluetoothScanResultCounterLocked() {
7374 if (mBluetoothScanResultCounter == null) {
7375 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase);
7376 }
7377 return mBluetoothScanResultCounter;
7378 }
7379
Bookatzb1f04f32017-05-19 13:57:32 -07007380 public Counter createBluetoothScanResultBgCounterLocked() {
7381 if (mBluetoothScanResultBgCounter == null) {
7382 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase);
7383 }
7384 return mBluetoothScanResultBgCounter;
7385 }
7386
Bookatz4ebc0642017-05-11 12:21:19 -07007387 public void noteBluetoothScanResultsLocked(int numNewResults) {
7388 createBluetoothScanResultCounterLocked().addAtomic(numNewResults);
Bookatzb1f04f32017-05-19 13:57:32 -07007389 // Uses background timebase, so the count will only be incremented if uid in background.
7390 createBluetoothScanResultBgCounterLocked().addAtomic(numNewResults);
Bookatz956f36bf2017-04-28 09:48:17 -07007391 }
7392
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007393 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007394 public void noteActivityResumedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007395 // We always start, since we want multiple foreground PIDs to nest
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007396 createForegroundActivityTimerLocked().startRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007397 }
7398
7399 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007400 public void noteActivityPausedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007401 if (mForegroundActivityTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007402 mForegroundActivityTimer.stopRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007403 }
7404 }
7405
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007406 public void noteForegroundServiceResumedLocked(long elapsedRealtimeMs) {
7407 createForegroundServiceTimerLocked().startRunningLocked(elapsedRealtimeMs);
7408 }
7409
7410 public void noteForegroundServicePausedLocked(long elapsedRealtimeMs) {
7411 if (mForegroundServiceTimer != null) {
7412 mForegroundServiceTimer.stopRunningLocked(elapsedRealtimeMs);
7413 }
7414 }
7415
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007416 public BatchTimer createVibratorOnTimerLocked() {
7417 if (mVibratorOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007418 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
7419 mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007420 }
7421 return mVibratorOnTimer;
7422 }
7423
7424 public void noteVibratorOnLocked(long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08007425 createVibratorOnTimerLocked().addDuration(mBsi, durationMillis);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007426 }
7427
7428 public void noteVibratorOffLocked() {
7429 if (mVibratorOnTimer != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007430 mVibratorOnTimer.abortLastDuration(mBsi);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007431 }
7432 }
7433
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007434 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007435 public long getWifiRunningTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007436 if (mWifiRunningTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007437 return 0;
7438 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007439 return mWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007440 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07007441
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007442 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007443 public long getFullWifiLockTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007444 if (mFullWifiLockTimer == null) {
7445 return 0;
7446 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007447 return mFullWifiLockTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07007448 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007449
7450 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007451 public long getWifiScanTime(long elapsedRealtimeUs, int which) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007452 if (mWifiScanTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007453 return 0;
7454 }
Bookatzaa4594a2017-03-24 12:39:56 -07007455 return mWifiScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07007456 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007457
7458 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07007459 public int getWifiScanCount(int which) {
7460 if (mWifiScanTimer == null) {
7461 return 0;
7462 }
Bookatzaa4594a2017-03-24 12:39:56 -07007463 return mWifiScanTimer.getCountLocked(which);
Bookatz867c0d72017-03-07 18:23:42 -08007464 }
7465
7466 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07007467 public Timer getWifiScanTimer() {
7468 return mWifiScanTimer;
7469 }
7470
7471 @Override
Bookatz867c0d72017-03-07 18:23:42 -08007472 public int getWifiScanBackgroundCount(int which) {
Bookatzaa4594a2017-03-24 12:39:56 -07007473 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007474 return 0;
7475 }
7476 return mWifiScanTimer.getSubTimer().getCountLocked(which);
7477 }
7478
7479 @Override
7480 public long getWifiScanActualTime(final long elapsedRealtimeUs) {
7481 if (mWifiScanTimer == null) {
7482 return 0;
7483 }
7484 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
Bookatzaa4594a2017-03-24 12:39:56 -07007485 return mWifiScanTimer.getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Bookatz867c0d72017-03-07 18:23:42 -08007486 }
7487
7488 @Override
7489 public long getWifiScanBackgroundTime(final long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07007490 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007491 return 0;
7492 }
7493 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
7494 return mWifiScanTimer.getSubTimer().getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Dianne Hackborn62793e42015-03-09 11:15:41 -07007495 }
7496
7497 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07007498 public Timer getWifiScanBackgroundTimer() {
7499 if (mWifiScanTimer == null) {
7500 return null;
7501 }
7502 return mWifiScanTimer.getSubTimer();
7503 }
7504
7505 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007506 public long getWifiBatchedScanTime(int csphBin, long elapsedRealtimeUs, int which) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007507 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
7508 if (mWifiBatchedScanTimer[csphBin] == null) {
7509 return 0;
7510 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007511 return mWifiBatchedScanTimer[csphBin].getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007512 }
7513
7514 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07007515 public int getWifiBatchedScanCount(int csphBin, int which) {
7516 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
7517 if (mWifiBatchedScanTimer[csphBin] == null) {
7518 return 0;
7519 }
7520 return mWifiBatchedScanTimer[csphBin].getCountLocked(which);
7521 }
7522
7523 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007524 public long getWifiMulticastTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007525 if (mWifiMulticastTimer == null) {
7526 return 0;
7527 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007528 return mWifiMulticastTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007529 }
7530
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007531 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007532 public Timer getAudioTurnedOnTimer() {
7533 return mAudioTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007534 }
7535
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007536 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007537 public Timer getVideoTurnedOnTimer() {
7538 return mVideoTurnedOnTimer;
7539 }
7540
7541 @Override
7542 public Timer getFlashlightTurnedOnTimer() {
7543 return mFlashlightTurnedOnTimer;
7544 }
7545
7546 @Override
7547 public Timer getCameraTurnedOnTimer() {
7548 return mCameraTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007549 }
7550
Dianne Hackborn617f8772009-03-31 15:04:46 -07007551 @Override
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007552 public Timer getForegroundActivityTimer() {
7553 return mForegroundActivityTimer;
7554 }
7555
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007556 @Override
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007557 public Timer getForegroundServiceTimer() {
7558 return mForegroundServiceTimer;
7559 }
7560
7561 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007562 public Timer getBluetoothScanTimer() {
Bookatzaa4594a2017-03-24 12:39:56 -07007563 return mBluetoothScanTimer;
Bookatz867c0d72017-03-07 18:23:42 -08007564 }
7565
7566 @Override
7567 public Timer getBluetoothScanBackgroundTimer() {
7568 if (mBluetoothScanTimer == null) {
7569 return null;
7570 }
7571 return mBluetoothScanTimer.getSubTimer();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007572 }
7573
Bookatz956f36bf2017-04-28 09:48:17 -07007574 @Override
Bookatzb1f04f32017-05-19 13:57:32 -07007575 public Timer getBluetoothUnoptimizedScanTimer() {
7576 return mBluetoothUnoptimizedScanTimer;
7577 }
7578
7579 @Override
7580 public Timer getBluetoothUnoptimizedScanBackgroundTimer() {
7581 if (mBluetoothUnoptimizedScanTimer == null) {
7582 return null;
7583 }
7584 return mBluetoothUnoptimizedScanTimer.getSubTimer();
7585 }
7586
7587 @Override
Bookatz956f36bf2017-04-28 09:48:17 -07007588 public Counter getBluetoothScanResultCounter() {
7589 return mBluetoothScanResultCounter;
7590 }
7591
Bookatzb1f04f32017-05-19 13:57:32 -07007592 @Override
7593 public Counter getBluetoothScanResultBgCounter() {
7594 return mBluetoothScanResultBgCounter;
7595 }
7596
Dianne Hackborn61659e52014-07-09 16:13:01 -07007597 void makeProcessState(int i, Parcel in) {
7598 if (i < 0 || i >= NUM_PROCESS_STATE) return;
7599
7600 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007601 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
7602 mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007603 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08007604 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
7605 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007606 }
7607 }
7608
7609 @Override
7610 public long getProcessStateTime(int state, long elapsedRealtimeUs, int which) {
7611 if (state < 0 || state >= NUM_PROCESS_STATE) return 0;
7612 if (mProcessStateTimer[state] == null) {
7613 return 0;
7614 }
7615 return mProcessStateTimer[state].getTotalTimeLocked(elapsedRealtimeUs, which);
7616 }
7617
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007618 @Override
Joe Onorato713fec82016-03-04 10:34:02 -08007619 public Timer getProcessStateTimer(int state) {
7620 if (state < 0 || state >= NUM_PROCESS_STATE) return null;
7621 return mProcessStateTimer[state];
7622 }
7623
7624 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007625 public Timer getVibratorOnTimer() {
7626 return mVibratorOnTimer;
7627 }
7628
7629 @Override
Dianne Hackborn617f8772009-03-31 15:04:46 -07007630 public void noteUserActivityLocked(int type) {
7631 if (mUserActivityCounters == null) {
7632 initUserActivityLocked();
7633 }
Jeff Browndf693de2012-07-27 12:03:38 -07007634 if (type >= 0 && type < NUM_USER_ACTIVITY_TYPES) {
7635 mUserActivityCounters[type].stepAtomic();
7636 } else {
7637 Slog.w(TAG, "Unknown user activity type " + type + " was specified.",
7638 new Throwable());
7639 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07007640 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007641
Dianne Hackborn617f8772009-03-31 15:04:46 -07007642 @Override
7643 public boolean hasUserActivity() {
7644 return mUserActivityCounters != null;
7645 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007646
Dianne Hackborn617f8772009-03-31 15:04:46 -07007647 @Override
7648 public int getUserActivityCount(int type, int which) {
7649 if (mUserActivityCounters == null) {
7650 return 0;
7651 }
Evan Millarc64edde2009-04-18 12:26:32 -07007652 return mUserActivityCounters[type].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007653 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007654
Robert Greenwalta029ea12013-09-25 16:38:12 -07007655 void makeWifiBatchedScanBin(int i, Parcel in) {
7656 if (i < 0 || i >= NUM_WIFI_BATCHED_SCAN_BINS) return;
7657
Joe Onoratoabded112016-02-08 16:49:39 -08007658 ArrayList<StopwatchTimer> collected = mBsi.mWifiBatchedScanTimers.get(i);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007659 if (collected == null) {
7660 collected = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08007661 mBsi.mWifiBatchedScanTimers.put(i, collected);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007662 }
7663 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007664 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
7665 collected, mBsi.mOnBatteryTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007666 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08007667 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
7668 collected, mBsi.mOnBatteryTimeBase, in);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007669 }
7670 }
7671
7672
Dianne Hackborn617f8772009-03-31 15:04:46 -07007673 void initUserActivityLocked() {
7674 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
7675 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007676 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007677 }
7678 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007679
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007680 void noteNetworkActivityLocked(int type, long deltaBytes, long deltaPackets) {
7681 if (mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007682 initNetworkActivityLocked();
7683 }
7684 if (type >= 0 && type < NUM_NETWORK_ACTIVITY_TYPES) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007685 mNetworkByteActivityCounters[type].addCountLocked(deltaBytes);
7686 mNetworkPacketActivityCounters[type].addCountLocked(deltaPackets);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007687 } else {
7688 Slog.w(TAG, "Unknown network activity type " + type + " was specified.",
7689 new Throwable());
7690 }
7691 }
7692
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007693 void noteMobileRadioActiveTimeLocked(long batteryUptime) {
7694 if (mNetworkByteActivityCounters == null) {
7695 initNetworkActivityLocked();
7696 }
7697 mMobileRadioActiveTime.addCountLocked(batteryUptime);
7698 mMobileRadioActiveCount.addCountLocked(1);
7699 }
7700
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007701 @Override
7702 public boolean hasNetworkActivity() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007703 return mNetworkByteActivityCounters != null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007704 }
7705
7706 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007707 public long getNetworkActivityBytes(int type, int which) {
7708 if (mNetworkByteActivityCounters != null && type >= 0
7709 && type < mNetworkByteActivityCounters.length) {
7710 return mNetworkByteActivityCounters[type].getCountLocked(which);
7711 } else {
7712 return 0;
7713 }
7714 }
7715
7716 @Override
7717 public long getNetworkActivityPackets(int type, int which) {
7718 if (mNetworkPacketActivityCounters != null && type >= 0
7719 && type < mNetworkPacketActivityCounters.length) {
7720 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007721 } else {
7722 return 0;
7723 }
7724 }
7725
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007726 @Override
7727 public long getMobileRadioActiveTime(int which) {
7728 return mMobileRadioActiveTime != null
7729 ? mMobileRadioActiveTime.getCountLocked(which) : 0;
7730 }
7731
7732 @Override
7733 public int getMobileRadioActiveCount(int which) {
7734 return mMobileRadioActiveCount != null
7735 ? (int)mMobileRadioActiveCount.getCountLocked(which) : 0;
7736 }
7737
Adam Lesinskie08af192015-03-25 16:42:59 -07007738 @Override
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007739 public long getUserCpuTimeUs(int which) {
7740 return mUserCpuTime.getCountLocked(which);
7741 }
7742
7743 @Override
7744 public long getSystemCpuTimeUs(int which) {
7745 return mSystemCpuTime.getCountLocked(which);
7746 }
7747
7748 @Override
Adam Lesinski6832f392015-09-05 18:05:40 -07007749 public long getTimeAtCpuSpeed(int cluster, int step, int which) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07007750 if (mCpuClusterSpeedTimesUs != null) {
7751 if (cluster >= 0 && cluster < mCpuClusterSpeedTimesUs.length) {
7752 final LongSamplingCounter[] cpuSpeedTimesUs = mCpuClusterSpeedTimesUs[cluster];
7753 if (cpuSpeedTimesUs != null) {
7754 if (step >= 0 && step < cpuSpeedTimesUs.length) {
7755 final LongSamplingCounter c = cpuSpeedTimesUs[step];
Adam Lesinski6832f392015-09-05 18:05:40 -07007756 if (c != null) {
7757 return c.getCountLocked(which);
7758 }
7759 }
7760 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007761 }
7762 }
7763 return 0;
7764 }
7765
Adam Lesinski5f056f62016-07-14 16:56:08 -07007766 public void noteMobileRadioApWakeupLocked() {
7767 if (mMobileRadioApWakeupCount == null) {
7768 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7769 }
7770 mMobileRadioApWakeupCount.addCountLocked(1);
7771 }
7772
7773 @Override
7774 public long getMobileRadioApWakeupCount(int which) {
7775 if (mMobileRadioApWakeupCount != null) {
7776 return mMobileRadioApWakeupCount.getCountLocked(which);
7777 }
7778 return 0;
7779 }
7780
7781 public void noteWifiRadioApWakeupLocked() {
7782 if (mWifiRadioApWakeupCount == null) {
7783 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7784 }
7785 mWifiRadioApWakeupCount.addCountLocked(1);
7786 }
7787
7788 @Override
7789 public long getWifiRadioApWakeupCount(int which) {
7790 if (mWifiRadioApWakeupCount != null) {
7791 return mWifiRadioApWakeupCount.getCountLocked(which);
7792 }
7793 return 0;
7794 }
7795
Amith Yamasani977e11f2018-02-16 11:29:54 -08007796 @Override
7797 public void getDeferredJobsCheckinLineLocked(StringBuilder sb, int which) {
7798 sb.setLength(0);
7799 final int deferredEventCount = mJobsDeferredEventCount.getCountLocked(which);
7800 if (deferredEventCount == 0) {
7801 return;
7802 }
7803 final int deferredCount = mJobsDeferredCount.getCountLocked(which);
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007804 final long totalLatency = mJobsFreshnessTimeMs.getCountLocked(which);
Amith Yamasani977e11f2018-02-16 11:29:54 -08007805 sb.append(deferredEventCount); sb.append(',');
7806 sb.append(deferredCount); sb.append(',');
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007807 sb.append(totalLatency);
Amith Yamasani977e11f2018-02-16 11:29:54 -08007808 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
7809 if (mJobsFreshnessBuckets[i] == null) {
7810 sb.append(",0");
7811 } else {
7812 sb.append(",");
7813 sb.append(mJobsFreshnessBuckets[i].getCountLocked(which));
7814 }
7815 }
7816 }
7817
7818 @Override
7819 public void getDeferredJobsLineLocked(StringBuilder sb, int which) {
7820 sb.setLength(0);
7821 final int deferredEventCount = mJobsDeferredEventCount.getCountLocked(which);
7822 if (deferredEventCount == 0) {
7823 return;
7824 }
7825 final int deferredCount = mJobsDeferredCount.getCountLocked(which);
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007826 final long totalLatency = mJobsFreshnessTimeMs.getCountLocked(which);
Amith Yamasani977e11f2018-02-16 11:29:54 -08007827 sb.append("times="); sb.append(deferredEventCount); sb.append(", ");
7828 sb.append("count="); sb.append(deferredCount); sb.append(", ");
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007829 sb.append("totalLatencyMs="); sb.append(totalLatency); sb.append(", ");
Amith Yamasani977e11f2018-02-16 11:29:54 -08007830 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
7831 sb.append("<"); sb.append(JOB_FRESHNESS_BUCKETS[i]); sb.append("ms=");
7832 if (mJobsFreshnessBuckets[i] == null) {
7833 sb.append("0");
7834 } else {
7835 sb.append(mJobsFreshnessBuckets[i].getCountLocked(which));
7836 }
7837 sb.append(" ");
7838 }
7839 }
7840
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007841 void initNetworkActivityLocked() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007842 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
7843 mNetworkPacketActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007844 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007845 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7846 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007847 }
Joe Onoratoabded112016-02-08 16:49:39 -08007848 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7849 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007850 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07007851
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007852 /**
7853 * Clear all stats for this uid. Returns true if the uid is completely
7854 * inactive so can be dropped.
7855 */
Adam Lesinski5f212c82017-03-13 12:25:13 -07007856 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
Bookatz993a0be2017-07-21 09:03:23 -07007857 public boolean reset(long uptime, long realtime) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007858 boolean active = false;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007859
Bookatz993a0be2017-07-21 09:03:23 -07007860 mOnBatteryBackgroundTimeBase.init(uptime, realtime);
7861 mOnBatteryScreenOffBackgroundTimeBase.init(uptime, realtime);
7862
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007863 if (mWifiRunningTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007864 active |= !mWifiRunningTimer.reset(false);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007865 active |= mWifiRunning;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007866 }
7867 if (mFullWifiLockTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007868 active |= !mFullWifiLockTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007869 active |= mFullWifiLockOut;
7870 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07007871 if (mWifiScanTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007872 active |= !mWifiScanTimer.reset(false);
Nick Pelly6ccaa542012-06-15 15:22:47 -07007873 active |= mWifiScanStarted;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007874 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07007875 if (mWifiBatchedScanTimer != null) {
7876 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
7877 if (mWifiBatchedScanTimer[i] != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007878 active |= !mWifiBatchedScanTimer[i].reset(false);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007879 }
7880 }
7881 active |= (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED);
7882 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007883 if (mWifiMulticastTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007884 active |= !mWifiMulticastTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007885 active |= mWifiMulticastEnabled;
7886 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007887
7888 active |= !resetTimerIfNotNull(mAudioTurnedOnTimer, false);
7889 active |= !resetTimerIfNotNull(mVideoTurnedOnTimer, false);
7890 active |= !resetTimerIfNotNull(mFlashlightTurnedOnTimer, false);
7891 active |= !resetTimerIfNotNull(mCameraTurnedOnTimer, false);
7892 active |= !resetTimerIfNotNull(mForegroundActivityTimer, false);
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007893 active |= !resetTimerIfNotNull(mForegroundServiceTimer, false);
Bookatzc8c44962017-05-11 12:12:54 -07007894 active |= !resetTimerIfNotNull(mAggregatedPartialWakelockTimer, false);
Adam Lesinski5f056f62016-07-14 16:56:08 -07007895 active |= !resetTimerIfNotNull(mBluetoothScanTimer, false);
Bookatzb1f04f32017-05-19 13:57:32 -07007896 active |= !resetTimerIfNotNull(mBluetoothUnoptimizedScanTimer, false);
Bookatz956f36bf2017-04-28 09:48:17 -07007897 if (mBluetoothScanResultCounter != null) {
7898 mBluetoothScanResultCounter.reset(false);
7899 }
Bookatzb1f04f32017-05-19 13:57:32 -07007900 if (mBluetoothScanResultBgCounter != null) {
7901 mBluetoothScanResultBgCounter.reset(false);
7902 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007903
Dianne Hackborn61659e52014-07-09 16:13:01 -07007904 if (mProcessStateTimer != null) {
7905 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
7906 if (mProcessStateTimer[i] != null) {
7907 active |= !mProcessStateTimer[i].reset(false);
7908 }
7909 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08007910 active |= (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007911 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007912 if (mVibratorOnTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007913 if (mVibratorOnTimer.reset(false)) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007914 mVibratorOnTimer.detach();
7915 mVibratorOnTimer = null;
7916 } else {
7917 active = true;
7918 }
7919 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007920
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007921 if (mUserActivityCounters != null) {
7922 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
7923 mUserActivityCounters[i].reset(false);
7924 }
7925 }
7926
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007927 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007928 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007929 mNetworkByteActivityCounters[i].reset(false);
7930 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007931 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007932 mMobileRadioActiveTime.reset(false);
7933 mMobileRadioActiveCount.reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007934 }
7935
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007936 if (mWifiControllerActivity != null) {
7937 mWifiControllerActivity.reset(false);
7938 }
Adam Lesinskie08af192015-03-25 16:42:59 -07007939
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07007940 if (mBluetoothControllerActivity != null) {
7941 mBluetoothControllerActivity.reset(false);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007942 }
7943
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07007944 if (mModemControllerActivity != null) {
7945 mModemControllerActivity.reset(false);
Adam Lesinskie08af192015-03-25 16:42:59 -07007946 }
7947
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007948 mUserCpuTime.reset(false);
7949 mSystemCpuTime.reset(false);
Adam Lesinski6832f392015-09-05 18:05:40 -07007950
Sudheer Shankaaf857412017-07-21 00:14:24 -07007951 if (mCpuClusterSpeedTimesUs != null) {
7952 for (LongSamplingCounter[] speeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07007953 if (speeds != null) {
7954 for (LongSamplingCounter speed : speeds) {
7955 if (speed != null) {
7956 speed.reset(false);
7957 }
7958 }
7959 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007960 }
7961 }
7962
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007963 if (mCpuFreqTimeMs != null) {
7964 mCpuFreqTimeMs.reset(false);
7965 }
7966 if (mScreenOffCpuFreqTimeMs != null) {
7967 mScreenOffCpuFreqTimeMs.reset(false);
7968 }
7969
Mike Ma3d422c32017-10-25 11:08:57 -07007970 mCpuActiveTimeMs.reset(false);
7971 mCpuClusterTimesMs.reset(false);
7972
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007973 if (mProcStateTimeMs != null) {
7974 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
7975 if (counters != null) {
7976 counters.reset(false);
7977 }
7978 }
7979 }
7980 if (mProcStateScreenOffTimeMs != null) {
7981 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
7982 if (counters != null) {
7983 counters.reset(false);
7984 }
7985 }
7986 }
7987
Adam Lesinski5f056f62016-07-14 16:56:08 -07007988 resetLongCounterIfNotNull(mMobileRadioApWakeupCount, false);
7989 resetLongCounterIfNotNull(mWifiRadioApWakeupCount, false);
7990
Dianne Hackbornd953c532014-08-16 18:17:38 -07007991 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
7992 for (int iw=wakeStats.size()-1; iw>=0; iw--) {
7993 Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007994 if (wl.reset()) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007995 wakeStats.removeAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007996 } else {
7997 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007998 }
7999 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07008000 mWakelockStats.cleanup();
Bookatz2bffb5b2017-04-13 11:59:33 -07008001 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008002 for (int is=syncStats.size()-1; is>=0; is--) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008003 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008004 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008005 syncStats.removeAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008006 timer.detach();
8007 } else {
8008 active = true;
8009 }
8010 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07008011 mSyncStats.cleanup();
Bookatzaa4594a2017-03-24 12:39:56 -07008012 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008013 for (int ij=jobStats.size()-1; ij>=0; ij--) {
Bookatzaa4594a2017-03-24 12:39:56 -07008014 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008015 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008016 jobStats.removeAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008017 timer.detach();
8018 } else {
8019 active = true;
8020 }
8021 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07008022 mJobStats.cleanup();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008023 mJobCompletions.clear();
Amith Yamasani977e11f2018-02-16 11:29:54 -08008024
8025 mJobsDeferredEventCount.reset(false);
8026 mJobsDeferredCount.reset(false);
8027 mJobsFreshnessTimeMs.reset(false);
8028 for (int ij = 0; ij < JOB_FRESHNESS_BUCKETS.length; ij++) {
8029 if (mJobsFreshnessBuckets[ij] != null) {
8030 mJobsFreshnessBuckets[ij].reset(false);
8031 }
8032 }
8033
Dianne Hackborn61659e52014-07-09 16:13:01 -07008034 for (int ise=mSensorStats.size()-1; ise>=0; ise--) {
8035 Sensor s = mSensorStats.valueAt(ise);
8036 if (s.reset()) {
8037 mSensorStats.removeAt(ise);
8038 } else {
8039 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008040 }
8041 }
Amith Yamasani977e11f2018-02-16 11:29:54 -08008042
Dianne Hackborn61659e52014-07-09 16:13:01 -07008043 for (int ip=mProcessStats.size()-1; ip>=0; ip--) {
8044 Proc proc = mProcessStats.valueAt(ip);
Dianne Hackborna8d10942015-11-19 17:55:19 -08008045 proc.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008046 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08008047 mProcessStats.clear();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008048 if (mPids.size() > 0) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008049 for (int i=mPids.size()-1; i>=0; i--) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008050 Pid pid = mPids.valueAt(i);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008051 if (pid.mWakeNesting > 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008052 active = true;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008053 } else {
8054 mPids.removeAt(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008055 }
8056 }
8057 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008058 if (mPackageStats.size() > 0) {
8059 Iterator<Map.Entry<String, Pkg>> it = mPackageStats.entrySet().iterator();
8060 while (it.hasNext()) {
8061 Map.Entry<String, Pkg> pkgEntry = it.next();
8062 Pkg p = pkgEntry.getValue();
8063 p.detach();
8064 if (p.mServiceStats.size() > 0) {
8065 Iterator<Map.Entry<String, Pkg.Serv>> it2
8066 = p.mServiceStats.entrySet().iterator();
8067 while (it2.hasNext()) {
8068 Map.Entry<String, Pkg.Serv> servEntry = it2.next();
8069 servEntry.getValue().detach();
8070 }
8071 }
8072 }
8073 mPackageStats.clear();
8074 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008075
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08008076 mLastStepUserTime = mLastStepSystemTime = 0;
8077 mCurStepUserTime = mCurStepSystemTime = 0;
8078
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008079 if (!active) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008080 if (mWifiRunningTimer != null) {
8081 mWifiRunningTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008082 }
8083 if (mFullWifiLockTimer != null) {
8084 mFullWifiLockTimer.detach();
8085 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008086 if (mWifiScanTimer != null) {
8087 mWifiScanTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008088 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008089 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8090 if (mWifiBatchedScanTimer[i] != null) {
8091 mWifiBatchedScanTimer[i].detach();
8092 }
8093 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008094 if (mWifiMulticastTimer != null) {
8095 mWifiMulticastTimer.detach();
8096 }
8097 if (mAudioTurnedOnTimer != null) {
8098 mAudioTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008099 mAudioTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008100 }
8101 if (mVideoTurnedOnTimer != null) {
8102 mVideoTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008103 mVideoTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008104 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008105 if (mFlashlightTurnedOnTimer != null) {
8106 mFlashlightTurnedOnTimer.detach();
8107 mFlashlightTurnedOnTimer = null;
8108 }
8109 if (mCameraTurnedOnTimer != null) {
8110 mCameraTurnedOnTimer.detach();
8111 mCameraTurnedOnTimer = null;
8112 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008113 if (mForegroundActivityTimer != null) {
8114 mForegroundActivityTimer.detach();
8115 mForegroundActivityTimer = null;
8116 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008117 if (mForegroundServiceTimer != null) {
8118 mForegroundServiceTimer.detach();
8119 mForegroundServiceTimer = null;
8120 }
Bookatzc8c44962017-05-11 12:12:54 -07008121 if (mAggregatedPartialWakelockTimer != null) {
8122 mAggregatedPartialWakelockTimer.detach();
8123 mAggregatedPartialWakelockTimer = null;
8124 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008125 if (mBluetoothScanTimer != null) {
8126 mBluetoothScanTimer.detach();
8127 mBluetoothScanTimer = null;
8128 }
Bookatzb1f04f32017-05-19 13:57:32 -07008129 if (mBluetoothUnoptimizedScanTimer != null) {
8130 mBluetoothUnoptimizedScanTimer.detach();
8131 mBluetoothUnoptimizedScanTimer = null;
8132 }
Bookatz956f36bf2017-04-28 09:48:17 -07008133 if (mBluetoothScanResultCounter != null) {
8134 mBluetoothScanResultCounter.detach();
8135 mBluetoothScanResultCounter = null;
8136 }
Bookatzb1f04f32017-05-19 13:57:32 -07008137 if (mBluetoothScanResultBgCounter != null) {
8138 mBluetoothScanResultBgCounter.detach();
8139 mBluetoothScanResultBgCounter = null;
8140 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008141 if (mUserActivityCounters != null) {
8142 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
8143 mUserActivityCounters[i].detach();
8144 }
8145 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008146 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008147 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008148 mNetworkByteActivityCounters[i].detach();
8149 mNetworkPacketActivityCounters[i].detach();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008150 }
8151 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008152
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008153 if (mWifiControllerActivity != null) {
8154 mWifiControllerActivity.detach();
Adam Lesinskie08af192015-03-25 16:42:59 -07008155 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008156
8157 if (mBluetoothControllerActivity != null) {
8158 mBluetoothControllerActivity.detach();
8159 }
8160
8161 if (mModemControllerActivity != null) {
8162 mModemControllerActivity.detach();
8163 }
8164
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008165 mPids.clear();
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008166
8167 mUserCpuTime.detach();
8168 mSystemCpuTime.detach();
Adam Lesinski6832f392015-09-05 18:05:40 -07008169
Sudheer Shankaaf857412017-07-21 00:14:24 -07008170 if (mCpuClusterSpeedTimesUs != null) {
8171 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008172 if (cpuSpeeds != null) {
8173 for (LongSamplingCounter c : cpuSpeeds) {
8174 if (c != null) {
8175 c.detach();
8176 }
8177 }
8178 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008179 }
8180 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008181
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008182 if (mCpuFreqTimeMs != null) {
8183 mCpuFreqTimeMs.detach();
8184 }
8185 if (mScreenOffCpuFreqTimeMs != null) {
8186 mScreenOffCpuFreqTimeMs.detach();
8187 }
Mike Ma3d422c32017-10-25 11:08:57 -07008188 mCpuActiveTimeMs.detach();
8189 mCpuClusterTimesMs.detach();
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008190
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008191 if (mProcStateTimeMs != null) {
8192 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8193 if (counters != null) {
8194 counters.detach();
8195 }
8196 }
8197 }
8198 if (mProcStateScreenOffTimeMs != null) {
8199 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8200 if (counters != null) {
8201 counters.detach();
8202 }
8203 }
8204 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008205 detachLongCounterIfNotNull(mMobileRadioApWakeupCount);
8206 detachLongCounterIfNotNull(mWifiRadioApWakeupCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008207 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008208
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008209 return !active;
8210 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008211
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008212 void writeJobCompletionsToParcelLocked(Parcel out) {
8213 int NJC = mJobCompletions.size();
8214 out.writeInt(NJC);
8215 for (int ijc=0; ijc<NJC; ijc++) {
8216 out.writeString(mJobCompletions.keyAt(ijc));
8217 SparseIntArray types = mJobCompletions.valueAt(ijc);
8218 int NT = types.size();
8219 out.writeInt(NT);
8220 for (int it=0; it<NT; it++) {
8221 out.writeInt(types.keyAt(it));
8222 out.writeInt(types.valueAt(it));
8223 }
8224 }
8225 }
8226
Bookatz867c0d72017-03-07 18:23:42 -08008227 void writeToParcelLocked(Parcel out, long uptimeUs, long elapsedRealtimeUs) {
8228 mOnBatteryBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatzc8c44962017-05-11 12:12:54 -07008229 mOnBatteryScreenOffBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08008230
Dianne Hackbornd953c532014-08-16 18:17:38 -07008231 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
8232 int NW = wakeStats.size();
Dianne Hackborn61659e52014-07-09 16:13:01 -07008233 out.writeInt(NW);
8234 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008235 out.writeString(wakeStats.keyAt(iw));
8236 Uid.Wakelock wakelock = wakeStats.valueAt(iw);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008237 wakelock.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008238 }
8239
Bookatz2bffb5b2017-04-13 11:59:33 -07008240 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008241 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008242 out.writeInt(NS);
8243 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008244 out.writeString(syncStats.keyAt(is));
Bookatz2bffb5b2017-04-13 11:59:33 -07008245 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008246 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
8247 }
8248
Bookatzaa4594a2017-03-24 12:39:56 -07008249 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008250 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008251 out.writeInt(NJ);
8252 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008253 out.writeString(jobStats.keyAt(ij));
Bookatzaa4594a2017-03-24 12:39:56 -07008254 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008255 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
8256 }
8257
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008258 writeJobCompletionsToParcelLocked(out);
8259
Amith Yamasani977e11f2018-02-16 11:29:54 -08008260 mJobsDeferredEventCount.writeToParcel(out);
8261 mJobsDeferredCount.writeToParcel(out);
8262 mJobsFreshnessTimeMs.writeToParcel(out);
8263 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
8264 Counter.writeCounterToParcel(out, mJobsFreshnessBuckets[i]);
8265 }
8266
Dianne Hackborn61659e52014-07-09 16:13:01 -07008267 int NSE = mSensorStats.size();
8268 out.writeInt(NSE);
8269 for (int ise=0; ise<NSE; ise++) {
8270 out.writeInt(mSensorStats.keyAt(ise));
8271 Uid.Sensor sensor = mSensorStats.valueAt(ise);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008272 sensor.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008273 }
8274
Dianne Hackborn61659e52014-07-09 16:13:01 -07008275 int NP = mProcessStats.size();
8276 out.writeInt(NP);
8277 for (int ip=0; ip<NP; ip++) {
8278 out.writeString(mProcessStats.keyAt(ip));
8279 Uid.Proc proc = mProcessStats.valueAt(ip);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008280 proc.writeToParcelLocked(out);
8281 }
8282
8283 out.writeInt(mPackageStats.size());
8284 for (Map.Entry<String, Uid.Pkg> pkgEntry : mPackageStats.entrySet()) {
8285 out.writeString(pkgEntry.getKey());
8286 Uid.Pkg pkg = pkgEntry.getValue();
8287 pkg.writeToParcelLocked(out);
8288 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008289
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008290 if (mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008291 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008292 mWifiRunningTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008293 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008294 out.writeInt(0);
8295 }
8296 if (mFullWifiLockTimer != null) {
8297 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008298 mFullWifiLockTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008299 } else {
8300 out.writeInt(0);
8301 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008302 if (mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008303 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008304 mWifiScanTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008305 } else {
8306 out.writeInt(0);
8307 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008308 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8309 if (mWifiBatchedScanTimer[i] != null) {
8310 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008311 mWifiBatchedScanTimer[i].writeToParcel(out, elapsedRealtimeUs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07008312 } else {
8313 out.writeInt(0);
8314 }
8315 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008316 if (mWifiMulticastTimer != null) {
8317 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008318 mWifiMulticastTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008319 } else {
8320 out.writeInt(0);
8321 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008322
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008323 if (mAudioTurnedOnTimer != null) {
8324 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008325 mAudioTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008326 } else {
8327 out.writeInt(0);
8328 }
8329 if (mVideoTurnedOnTimer != null) {
8330 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008331 mVideoTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008332 } else {
8333 out.writeInt(0);
8334 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008335 if (mFlashlightTurnedOnTimer != null) {
8336 out.writeInt(1);
8337 mFlashlightTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
8338 } else {
8339 out.writeInt(0);
8340 }
8341 if (mCameraTurnedOnTimer != null) {
8342 out.writeInt(1);
8343 mCameraTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
8344 } else {
8345 out.writeInt(0);
8346 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008347 if (mForegroundActivityTimer != null) {
8348 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008349 mForegroundActivityTimer.writeToParcel(out, elapsedRealtimeUs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008350 } else {
8351 out.writeInt(0);
8352 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008353 if (mForegroundServiceTimer != null) {
8354 out.writeInt(1);
8355 mForegroundServiceTimer.writeToParcel(out, elapsedRealtimeUs);
8356 } else {
8357 out.writeInt(0);
8358 }
Bookatzc8c44962017-05-11 12:12:54 -07008359 if (mAggregatedPartialWakelockTimer != null) {
8360 out.writeInt(1);
8361 mAggregatedPartialWakelockTimer.writeToParcel(out, elapsedRealtimeUs);
8362 } else {
8363 out.writeInt(0);
8364 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008365 if (mBluetoothScanTimer != null) {
8366 out.writeInt(1);
8367 mBluetoothScanTimer.writeToParcel(out, elapsedRealtimeUs);
8368 } else {
8369 out.writeInt(0);
8370 }
Bookatzb1f04f32017-05-19 13:57:32 -07008371 if (mBluetoothUnoptimizedScanTimer != null) {
8372 out.writeInt(1);
8373 mBluetoothUnoptimizedScanTimer.writeToParcel(out, elapsedRealtimeUs);
8374 } else {
8375 out.writeInt(0);
8376 }
Bookatz956f36bf2017-04-28 09:48:17 -07008377 if (mBluetoothScanResultCounter != null) {
8378 out.writeInt(1);
8379 mBluetoothScanResultCounter.writeToParcel(out);
8380 } else {
8381 out.writeInt(0);
8382 }
Bookatzb1f04f32017-05-19 13:57:32 -07008383 if (mBluetoothScanResultBgCounter != null) {
8384 out.writeInt(1);
8385 mBluetoothScanResultBgCounter.writeToParcel(out);
8386 } else {
8387 out.writeInt(0);
8388 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07008389 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8390 if (mProcessStateTimer[i] != null) {
8391 out.writeInt(1);
8392 mProcessStateTimer[i].writeToParcel(out, elapsedRealtimeUs);
8393 } else {
8394 out.writeInt(0);
8395 }
8396 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008397 if (mVibratorOnTimer != null) {
8398 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008399 mVibratorOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008400 } else {
8401 out.writeInt(0);
8402 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008403 if (mUserActivityCounters != null) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07008404 out.writeInt(1);
8405 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
8406 mUserActivityCounters[i].writeToParcel(out);
8407 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008408 } else {
8409 out.writeInt(0);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008410 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008411 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008412 out.writeInt(1);
8413 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008414 mNetworkByteActivityCounters[i].writeToParcel(out);
8415 mNetworkPacketActivityCounters[i].writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008416 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08008417 mMobileRadioActiveTime.writeToParcel(out);
8418 mMobileRadioActiveCount.writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008419 } else {
8420 out.writeInt(0);
8421 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008422
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008423 if (mWifiControllerActivity != null) {
8424 out.writeInt(1);
8425 mWifiControllerActivity.writeToParcel(out, 0);
8426 } else {
8427 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07008428 }
8429
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008430 if (mBluetoothControllerActivity != null) {
8431 out.writeInt(1);
8432 mBluetoothControllerActivity.writeToParcel(out, 0);
8433 } else {
8434 out.writeInt(0);
8435 }
8436
8437 if (mModemControllerActivity != null) {
8438 out.writeInt(1);
8439 mModemControllerActivity.writeToParcel(out, 0);
8440 } else {
8441 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07008442 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008443
8444 mUserCpuTime.writeToParcel(out);
8445 mSystemCpuTime.writeToParcel(out);
8446
Sudheer Shankaaf857412017-07-21 00:14:24 -07008447 if (mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008448 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -07008449 out.writeInt(mCpuClusterSpeedTimesUs.length);
8450 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008451 if (cpuSpeeds != null) {
8452 out.writeInt(1);
8453 out.writeInt(cpuSpeeds.length);
8454 for (LongSamplingCounter c : cpuSpeeds) {
8455 if (c != null) {
8456 out.writeInt(1);
8457 c.writeToParcel(out);
8458 } else {
8459 out.writeInt(0);
8460 }
8461 }
8462 } else {
8463 out.writeInt(0);
8464 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008465 }
Adam Lesinski6832f392015-09-05 18:05:40 -07008466 } else {
8467 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008468 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008469
Sudheer Shanka59f5c002017-05-15 10:57:15 -07008470 LongSamplingCounterArray.writeToParcel(out, mCpuFreqTimeMs);
8471 LongSamplingCounterArray.writeToParcel(out, mScreenOffCpuFreqTimeMs);
Mike Ma3d422c32017-10-25 11:08:57 -07008472
8473 mCpuActiveTimeMs.writeToParcel(out);
8474 mCpuClusterTimesMs.writeToParcel(out);
8475
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008476 if (mProcStateTimeMs != null) {
8477 out.writeInt(mProcStateTimeMs.length);
8478 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8479 LongSamplingCounterArray.writeToParcel(out, counters);
8480 }
8481 } else {
8482 out.writeInt(0);
8483 }
8484 if (mProcStateScreenOffTimeMs != null) {
8485 out.writeInt(mProcStateScreenOffTimeMs.length);
8486 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8487 LongSamplingCounterArray.writeToParcel(out, counters);
8488 }
8489 } else {
8490 out.writeInt(0);
8491 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008492
Adam Lesinski5f056f62016-07-14 16:56:08 -07008493 if (mMobileRadioApWakeupCount != null) {
8494 out.writeInt(1);
8495 mMobileRadioApWakeupCount.writeToParcel(out);
8496 } else {
8497 out.writeInt(0);
8498 }
8499
8500 if (mWifiRadioApWakeupCount != null) {
8501 out.writeInt(1);
8502 mWifiRadioApWakeupCount.writeToParcel(out);
8503 } else {
8504 out.writeInt(0);
8505 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008506 }
8507
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008508 void readJobCompletionsFromParcelLocked(Parcel in) {
8509 int numJobCompletions = in.readInt();
8510 mJobCompletions.clear();
8511 for (int j = 0; j < numJobCompletions; j++) {
8512 String jobName = in.readString();
8513 int numTypes = in.readInt();
8514 if (numTypes > 0) {
8515 SparseIntArray types = new SparseIntArray();
8516 for (int k = 0; k < numTypes; k++) {
8517 int type = in.readInt();
8518 int count = in.readInt();
8519 types.put(type, count);
8520 }
8521 mJobCompletions.put(jobName, types);
8522 }
8523 }
8524 }
8525
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008526 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase, Parcel in) {
Bookatz867c0d72017-03-07 18:23:42 -08008527 mOnBatteryBackgroundTimeBase.readFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -07008528 mOnBatteryScreenOffBackgroundTimeBase.readFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -08008529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008530 int numWakelocks = in.readInt();
8531 mWakelockStats.clear();
8532 for (int j = 0; j < numWakelocks; j++) {
8533 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008534 Uid.Wakelock wakelock = new Wakelock(mBsi, this);
Bookatz5b5ec322017-05-26 09:40:38 -07008535 wakelock.readFromParcelLocked(
8536 timeBase, screenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase, in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07008537 mWakelockStats.add(wakelockName, wakelock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008538 }
8539
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008540 int numSyncs = in.readInt();
8541 mSyncStats.clear();
8542 for (int j = 0; j < numSyncs; j++) {
8543 String syncName = in.readString();
8544 if (in.readInt() != 0) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008545 mSyncStats.add(syncName, new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
8546 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008547 }
8548 }
8549
8550 int numJobs = in.readInt();
8551 mJobStats.clear();
8552 for (int j = 0; j < numJobs; j++) {
8553 String jobName = in.readString();
8554 if (in.readInt() != 0) {
Bookatzaa4594a2017-03-24 12:39:56 -07008555 mJobStats.add(jobName, new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
8556 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008557 }
8558 }
8559
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008560 readJobCompletionsFromParcelLocked(in);
8561
Amith Yamasani977e11f2018-02-16 11:29:54 -08008562 mJobsDeferredEventCount = new Counter(mBsi.mOnBatteryTimeBase, in);
8563 mJobsDeferredCount = new Counter(mBsi.mOnBatteryTimeBase, in);
8564 mJobsFreshnessTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8565 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
8566 mJobsFreshnessBuckets[i] = Counter.readCounterFromParcel(mBsi.mOnBatteryTimeBase,
8567 in);
8568 }
8569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008570 int numSensors = in.readInt();
8571 mSensorStats.clear();
8572 for (int k = 0; k < numSensors; k++) {
8573 int sensorNumber = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008574 Uid.Sensor sensor = new Sensor(mBsi, this, sensorNumber);
Bookatz867c0d72017-03-07 18:23:42 -08008575 sensor.readFromParcelLocked(mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
8576 in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008577 mSensorStats.put(sensorNumber, sensor);
8578 }
8579
8580 int numProcs = in.readInt();
8581 mProcessStats.clear();
8582 for (int k = 0; k < numProcs; k++) {
8583 String processName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008584 Uid.Proc proc = new Proc(mBsi, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008585 proc.readFromParcelLocked(in);
8586 mProcessStats.put(processName, proc);
8587 }
8588
8589 int numPkgs = in.readInt();
8590 mPackageStats.clear();
8591 for (int l = 0; l < numPkgs; l++) {
8592 String packageName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008593 Uid.Pkg pkg = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008594 pkg.readFromParcelLocked(in);
8595 mPackageStats.put(packageName, pkg);
8596 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008597
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008598 mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008599 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008600 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
8601 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008602 } else {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008603 mWifiRunningTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008604 }
8605 mFullWifiLockOut = false;
8606 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008607 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
8608 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008609 } else {
8610 mFullWifiLockTimer = null;
8611 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008612 mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008613 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08008614 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
8615 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
8616 in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008617 } else {
Nick Pelly6ccaa542012-06-15 15:22:47 -07008618 mWifiScanTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008619 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008620 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
8621 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8622 if (in.readInt() != 0) {
8623 makeWifiBatchedScanBin(i, in);
8624 } else {
8625 mWifiBatchedScanTimer[i] = null;
8626 }
8627 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008628 mWifiMulticastEnabled = false;
8629 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008630 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_MULTICAST_ENABLED,
8631 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008632 } else {
8633 mWifiMulticastTimer = null;
8634 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008635 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008636 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
8637 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008638 } else {
8639 mAudioTurnedOnTimer = null;
8640 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008641 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008642 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
8643 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008644 } else {
8645 mVideoTurnedOnTimer = null;
8646 }
8647 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008648 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8649 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008650 } else {
8651 mFlashlightTurnedOnTimer = null;
8652 }
8653 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008654 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
8655 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008656 } else {
8657 mCameraTurnedOnTimer = null;
8658 }
8659 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008660 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8661 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008662 } else {
8663 mForegroundActivityTimer = null;
8664 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008665 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008666 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8667 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase, in);
8668 } else {
8669 mForegroundServiceTimer = null;
8670 }
8671 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -07008672 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
8673 AGGREGATED_WAKE_TYPE_PARTIAL, null,
8674 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase,
8675 in);
8676 } else {
8677 mAggregatedPartialWakelockTimer = null;
8678 }
8679 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08008680 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
8681 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
8682 mOnBatteryBackgroundTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008683 } else {
8684 mBluetoothScanTimer = null;
8685 }
Bookatz956f36bf2017-04-28 09:48:17 -07008686 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -07008687 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
8688 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
8689 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in);
8690 } else {
8691 mBluetoothUnoptimizedScanTimer = null;
8692 }
8693 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -07008694 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase, in);
8695 } else {
8696 mBluetoothScanResultCounter = null;
8697 }
Bookatzb1f04f32017-05-19 13:57:32 -07008698 if (in.readInt() != 0) {
8699 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase, in);
8700 } else {
8701 mBluetoothScanResultBgCounter = null;
8702 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08008703 mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07008704 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8705 if (in.readInt() != 0) {
8706 makeProcessState(i, in);
8707 } else {
8708 mProcessStateTimer[i] = null;
8709 }
8710 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008711 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008712 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
8713 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008714 } else {
8715 mVibratorOnTimer = null;
8716 }
8717 if (in.readInt() != 0) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07008718 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
8719 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08008720 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008721 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008722 } else {
8723 mUserActivityCounters = null;
Dianne Hackborn617f8772009-03-31 15:04:46 -07008724 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008725 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008726 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
8727 mNetworkPacketActivityCounters
8728 = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008729 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008730 mNetworkByteActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08008731 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008732 mNetworkPacketActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08008733 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008734 }
Joe Onoratoabded112016-02-08 16:49:39 -08008735 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8736 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008737 } else {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008738 mNetworkByteActivityCounters = null;
8739 mNetworkPacketActivityCounters = null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008740 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008741
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008742 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008743 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008744 NUM_WIFI_TX_LEVELS, in);
8745 } else {
8746 mWifiControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07008747 }
8748
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008749 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008750 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008751 NUM_BT_TX_LEVELS, in);
8752 } else {
8753 mBluetoothControllerActivity = null;
8754 }
8755
8756 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008757 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008758 ModemActivityInfo.TX_POWER_LEVELS, in);
8759 } else {
8760 mModemControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07008761 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008762
Joe Onoratoabded112016-02-08 16:49:39 -08008763 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8764 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008765
Adam Lesinski6832f392015-09-05 18:05:40 -07008766 if (in.readInt() != 0) {
8767 int numCpuClusters = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008768 if (mBsi.mPowerProfile != null && mBsi.mPowerProfile.getNumCpuClusters() != numCpuClusters) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008769 throw new ParcelFormatException("Incompatible number of cpu clusters");
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008770 }
Adam Lesinski6832f392015-09-05 18:05:40 -07008771
Sudheer Shankaaf857412017-07-21 00:14:24 -07008772 mCpuClusterSpeedTimesUs = new LongSamplingCounter[numCpuClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -07008773 for (int cluster = 0; cluster < numCpuClusters; cluster++) {
8774 if (in.readInt() != 0) {
8775 int numSpeeds = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008776 if (mBsi.mPowerProfile != null &&
8777 mBsi.mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != numSpeeds) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008778 throw new ParcelFormatException("Incompatible number of cpu speeds");
8779 }
8780
8781 final LongSamplingCounter[] cpuSpeeds = new LongSamplingCounter[numSpeeds];
Sudheer Shankaaf857412017-07-21 00:14:24 -07008782 mCpuClusterSpeedTimesUs[cluster] = cpuSpeeds;
Adam Lesinski6832f392015-09-05 18:05:40 -07008783 for (int speed = 0; speed < numSpeeds; speed++) {
8784 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008785 cpuSpeeds[speed] = new LongSamplingCounter(
8786 mBsi.mOnBatteryTimeBase, in);
Adam Lesinski6832f392015-09-05 18:05:40 -07008787 }
8788 }
Adam Lesinskia57a5402015-09-28 10:21:33 -07008789 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008790 mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -07008791 }
8792 }
8793 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008794 mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008795 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008796
Sudheer Shanka59f5c002017-05-15 10:57:15 -07008797 mCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(in, mBsi.mOnBatteryTimeBase);
8798 mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(
8799 in, mBsi.mOnBatteryScreenOffTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008800
Mike Ma3d422c32017-10-25 11:08:57 -07008801 mCpuActiveTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8802 mCpuClusterTimesMs = new LongSamplingCounterArray(mBsi.mOnBatteryTimeBase, in);
8803
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008804 int length = in.readInt();
8805 if (length == NUM_PROCESS_STATE) {
8806 mProcStateTimeMs = new LongSamplingCounterArray[length];
8807 for (int procState = 0; procState < length; ++procState) {
8808 mProcStateTimeMs[procState] = LongSamplingCounterArray.readFromParcel(
8809 in, mBsi.mOnBatteryTimeBase);
8810 }
8811 } else {
8812 mProcStateTimeMs = null;
8813 }
8814 length = in.readInt();
8815 if (length == NUM_PROCESS_STATE) {
8816 mProcStateScreenOffTimeMs = new LongSamplingCounterArray[length];
8817 for (int procState = 0; procState < length; ++procState) {
8818 mProcStateScreenOffTimeMs[procState] = LongSamplingCounterArray.readFromParcel(
8819 in, mBsi.mOnBatteryScreenOffTimeBase);
8820 }
8821 } else {
8822 mProcStateScreenOffTimeMs = null;
8823 }
8824
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008825 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07008826 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8827 } else {
8828 mMobileRadioApWakeupCount = null;
8829 }
8830
8831 if (in.readInt() != 0) {
8832 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8833 } else {
8834 mWifiRadioApWakeupCount = null;
8835 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008836 }
8837
Amith Yamasani977e11f2018-02-16 11:29:54 -08008838 public void noteJobsDeferredLocked(int numDeferred, long sinceLast) {
8839 mJobsDeferredEventCount.addAtomic(1);
8840 mJobsDeferredCount.addAtomic(numDeferred);
8841 if (sinceLast != 0) {
8842 // Add the total time, which can be divided by the event count to get an average
8843 mJobsFreshnessTimeMs.addCountLocked(sinceLast);
8844 // Also keep track of how many times there were in these different buckets.
8845 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
8846 if (sinceLast < JOB_FRESHNESS_BUCKETS[i]) {
8847 if (mJobsFreshnessBuckets[i] == null) {
8848 mJobsFreshnessBuckets[i] = new Counter(
8849 mBsi.mOnBatteryTimeBase);
8850 }
8851 mJobsFreshnessBuckets[i].addAtomic(1);
8852 break;
8853 }
8854 }
8855 }
8856 }
8857
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008858 /**
8859 * The statistics associated with a particular wake lock.
8860 */
Joe Onoratoabded112016-02-08 16:49:39 -08008861 public static class Wakelock extends BatteryStats.Uid.Wakelock {
8862 /**
8863 * BatteryStatsImpl that we are associated with.
8864 */
8865 protected BatteryStatsImpl mBsi;
8866
8867 /**
8868 * BatteryStatsImpl that we are associated with.
8869 */
8870 protected Uid mUid;
8871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008872 /**
8873 * How long (in ms) this uid has been keeping the device partially awake.
Bookatz5b5ec322017-05-26 09:40:38 -07008874 * 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 -08008875 */
Bookatz5b5ec322017-05-26 09:40:38 -07008876 DualTimer mTimerPartial;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008877
8878 /**
8879 * How long (in ms) this uid has been keeping the device fully awake.
8880 */
Evan Millarc64edde2009-04-18 12:26:32 -07008881 StopwatchTimer mTimerFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008882
8883 /**
8884 * How long (in ms) this uid has had a window keeping the device awake.
8885 */
Evan Millarc64edde2009-04-18 12:26:32 -07008886 StopwatchTimer mTimerWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008887
8888 /**
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008889 * How long (in ms) this uid has had a draw wake lock.
Adam Lesinski9425fe22015-06-19 12:02:13 -07008890 */
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008891 StopwatchTimer mTimerDraw;
Adam Lesinski9425fe22015-06-19 12:02:13 -07008892
Joe Onoratoabded112016-02-08 16:49:39 -08008893 public Wakelock(BatteryStatsImpl bsi, Uid uid) {
8894 mBsi = bsi;
8895 mUid = uid;
8896 }
8897
Adam Lesinski9425fe22015-06-19 12:02:13 -07008898 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008899 * Reads a possibly null Timer from a Parcel. The timer is associated with the
8900 * proper timer pool from the given BatteryStatsImpl object.
8901 *
8902 * @param in the Parcel to be read from.
8903 * return a new Timer, or null.
8904 */
Joe Onorato92fd23f2016-07-25 11:18:42 -07008905 private StopwatchTimer readStopwatchTimerFromParcel(int type,
8906 ArrayList<StopwatchTimer> pool, TimeBase timeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008907 if (in.readInt() == 0) {
8908 return null;
8909 }
8910
Joe Onoratoabded112016-02-08 16:49:39 -08008911 return new StopwatchTimer(mBsi.mClocks, mUid, type, pool, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008912 }
8913
Joe Onorato92fd23f2016-07-25 11:18:42 -07008914 /**
8915 * Reads a possibly null Timer from a Parcel. The timer is associated with the
8916 * proper timer pool from the given BatteryStatsImpl object.
8917 *
8918 * @param in the Parcel to be read from.
8919 * return a new Timer, or null.
8920 */
Bookatz5b5ec322017-05-26 09:40:38 -07008921 private DualTimer readDualTimerFromParcel(int type, ArrayList<StopwatchTimer> pool,
8922 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07008923 if (in.readInt() == 0) {
8924 return null;
8925 }
8926
Bookatz5b5ec322017-05-26 09:40:38 -07008927 return new DualTimer(mBsi.mClocks, mUid, type, pool, timeBase, bgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07008928 }
8929
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008930 boolean reset() {
8931 boolean wlactive = false;
8932 if (mTimerFull != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008933 wlactive |= !mTimerFull.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008934 }
8935 if (mTimerPartial != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008936 wlactive |= !mTimerPartial.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008937 }
8938 if (mTimerWindow != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008939 wlactive |= !mTimerWindow.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008940 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008941 if (mTimerDraw != null) {
8942 wlactive |= !mTimerDraw.reset(false);
Adam Lesinski9425fe22015-06-19 12:02:13 -07008943 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008944 if (!wlactive) {
8945 if (mTimerFull != null) {
8946 mTimerFull.detach();
8947 mTimerFull = null;
8948 }
8949 if (mTimerPartial != null) {
8950 mTimerPartial.detach();
8951 mTimerPartial = null;
8952 }
8953 if (mTimerWindow != null) {
8954 mTimerWindow.detach();
8955 mTimerWindow = null;
8956 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008957 if (mTimerDraw != null) {
8958 mTimerDraw.detach();
8959 mTimerDraw = null;
Adam Lesinski9425fe22015-06-19 12:02:13 -07008960 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008961 }
8962 return !wlactive;
8963 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008964
Bookatz5b5ec322017-05-26 09:40:38 -07008965 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase,
8966 TimeBase screenOffBgTimeBase, Parcel in) {
8967 mTimerPartial = readDualTimerFromParcel(WAKE_TYPE_PARTIAL,
8968 mBsi.mPartialTimers, screenOffTimeBase, screenOffBgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07008969 mTimerFull = readStopwatchTimerFromParcel(WAKE_TYPE_FULL,
8970 mBsi.mFullTimers, timeBase, in);
8971 mTimerWindow = readStopwatchTimerFromParcel(WAKE_TYPE_WINDOW,
8972 mBsi.mWindowTimers, timeBase, in);
8973 mTimerDraw = readStopwatchTimerFromParcel(WAKE_TYPE_DRAW,
8974 mBsi.mDrawTimers, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008975 }
8976
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008977 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
8978 Timer.writeTimerToParcel(out, mTimerPartial, elapsedRealtimeUs);
8979 Timer.writeTimerToParcel(out, mTimerFull, elapsedRealtimeUs);
8980 Timer.writeTimerToParcel(out, mTimerWindow, elapsedRealtimeUs);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008981 Timer.writeTimerToParcel(out, mTimerDraw, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008982 }
8983
8984 @Override
8985 public Timer getWakeTime(int type) {
8986 switch (type) {
8987 case WAKE_TYPE_FULL: return mTimerFull;
8988 case WAKE_TYPE_PARTIAL: return mTimerPartial;
8989 case WAKE_TYPE_WINDOW: return mTimerWindow;
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008990 case WAKE_TYPE_DRAW: return mTimerDraw;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008991 default: throw new IllegalArgumentException("type = " + type);
8992 }
8993 }
8994 }
8995
Joe Onoratoabded112016-02-08 16:49:39 -08008996 public static class Sensor extends BatteryStats.Uid.Sensor {
8997 /**
8998 * BatteryStatsImpl that we are associated with.
8999 */
9000 protected BatteryStatsImpl mBsi;
9001
9002 /**
Bookatz867c0d72017-03-07 18:23:42 -08009003 * Uid that we are associated with.
Joe Onoratoabded112016-02-08 16:49:39 -08009004 */
9005 protected Uid mUid;
9006
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009007 final int mHandle;
Bookatz867c0d72017-03-07 18:23:42 -08009008 DualTimer mTimer;
Amith Yamasaniab9ad192016-12-06 12:46:59 -08009009
Joe Onoratoabded112016-02-08 16:49:39 -08009010 public Sensor(BatteryStatsImpl bsi, Uid uid, int handle) {
9011 mBsi = bsi;
9012 mUid = uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009013 mHandle = handle;
9014 }
9015
Bookatz867c0d72017-03-07 18:23:42 -08009016 private DualTimer readTimersFromParcel(
9017 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009018 if (in.readInt() == 0) {
9019 return null;
9020 }
9021
Joe Onoratoabded112016-02-08 16:49:39 -08009022 ArrayList<StopwatchTimer> pool = mBsi.mSensorTimers.get(mHandle);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009023 if (pool == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07009024 pool = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08009025 mBsi.mSensorTimers.put(mHandle, pool);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009026 }
Bookatz867c0d72017-03-07 18:23:42 -08009027 return new DualTimer(mBsi.mClocks, mUid, 0, pool, timeBase, bgTimeBase, in);
Amith Yamasaniab9ad192016-12-06 12:46:59 -08009028 }
9029
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009030 boolean reset() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009031 if (mTimer.reset(true)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009032 mTimer = null;
9033 return true;
9034 }
9035 return false;
9036 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009037
Bookatz867c0d72017-03-07 18:23:42 -08009038 void readFromParcelLocked(TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
9039 mTimer = readTimersFromParcel(timeBase, bgTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009040 }
9041
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009042 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07009043 Timer.writeTimerToParcel(out, mTimer, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009044 }
9045
9046 @Override
9047 public Timer getSensorTime() {
Bookatzaa4594a2017-03-24 12:39:56 -07009048 return mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009049 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009050
9051 @Override
Bookatz867c0d72017-03-07 18:23:42 -08009052 public Timer getSensorBackgroundTime() {
9053 if (mTimer == null) {
9054 return null;
9055 }
9056 return mTimer.getSubTimer();
Amith Yamasaniab9ad192016-12-06 12:46:59 -08009057 }
9058
9059 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009060 public int getHandle() {
9061 return mHandle;
9062 }
9063 }
9064
9065 /**
9066 * The statistics associated with a particular process.
9067 */
Joe Onoratoabded112016-02-08 16:49:39 -08009068 public static class Proc extends BatteryStats.Uid.Proc implements TimeBaseObs {
9069 /**
9070 * BatteryStatsImpl that we are associated with.
9071 */
9072 protected BatteryStatsImpl mBsi;
9073
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009074 /**
Dianne Hackborncd0e3352014-08-07 17:08:09 -07009075 * The name of this process.
9076 */
9077 final String mName;
9078
9079 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -08009080 * Remains true until removed from the stats.
9081 */
9082 boolean mActive = true;
9083
9084 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07009085 * Total time (in ms) spent executing in user code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009086 */
9087 long mUserTime;
9088
9089 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07009090 * Total time (in ms) spent executing in kernel code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009091 */
9092 long mSystemTime;
9093
9094 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07009095 * Amount of time (in ms) the process was running in the foreground.
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009096 */
9097 long mForegroundTime;
9098
9099 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009100 * Number of times the process has been started.
9101 */
9102 int mStarts;
9103
9104 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009105 * Number of times the process has crashed.
9106 */
9107 int mNumCrashes;
9108
9109 /**
9110 * Number of times the process has had an ANR.
9111 */
9112 int mNumAnrs;
9113
9114 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009115 * The amount of user time loaded from a previous save.
9116 */
9117 long mLoadedUserTime;
9118
9119 /**
9120 * The amount of system time loaded from a previous save.
9121 */
9122 long mLoadedSystemTime;
9123
9124 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009125 * The amount of foreground time loaded from a previous save.
9126 */
9127 long mLoadedForegroundTime;
9128
9129 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009130 * The number of times the process has started from a previous save.
9131 */
9132 int mLoadedStarts;
9133
9134 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009135 * Number of times the process has crashed from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009136 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009137 int mLoadedNumCrashes;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009138
9139 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009140 * Number of times the process has had an ANR from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009141 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009142 int mLoadedNumAnrs;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009143
9144 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009145 * The amount of user time when last unplugged.
9146 */
9147 long mUnpluggedUserTime;
9148
9149 /**
9150 * The amount of system time when last unplugged.
9151 */
9152 long mUnpluggedSystemTime;
9153
9154 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009155 * The amount of foreground time since unplugged.
9156 */
9157 long mUnpluggedForegroundTime;
9158
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009159 /**
9160 * The number of times the process has started before unplugged.
9161 */
9162 int mUnpluggedStarts;
9163
Dianne Hackborn61659e52014-07-09 16:13:01 -07009164 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009165 * Number of times the process has crashed before unplugged.
9166 */
9167 int mUnpluggedNumCrashes;
9168
9169 /**
9170 * Number of times the process has had an ANR before unplugged.
9171 */
9172 int mUnpluggedNumAnrs;
9173
Dianne Hackborn287952c2010-09-22 22:34:31 -07009174 ArrayList<ExcessivePower> mExcessivePower;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009175
Joe Onoratoabded112016-02-08 16:49:39 -08009176 public Proc(BatteryStatsImpl bsi, String name) {
9177 mBsi = bsi;
Dianne Hackborncd0e3352014-08-07 17:08:09 -07009178 mName = name;
Joe Onoratoabded112016-02-08 16:49:39 -08009179 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009180 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07009181
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009182 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009183 mUnpluggedUserTime = mUserTime;
9184 mUnpluggedSystemTime = mSystemTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009185 mUnpluggedForegroundTime = mForegroundTime;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009186 mUnpluggedStarts = mStarts;
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009187 mUnpluggedNumCrashes = mNumCrashes;
9188 mUnpluggedNumAnrs = mNumAnrs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009189 }
9190
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009191 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009192 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009193
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009194 void detach() {
Dianne Hackborn099bc622014-01-22 13:39:16 -08009195 mActive = false;
Joe Onoratoabded112016-02-08 16:49:39 -08009196 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009197 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009198
Dianne Hackborn287952c2010-09-22 22:34:31 -07009199 public int countExcessivePowers() {
9200 return mExcessivePower != null ? mExcessivePower.size() : 0;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009201 }
9202
Dianne Hackborn287952c2010-09-22 22:34:31 -07009203 public ExcessivePower getExcessivePower(int i) {
9204 if (mExcessivePower != null) {
9205 return mExcessivePower.get(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009206 }
9207 return null;
9208 }
9209
Dianne Hackborn287952c2010-09-22 22:34:31 -07009210 public void addExcessiveCpu(long overTime, long usedTime) {
9211 if (mExcessivePower == null) {
9212 mExcessivePower = new ArrayList<ExcessivePower>();
9213 }
9214 ExcessivePower ew = new ExcessivePower();
9215 ew.type = ExcessivePower.TYPE_CPU;
9216 ew.overTime = overTime;
9217 ew.usedTime = usedTime;
9218 mExcessivePower.add(ew);
9219 }
9220
9221 void writeExcessivePowerToParcelLocked(Parcel out) {
9222 if (mExcessivePower == null) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009223 out.writeInt(0);
9224 return;
9225 }
9226
Dianne Hackborn287952c2010-09-22 22:34:31 -07009227 final int N = mExcessivePower.size();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009228 out.writeInt(N);
9229 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009230 ExcessivePower ew = mExcessivePower.get(i);
9231 out.writeInt(ew.type);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009232 out.writeLong(ew.overTime);
9233 out.writeLong(ew.usedTime);
9234 }
9235 }
9236
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009237 void readExcessivePowerFromParcelLocked(Parcel in) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009238 final int N = in.readInt();
9239 if (N == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009240 mExcessivePower = null;
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009241 return;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009242 }
9243
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08009244 if (N > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009245 throw new ParcelFormatException(
9246 "File corrupt: too many excessive power entries " + N);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08009247 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009248
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009249 mExcessivePower = new ArrayList<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009250 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009251 ExcessivePower ew = new ExcessivePower();
9252 ew.type = in.readInt();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009253 ew.overTime = in.readLong();
9254 ew.usedTime = in.readLong();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009255 mExcessivePower.add(ew);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009256 }
9257 }
9258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009259 void writeToParcelLocked(Parcel out) {
9260 out.writeLong(mUserTime);
9261 out.writeLong(mSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009262 out.writeLong(mForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009263 out.writeInt(mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009264 out.writeInt(mNumCrashes);
9265 out.writeInt(mNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009266 out.writeLong(mLoadedUserTime);
9267 out.writeLong(mLoadedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009268 out.writeLong(mLoadedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009269 out.writeInt(mLoadedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009270 out.writeInt(mLoadedNumCrashes);
9271 out.writeInt(mLoadedNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009272 out.writeLong(mUnpluggedUserTime);
9273 out.writeLong(mUnpluggedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009274 out.writeLong(mUnpluggedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009275 out.writeInt(mUnpluggedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009276 out.writeInt(mUnpluggedNumCrashes);
9277 out.writeInt(mUnpluggedNumAnrs);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009278 writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009279 }
9280
9281 void readFromParcelLocked(Parcel in) {
9282 mUserTime = in.readLong();
9283 mSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009284 mForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009285 mStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009286 mNumCrashes = in.readInt();
9287 mNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009288 mLoadedUserTime = in.readLong();
9289 mLoadedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009290 mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009291 mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009292 mLoadedNumCrashes = in.readInt();
9293 mLoadedNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009294 mUnpluggedUserTime = in.readLong();
9295 mUnpluggedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009296 mUnpluggedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009297 mUnpluggedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009298 mUnpluggedNumCrashes = in.readInt();
9299 mUnpluggedNumAnrs = in.readInt();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009300 readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009301 }
9302
Adam Lesinski06af1fa2015-05-05 17:35:35 -07009303 public void addCpuTimeLocked(int utime, int stime) {
Sudheer Shankac57729a2018-02-09 15:44:42 -08009304 addCpuTimeLocked(utime, stime, mBsi.mOnBatteryTimeBase.isRunning());
9305 }
9306
9307 public void addCpuTimeLocked(int utime, int stime, boolean isRunning) {
9308 if (isRunning) {
9309 mUserTime += utime;
9310 mSystemTime += stime;
9311 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009312 }
9313
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009314 public void addForegroundTimeLocked(long ttime) {
9315 mForegroundTime += ttime;
9316 }
9317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009318 public void incStartsLocked() {
9319 mStarts++;
9320 }
9321
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009322 public void incNumCrashesLocked() {
9323 mNumCrashes++;
9324 }
9325
9326 public void incNumAnrsLocked() {
9327 mNumAnrs++;
9328 }
9329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009330 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -08009331 public boolean isActive() {
9332 return mActive;
9333 }
9334
9335 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009336 public long getUserTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009337 long val = mUserTime;
9338 if (which == STATS_CURRENT) {
9339 val -= mLoadedUserTime;
9340 } else if (which == STATS_SINCE_UNPLUGGED) {
9341 val -= mUnpluggedUserTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009342 }
9343 return val;
9344 }
9345
9346 @Override
9347 public long getSystemTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009348 long val = mSystemTime;
9349 if (which == STATS_CURRENT) {
9350 val -= mLoadedSystemTime;
9351 } else if (which == STATS_SINCE_UNPLUGGED) {
9352 val -= mUnpluggedSystemTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009353 }
9354 return val;
9355 }
9356
9357 @Override
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009358 public long getForegroundTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009359 long val = mForegroundTime;
9360 if (which == STATS_CURRENT) {
9361 val -= mLoadedForegroundTime;
9362 } else if (which == STATS_SINCE_UNPLUGGED) {
9363 val -= mUnpluggedForegroundTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009364 }
9365 return val;
9366 }
9367
9368 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009369 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009370 int val = mStarts;
9371 if (which == STATS_CURRENT) {
9372 val -= mLoadedStarts;
9373 } else if (which == STATS_SINCE_UNPLUGGED) {
9374 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009375 }
9376 return val;
9377 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07009378
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009379 @Override
9380 public int getNumCrashes(int which) {
9381 int val = mNumCrashes;
9382 if (which == STATS_CURRENT) {
9383 val -= mLoadedNumCrashes;
9384 } else if (which == STATS_SINCE_UNPLUGGED) {
9385 val -= mUnpluggedNumCrashes;
9386 }
9387 return val;
9388 }
9389
9390 @Override
9391 public int getNumAnrs(int which) {
9392 int val = mNumAnrs;
9393 if (which == STATS_CURRENT) {
9394 val -= mLoadedNumAnrs;
9395 } else if (which == STATS_SINCE_UNPLUGGED) {
9396 val -= mUnpluggedNumAnrs;
9397 }
9398 return val;
9399 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009400 }
9401
9402 /**
9403 * The statistics associated with a particular package.
9404 */
Joe Onoratoabded112016-02-08 16:49:39 -08009405 public static class Pkg extends BatteryStats.Uid.Pkg implements TimeBaseObs {
9406 /**
9407 * BatteryStatsImpl that we are associated with.
9408 */
9409 protected BatteryStatsImpl mBsi;
9410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009411 /**
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009412 * Number of times wakeup alarms have occurred for this app.
Bookatz98d4d5c2017-08-01 19:07:54 -07009413 * On screen-off timebase starting in report v25.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009414 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009415 ArrayMap<String, Counter> mWakeupAlarms = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009416
9417 /**
9418 * The statics we have collected for this package's services.
9419 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009420 final ArrayMap<String, Serv> mServiceStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009421
Joe Onoratoabded112016-02-08 16:49:39 -08009422 public Pkg(BatteryStatsImpl bsi) {
9423 mBsi = bsi;
9424 mBsi.mOnBatteryScreenOffTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009425 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009426
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009427 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009428 }
9429
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009430 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009431 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009432
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009433 void detach() {
Joe Onoratoabded112016-02-08 16:49:39 -08009434 mBsi.mOnBatteryScreenOffTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009435 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009437 void readFromParcelLocked(Parcel in) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009438 int numWA = in.readInt();
9439 mWakeupAlarms.clear();
9440 for (int i=0; i<numWA; i++) {
9441 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -07009442 mWakeupAlarms.put(tag, new Counter(mBsi.mOnBatteryScreenOffTimeBase, in));
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009443 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009444
9445 int numServs = in.readInt();
9446 mServiceStats.clear();
9447 for (int m = 0; m < numServs; m++) {
9448 String serviceName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08009449 Uid.Pkg.Serv serv = new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009450 mServiceStats.put(serviceName, serv);
9451
9452 serv.readFromParcelLocked(in);
9453 }
9454 }
9455
9456 void writeToParcelLocked(Parcel out) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009457 int numWA = mWakeupAlarms.size();
9458 out.writeInt(numWA);
9459 for (int i=0; i<numWA; i++) {
9460 out.writeString(mWakeupAlarms.keyAt(i));
9461 mWakeupAlarms.valueAt(i).writeToParcel(out);
9462 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009463
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009464 final int NS = mServiceStats.size();
9465 out.writeInt(NS);
9466 for (int i=0; i<NS; i++) {
9467 out.writeString(mServiceStats.keyAt(i));
9468 Uid.Pkg.Serv serv = mServiceStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009469 serv.writeToParcelLocked(out);
9470 }
9471 }
9472
9473 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009474 public ArrayMap<String, ? extends BatteryStats.Counter> getWakeupAlarmStats() {
9475 return mWakeupAlarms;
9476 }
9477
9478 public void noteWakeupAlarmLocked(String tag) {
9479 Counter c = mWakeupAlarms.get(tag);
9480 if (c == null) {
Bookatz98d4d5c2017-08-01 19:07:54 -07009481 c = new Counter(mBsi.mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009482 mWakeupAlarms.put(tag, c);
9483 }
9484 c.stepAtomic();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009485 }
9486
9487 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009488 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg.Serv> getServiceStats() {
9489 return mServiceStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009490 }
9491
9492 /**
9493 * The statistics associated with a particular service.
9494 */
Joe Onoratoabded112016-02-08 16:49:39 -08009495 public static class Serv extends BatteryStats.Uid.Pkg.Serv implements TimeBaseObs {
9496 /**
9497 * BatteryStatsImpl that we are associated with.
9498 */
9499 protected BatteryStatsImpl mBsi;
9500
9501 /**
9502 * The android package in which this service resides.
9503 */
9504 protected Pkg mPkg;
9505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009506 /**
9507 * Total time (ms in battery uptime) the service has been left started.
9508 */
Joe Onoratoabded112016-02-08 16:49:39 -08009509 protected long mStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009510
9511 /**
9512 * If service has been started and not yet stopped, this is
9513 * when it was started.
9514 */
Joe Onoratoabded112016-02-08 16:49:39 -08009515 protected long mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009516
9517 /**
9518 * True if we are currently running.
9519 */
Joe Onoratoabded112016-02-08 16:49:39 -08009520 protected boolean mRunning;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009521
9522 /**
9523 * Total number of times startService() has been called.
9524 */
Joe Onoratoabded112016-02-08 16:49:39 -08009525 protected int mStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009526
9527 /**
9528 * Total time (ms in battery uptime) the service has been left launched.
9529 */
Joe Onoratoabded112016-02-08 16:49:39 -08009530 protected long mLaunchedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009531
9532 /**
9533 * If service has been launched and not yet exited, this is
9534 * when it was launched (ms in battery uptime).
9535 */
Joe Onoratoabded112016-02-08 16:49:39 -08009536 protected long mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009537
9538 /**
9539 * True if we are currently launched.
9540 */
Joe Onoratoabded112016-02-08 16:49:39 -08009541 protected boolean mLaunched;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009542
9543 /**
9544 * Total number times the service has been launched.
9545 */
Joe Onoratoabded112016-02-08 16:49:39 -08009546 protected int mLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009547
9548 /**
9549 * The amount of time spent started loaded from a previous save
9550 * (ms in battery uptime).
9551 */
Joe Onoratoabded112016-02-08 16:49:39 -08009552 protected long mLoadedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009553
9554 /**
9555 * The number of starts loaded from a previous save.
9556 */
Joe Onoratoabded112016-02-08 16:49:39 -08009557 protected int mLoadedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009558
9559 /**
9560 * The number of launches loaded from a previous save.
9561 */
Joe Onoratoabded112016-02-08 16:49:39 -08009562 protected int mLoadedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009563
9564 /**
9565 * The amount of time spent started as of the last run (ms
9566 * in battery uptime).
9567 */
Joe Onoratoabded112016-02-08 16:49:39 -08009568 protected long mLastStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009569
9570 /**
9571 * The number of starts as of the last run.
9572 */
Joe Onoratoabded112016-02-08 16:49:39 -08009573 protected int mLastStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009574
9575 /**
9576 * The number of launches as of the last run.
9577 */
Joe Onoratoabded112016-02-08 16:49:39 -08009578 protected int mLastLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009579
9580 /**
9581 * The amount of time spent started when last unplugged (ms
9582 * in battery uptime).
9583 */
Joe Onoratoabded112016-02-08 16:49:39 -08009584 protected long mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009585
9586 /**
9587 * The number of starts when last unplugged.
9588 */
Joe Onoratoabded112016-02-08 16:49:39 -08009589 protected int mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009590
9591 /**
9592 * The number of launches when last unplugged.
9593 */
Joe Onoratoabded112016-02-08 16:49:39 -08009594 protected int mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009595
Joe Onoratoabded112016-02-08 16:49:39 -08009596 /**
9597 * Construct a Serv. Also adds it to the on-battery time base as a listener.
9598 */
9599 public Serv(BatteryStatsImpl bsi) {
9600 mBsi = bsi;
9601 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009602 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009603
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009604 public void onTimeStarted(long elapsedRealtime, long baseUptime,
9605 long baseRealtime) {
9606 mUnpluggedStartTime = getStartTimeToNowLocked(baseUptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009607 mUnpluggedStarts = mStarts;
9608 mUnpluggedLaunches = mLaunches;
9609 }
9610
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009611 public void onTimeStopped(long elapsedRealtime, long baseUptime,
9612 long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009613 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009614
Joe Onoratoabded112016-02-08 16:49:39 -08009615 /**
9616 * Remove this Serv as a listener from the time base.
9617 */
9618 public void detach() {
9619 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009620 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009621
Joe Onoratoabded112016-02-08 16:49:39 -08009622 public void readFromParcelLocked(Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009623 mStartTime = in.readLong();
9624 mRunningSince = in.readLong();
9625 mRunning = in.readInt() != 0;
9626 mStarts = in.readInt();
9627 mLaunchedTime = in.readLong();
9628 mLaunchedSince = in.readLong();
9629 mLaunched = in.readInt() != 0;
9630 mLaunches = in.readInt();
9631 mLoadedStartTime = in.readLong();
9632 mLoadedStarts = in.readInt();
9633 mLoadedLaunches = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07009634 mLastStartTime = 0;
9635 mLastStarts = 0;
9636 mLastLaunches = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009637 mUnpluggedStartTime = in.readLong();
9638 mUnpluggedStarts = in.readInt();
9639 mUnpluggedLaunches = in.readInt();
9640 }
9641
Joe Onoratoabded112016-02-08 16:49:39 -08009642 public void writeToParcelLocked(Parcel out) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009643 out.writeLong(mStartTime);
9644 out.writeLong(mRunningSince);
9645 out.writeInt(mRunning ? 1 : 0);
9646 out.writeInt(mStarts);
9647 out.writeLong(mLaunchedTime);
9648 out.writeLong(mLaunchedSince);
9649 out.writeInt(mLaunched ? 1 : 0);
9650 out.writeInt(mLaunches);
9651 out.writeLong(mLoadedStartTime);
9652 out.writeInt(mLoadedStarts);
9653 out.writeInt(mLoadedLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009654 out.writeLong(mUnpluggedStartTime);
9655 out.writeInt(mUnpluggedStarts);
9656 out.writeInt(mUnpluggedLaunches);
9657 }
9658
Joe Onoratoabded112016-02-08 16:49:39 -08009659 public long getLaunchTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009660 if (!mLaunched) return mLaunchedTime;
9661 return mLaunchedTime + batteryUptime - mLaunchedSince;
9662 }
9663
Joe Onoratoabded112016-02-08 16:49:39 -08009664 public long getStartTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009665 if (!mRunning) return mStartTime;
9666 return mStartTime + batteryUptime - mRunningSince;
9667 }
9668
9669 public void startLaunchedLocked() {
9670 if (!mLaunched) {
9671 mLaunches++;
Joe Onoratoabded112016-02-08 16:49:39 -08009672 mLaunchedSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009673 mLaunched = true;
9674 }
9675 }
9676
9677 public void stopLaunchedLocked() {
9678 if (mLaunched) {
Joe Onoratoabded112016-02-08 16:49:39 -08009679 long time = mBsi.getBatteryUptimeLocked() - mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009680 if (time > 0) {
9681 mLaunchedTime += time;
9682 } else {
9683 mLaunches--;
9684 }
9685 mLaunched = false;
9686 }
9687 }
9688
9689 public void startRunningLocked() {
9690 if (!mRunning) {
9691 mStarts++;
Joe Onoratoabded112016-02-08 16:49:39 -08009692 mRunningSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009693 mRunning = true;
9694 }
9695 }
9696
9697 public void stopRunningLocked() {
9698 if (mRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08009699 long time = mBsi.getBatteryUptimeLocked() - mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009700 if (time > 0) {
9701 mStartTime += time;
9702 } else {
9703 mStarts--;
9704 }
9705 mRunning = false;
9706 }
9707 }
9708
9709 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -08009710 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009711 }
9712
9713 @Override
9714 public int getLaunches(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009715 int val = mLaunches;
9716 if (which == STATS_CURRENT) {
9717 val -= mLoadedLaunches;
9718 } else if (which == STATS_SINCE_UNPLUGGED) {
9719 val -= mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009720 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009721 return val;
9722 }
9723
9724 @Override
9725 public long getStartTime(long now, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009726 long val = getStartTimeToNowLocked(now);
9727 if (which == STATS_CURRENT) {
9728 val -= mLoadedStartTime;
9729 } else if (which == STATS_SINCE_UNPLUGGED) {
9730 val -= mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009731 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009732 return val;
9733 }
9734
9735 @Override
9736 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009737 int val = mStarts;
9738 if (which == STATS_CURRENT) {
9739 val -= mLoadedStarts;
9740 } else if (which == STATS_SINCE_UNPLUGGED) {
9741 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009742 }
9743
9744 return val;
9745 }
9746 }
9747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009748 final Serv newServiceStatsLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08009749 return new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009750 }
9751 }
9752
9753 /**
9754 * Retrieve the statistics object for a particular process, creating
9755 * if needed.
9756 */
9757 public Proc getProcessStatsLocked(String name) {
9758 Proc ps = mProcessStats.get(name);
9759 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08009760 ps = new Proc(mBsi, name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009761 mProcessStats.put(name, ps);
9762 }
9763
9764 return ps;
9765 }
9766
Andreas Gampe3f24e692018-02-05 13:24:28 -08009767 @GuardedBy("mBsi")
Dianne Hackborna8d10942015-11-19 17:55:19 -08009768 public void updateUidProcessStateLocked(int procState) {
9769 int uidRunningState;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009770 // Make special note of Foreground Services
9771 final boolean userAwareService =
9772 (procState == ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009773 uidRunningState = BatteryStats.mapToInternalProcessState(procState);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009774
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009775 if (mProcessState == uidRunningState && userAwareService == mInForegroundService) {
9776 return;
9777 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08009778
Bookatz867c0d72017-03-07 18:23:42 -08009779 final long elapsedRealtimeMs = mBsi.mClocks.elapsedRealtime();
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009780 if (mProcessState != uidRunningState) {
9781 final long uptimeMs = mBsi.mClocks.uptimeMillis();
Dianne Hackborna8d10942015-11-19 17:55:19 -08009782
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009783 if (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
9784 mProcessStateTimer[mProcessState].stopRunningLocked(elapsedRealtimeMs);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009785
Sudheer Shanka5c19b892018-01-05 17:25:46 -08009786 if (mBsi.trackPerProcStateCpuTimes()) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009787 if (mBsi.mPendingUids.size() == 0) {
Sudheer Shankae544d162017-12-28 17:06:20 -08009788 mBsi.mExternalSync.scheduleReadProcStateCpuTimes(
9789 mBsi.mOnBatteryTimeBase.isRunning(),
Sudheer Shankac20379e2018-02-15 00:06:21 -08009790 mBsi.mOnBatteryScreenOffTimeBase.isRunning(),
9791 mBsi.mConstants.PROC_STATE_CPU_TIMES_READ_DELAY_MS);
Mike Ma234d1822018-03-13 18:53:21 -07009792 mBsi.mNumSingleUidCpuTimeReads++;
Sudheer Shankac20379e2018-02-15 00:06:21 -08009793 } else {
Mike Ma234d1822018-03-13 18:53:21 -07009794 mBsi.mNumBatchedSingleUidCpuTimeReads++;
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009795 }
9796 if (mBsi.mPendingUids.indexOfKey(mUid) < 0
9797 || ArrayUtils.contains(CRITICAL_PROC_STATES, mProcessState)) {
9798 mBsi.mPendingUids.put(mUid, mProcessState);
9799 }
9800 } else {
9801 mBsi.mPendingUids.clear();
9802 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07009803 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009804 mProcessState = uidRunningState;
9805 if (uidRunningState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
9806 if (mProcessStateTimer[uidRunningState] == null) {
9807 makeProcessState(uidRunningState, null);
9808 }
9809 mProcessStateTimer[uidRunningState].startRunningLocked(elapsedRealtimeMs);
9810 }
9811
9812 updateOnBatteryBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
9813 updateOnBatteryScreenOffBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009814 }
Bookatz867c0d72017-03-07 18:23:42 -08009815
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009816 if (userAwareService != mInForegroundService) {
9817 if (userAwareService) {
9818 noteForegroundServiceResumedLocked(elapsedRealtimeMs);
9819 } else {
9820 noteForegroundServicePausedLocked(elapsedRealtimeMs);
9821 }
9822 mInForegroundService = userAwareService;
9823 }
Bookatz867c0d72017-03-07 18:23:42 -08009824 }
9825
Bookatzc8c44962017-05-11 12:12:54 -07009826 /** Whether to consider Uid to be in the background for background timebase purposes. */
9827 public boolean isInBackground() {
Bookatz867c0d72017-03-07 18:23:42 -08009828 // Note that PROCESS_STATE_CACHED and ActivityManager.PROCESS_STATE_NONEXISTENT is
9829 // also considered to be 'background' for our purposes, because it's not foreground.
Bookatzc8c44962017-05-11 12:12:54 -07009830 return mProcessState >= PROCESS_STATE_BACKGROUND;
9831 }
9832
9833 public boolean updateOnBatteryBgTimeBase(long uptimeUs, long realtimeUs) {
9834 boolean on = mBsi.mOnBatteryTimeBase.isRunning() && isInBackground();
9835 return mOnBatteryBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
9836 }
9837
9838 public boolean updateOnBatteryScreenOffBgTimeBase(long uptimeUs, long realtimeUs) {
9839 boolean on = mBsi.mOnBatteryScreenOffTimeBase.isRunning() && isInBackground();
9840 return mOnBatteryScreenOffBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009841 }
9842
Dianne Hackbornb5e31652010-09-07 12:13:55 -07009843 public SparseArray<? extends Pid> getPidStats() {
9844 return mPids;
9845 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009846
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009847 public Pid getPidStatsLocked(int pid) {
9848 Pid p = mPids.get(pid);
9849 if (p == null) {
9850 p = new Pid();
9851 mPids.put(pid, p);
9852 }
9853 return p;
9854 }
9855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009856 /**
9857 * Retrieve the statistics object for a particular service, creating
9858 * if needed.
9859 */
9860 public Pkg getPackageStatsLocked(String name) {
9861 Pkg ps = mPackageStats.get(name);
9862 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08009863 ps = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009864 mPackageStats.put(name, ps);
9865 }
9866
9867 return ps;
9868 }
9869
9870 /**
9871 * Retrieve the statistics object for a particular service, creating
9872 * if needed.
9873 */
9874 public Pkg.Serv getServiceStatsLocked(String pkg, String serv) {
9875 Pkg ps = getPackageStatsLocked(pkg);
9876 Pkg.Serv ss = ps.mServiceStats.get(serv);
9877 if (ss == null) {
9878 ss = ps.newServiceStatsLocked();
9879 ps.mServiceStats.put(serv, ss);
9880 }
9881
9882 return ss;
9883 }
9884
Dianne Hackbornd953c532014-08-16 18:17:38 -07009885 public void readSyncSummaryFromParcelLocked(String name, Parcel in) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009886 DualTimer timer = mSyncStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07009887 timer.readSummaryFromParcelLocked(in);
9888 mSyncStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009889 }
9890
Dianne Hackbornd953c532014-08-16 18:17:38 -07009891 public void readJobSummaryFromParcelLocked(String name, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07009892 DualTimer timer = mJobStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07009893 timer.readSummaryFromParcelLocked(in);
9894 mJobStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009895 }
9896
Dianne Hackbornd953c532014-08-16 18:17:38 -07009897 public void readWakeSummaryFromParcelLocked(String wlName, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08009898 Wakelock wl = new Wakelock(mBsi, this);
Dianne Hackbornd953c532014-08-16 18:17:38 -07009899 mWakelockStats.add(wlName, wl);
9900 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009901 getWakelockTimerLocked(wl, WAKE_TYPE_FULL).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009902 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07009903 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009904 getWakelockTimerLocked(wl, WAKE_TYPE_PARTIAL).readSummaryFromParcelLocked(in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07009905 }
9906 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009907 getWakelockTimerLocked(wl, WAKE_TYPE_WINDOW).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009908 }
Adam Lesinski9425fe22015-06-19 12:02:13 -07009909 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009910 getWakelockTimerLocked(wl, WAKE_TYPE_DRAW).readSummaryFromParcelLocked(in);
Adam Lesinski9425fe22015-06-19 12:02:13 -07009911 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009912 }
9913
Bookatz867c0d72017-03-07 18:23:42 -08009914 public DualTimer getSensorTimerLocked(int sensor, boolean create) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009915 Sensor se = mSensorStats.get(sensor);
9916 if (se == null) {
9917 if (!create) {
9918 return null;
9919 }
Joe Onoratoabded112016-02-08 16:49:39 -08009920 se = new Sensor(mBsi, this, sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009921 mSensorStats.put(sensor, se);
9922 }
Bookatz867c0d72017-03-07 18:23:42 -08009923 DualTimer t = se.mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009924 if (t != null) {
9925 return t;
9926 }
Joe Onoratoabded112016-02-08 16:49:39 -08009927 ArrayList<StopwatchTimer> timers = mBsi.mSensorTimers.get(sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009928 if (timers == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07009929 timers = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08009930 mBsi.mSensorTimers.put(sensor, timers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009931 }
Bookatz867c0d72017-03-07 18:23:42 -08009932 t = new DualTimer(mBsi.mClocks, this, BatteryStats.SENSOR, timers,
9933 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009934 se.mTimer = t;
9935 return t;
9936 }
9937
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009938 public void noteStartSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009939 DualTimer t = mSyncStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009940 if (t != null) {
9941 t.startRunningLocked(elapsedRealtimeMs);
9942 }
9943 }
9944
9945 public void noteStopSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009946 DualTimer t = mSyncStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009947 if (t != null) {
9948 t.stopRunningLocked(elapsedRealtimeMs);
9949 }
9950 }
9951
9952 public void noteStartJobLocked(String name, long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07009953 DualTimer t = mJobStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009954 if (t != null) {
9955 t.startRunningLocked(elapsedRealtimeMs);
9956 }
9957 }
9958
Dianne Hackborn94326cb2017-06-28 16:17:20 -07009959 public void noteStopJobLocked(String name, long elapsedRealtimeMs, int stopReason) {
Bookatzaa4594a2017-03-24 12:39:56 -07009960 DualTimer t = mJobStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009961 if (t != null) {
9962 t.stopRunningLocked(elapsedRealtimeMs);
9963 }
Dianne Hackborn94326cb2017-06-28 16:17:20 -07009964 if (mBsi.mOnBatteryTimeBase.isRunning()) {
9965 SparseIntArray types = mJobCompletions.get(name);
9966 if (types == null) {
9967 types = new SparseIntArray();
9968 mJobCompletions.put(name, types);
9969 }
9970 int last = types.get(stopReason, 0);
9971 types.put(stopReason, last + 1);
9972 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009973 }
9974
Bookatz5b5ec322017-05-26 09:40:38 -07009975 public StopwatchTimer getWakelockTimerLocked(Wakelock wl, int type) {
9976 if (wl == null) {
9977 return null;
9978 }
9979 switch (type) {
9980 case WAKE_TYPE_PARTIAL: {
9981 DualTimer t = wl.mTimerPartial;
9982 if (t == null) {
9983 t = new DualTimer(mBsi.mClocks, this, WAKE_TYPE_PARTIAL,
9984 mBsi.mPartialTimers, mBsi.mOnBatteryScreenOffTimeBase,
9985 mOnBatteryScreenOffBackgroundTimeBase);
9986 wl.mTimerPartial = t;
9987 }
9988 return t;
9989 }
9990 case WAKE_TYPE_FULL: {
9991 StopwatchTimer t = wl.mTimerFull;
9992 if (t == null) {
9993 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_FULL,
9994 mBsi.mFullTimers, mBsi.mOnBatteryTimeBase);
9995 wl.mTimerFull = t;
9996 }
9997 return t;
9998 }
9999 case WAKE_TYPE_WINDOW: {
10000 StopwatchTimer t = wl.mTimerWindow;
10001 if (t == null) {
10002 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_WINDOW,
10003 mBsi.mWindowTimers, mBsi.mOnBatteryTimeBase);
10004 wl.mTimerWindow = t;
10005 }
10006 return t;
10007 }
10008 case WAKE_TYPE_DRAW: {
10009 StopwatchTimer t = wl.mTimerDraw;
10010 if (t == null) {
10011 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_DRAW,
10012 mBsi.mDrawTimers, mBsi.mOnBatteryTimeBase);
10013 wl.mTimerDraw = t;
10014 }
10015 return t;
10016 }
10017 default:
10018 throw new IllegalArgumentException("type=" + type);
10019 }
10020 }
10021
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010022 public void noteStartWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070010023 Wakelock wl = mWakelockStats.startObject(name);
10024 if (wl != null) {
Bookatz5b5ec322017-05-26 09:40:38 -070010025 getWakelockTimerLocked(wl, type).startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010026 }
Bookatzc8c44962017-05-11 12:12:54 -070010027 if (type == WAKE_TYPE_PARTIAL) {
10028 createAggregatedPartialWakelockTimerLocked().startRunningLocked(elapsedRealtimeMs);
10029 if (pid >= 0) {
10030 Pid p = getPidStatsLocked(pid);
10031 if (p.mWakeNesting++ == 0) {
10032 p.mWakeStartMs = elapsedRealtimeMs;
10033 }
Dianne Hackbornb8071d792010-09-09 16:45:15 -070010034 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010035 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010036 }
10037
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010038 public void noteStopWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070010039 Wakelock wl = mWakelockStats.stopObject(name);
10040 if (wl != null) {
Bookatzd6746242017-10-24 18:39:35 -070010041 StopwatchTimer wlt = getWakelockTimerLocked(wl, type);
10042 wlt.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010043 }
Bookatzc8c44962017-05-11 12:12:54 -070010044 if (type == WAKE_TYPE_PARTIAL) {
10045 if (mAggregatedPartialWakelockTimer != null) {
10046 mAggregatedPartialWakelockTimer.stopRunningLocked(elapsedRealtimeMs);
10047 }
10048 if (pid >= 0) {
10049 Pid p = mPids.get(pid);
10050 if (p != null && p.mWakeNesting > 0) {
10051 if (p.mWakeNesting-- == 1) {
10052 p.mWakeSumMs += elapsedRealtimeMs - p.mWakeStartMs;
10053 p.mWakeStartMs = 0;
10054 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -080010055 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010056 }
10057 }
10058 }
10059
Dianne Hackborn287952c2010-09-22 22:34:31 -070010060 public void reportExcessiveCpuLocked(String proc, long overTime, long usedTime) {
10061 Proc p = getProcessStatsLocked(proc);
10062 if (p != null) {
10063 p.addExcessiveCpu(overTime, usedTime);
10064 }
10065 }
10066
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010067 public void noteStartSensor(int sensor, long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -080010068 DualTimer t = getSensorTimerLocked(sensor, /* create= */ true);
Amith Yamasani154d1242017-02-16 10:01:48 -080010069 t.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010070 }
10071
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010072 public void noteStopSensor(int sensor, long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010073 // Don't create a timer if one doesn't already exist
Bookatz867c0d72017-03-07 18:23:42 -080010074 DualTimer t = getSensorTimerLocked(sensor, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010075 if (t != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010076 t.stopRunningLocked(elapsedRealtimeMs);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010077 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010078 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010079
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010080 public void noteStartGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -080010081 noteStartSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010082 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010083
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010084 public void noteStopGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -080010085 noteStopSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010086 }
10087
10088 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -080010089 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010090 }
10091 }
10092
Sudheer Shanka9b735c52017-05-09 18:26:18 -070010093 public long[] getCpuFreqs() {
10094 return mCpuFreqs;
10095 }
10096
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010097 public BatteryStatsImpl(File systemDir, Handler handler, PlatformIdleStateCallback cb,
10098 UserInfoProvider userInfoProvider) {
10099 this(new SystemClocks(), systemDir, handler, cb, userInfoProvider);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010100 }
10101
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010102 private BatteryStatsImpl(Clocks clocks, File systemDir, Handler handler,
10103 PlatformIdleStateCallback cb,
10104 UserInfoProvider userInfoProvider) {
Joe Onoratoabded112016-02-08 16:49:39 -080010105 init(clocks);
10106
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010107 if (systemDir != null) {
10108 mFile = new JournaledFile(new File(systemDir, "batterystats.bin"),
10109 new File(systemDir, "batterystats.bin.tmp"));
10110 } else {
10111 mFile = null;
10112 }
10113 mCheckinFile = new AtomicFile(new File(systemDir, "batterystats-checkin.bin"));
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010114 mDailyFile = new AtomicFile(new File(systemDir, "batterystats-daily.xml"));
Jeff Brown6f357d32014-01-15 20:40:55 -080010115 mHandler = new MyHandler(handler.getLooper());
Sudheer Shanka5c19b892018-01-05 17:25:46 -080010116 mConstants = new Constants(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010117 mStartCount++;
Joe Onoratoabded112016-02-08 16:49:39 -080010118 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -070010119 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -070010120 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010121 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010122 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010123 }
Joe Onoratoabded112016-02-08 16:49:39 -080010124 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase);
10125 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
10126 mOnBatteryTimeBase);
10127 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -11, null,
10128 mOnBatteryTimeBase);
10129 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
10130 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null, mOnBatteryTimeBase);
10131 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase);
10132 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase);
10133 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
10134 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i, null,
10135 mOnBatteryTimeBase);
10136 }
10137 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
10138 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010139 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010140 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010141 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010142 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010143 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010144 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
10145 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010146 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010147 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase, NUM_WIFI_TX_LEVELS);
10148 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
10149 NUM_BT_TX_LEVELS);
10150 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
10151 ModemActivityInfo.TX_POWER_LEVELS);
Joe Onoratoabded112016-02-08 16:49:39 -080010152 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null, mOnBatteryTimeBase);
10153 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
10154 mOnBatteryTimeBase);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010155 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010156 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase);
10157 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080010158 mWifiMulticastWakelockTimer = new StopwatchTimer(mClocks, null,
10159 WIFI_AGGREGATE_MULTICAST_ENABLED, null, mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -080010160 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase);
10161 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null, mOnBatteryTimeBase);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010162 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010163 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i, null,
Dianne Hackborn3251b902014-06-20 14:40:53 -070010164 mOnBatteryTimeBase);
10165 }
Joe Onoratoabded112016-02-08 16:49:39 -080010166 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
10167 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i, null,
10168 mOnBatteryTimeBase);
10169 }
10170 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
10171 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i, null,
10172 mOnBatteryTimeBase);
10173 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080010174 mWifiActiveTimer = new StopwatchTimer(mClocks, null, -900, null, mOnBatteryTimeBase);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080010175 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
10176 mGpsSignalQualityTimer[i] = new StopwatchTimer(mClocks, null, -1000-i, null,
10177 mOnBatteryTimeBase);
10178 }
Joe Onoratoabded112016-02-08 16:49:39 -080010179 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
10180 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
10181 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase);
10182 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase);
10183 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010184 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -070010185 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Mike Ma15313c92017-11-15 17:58:21 -080010186 mDischargeLightDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
10187 mDischargeDeepDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010188 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010189 mOnBattery = mOnBatteryInternal = false;
Joe Onoratoabded112016-02-08 16:49:39 -080010190 long uptime = mClocks.uptimeMillis() * 1000;
10191 long realtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010192 initTimes(uptime, realtime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070010193 mStartPlatformVersion = mEndPlatformVersion = Build.ID;
Evan Millar633a1742009-04-02 16:36:33 -070010194 mDischargeStartLevel = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010195 mDischargeUnplugLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010196 mDischargePlugLevel = -1;
Evan Millar633a1742009-04-02 16:36:33 -070010197 mDischargeCurrentLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010198 mCurrentBatteryLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010199 initDischarge();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010200 clearHistoryLocked();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010201 updateDailyDeadlineLocked();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010202 mPlatformIdleStateCallback = cb;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010203 mUserInfoProvider = userInfoProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010204 }
10205
10206 public BatteryStatsImpl(Parcel p) {
Joe Onoratoabded112016-02-08 16:49:39 -080010207 this(new SystemClocks(), p);
10208 }
10209
10210 public BatteryStatsImpl(Clocks clocks, Parcel p) {
10211 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070010212 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010213 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010214 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -070010215 mHandler = null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010216 mExternalSync = null;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080010217 mConstants = new Constants(mHandler);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010218 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010219 readFromParcel(p);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010220 mPlatformIdleStateCallback = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010221 }
10222
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010223 public void setPowerProfileLocked(PowerProfile profile) {
10224 mPowerProfile = profile;
Adam Lesinski6832f392015-09-05 18:05:40 -070010225
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010226 // We need to initialize the KernelCpuSpeedReaders to read from
10227 // the first cpu of each core. Once we have the PowerProfile, we have access to this
10228 // information.
10229 final int numClusters = mPowerProfile.getNumCpuClusters();
10230 mKernelCpuSpeedReaders = new KernelCpuSpeedReader[numClusters];
10231 int firstCpuOfCluster = 0;
10232 for (int i = 0; i < numClusters; i++) {
10233 final int numSpeedSteps = mPowerProfile.getNumSpeedStepsInCpuCluster(i);
10234 mKernelCpuSpeedReaders[i] = new KernelCpuSpeedReader(firstCpuOfCluster,
10235 numSpeedSteps);
10236 firstCpuOfCluster += mPowerProfile.getNumCoresInCpuCluster(i);
10237 }
Adam Lesinskif9b20a92016-06-17 17:30:01 -070010238
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010239 if (mEstimatedBatteryCapacity == -1) {
10240 // Initialize the estimated battery capacity to a known preset one.
10241 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
Adam Lesinskie08af192015-03-25 16:42:59 -070010242 }
10243 }
10244
Dianne Hackborn0d903a82010-09-07 23:51:03 -070010245 public void setCallback(BatteryCallback cb) {
10246 mCallback = cb;
10247 }
10248
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010249 public void setRadioScanningTimeoutLocked(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -070010250 if (mPhoneSignalScanningTimer != null) {
10251 mPhoneSignalScanningTimer.setTimeout(timeout);
10252 }
10253 }
10254
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070010255 public void setExternalStatsSyncLocked(ExternalStatsSync sync) {
10256 mExternalSync = sync;
10257 }
10258
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010259 public void updateDailyDeadlineLocked() {
10260 // Get the current time.
10261 long currentTime = mDailyStartTime = System.currentTimeMillis();
10262 Calendar calDeadline = Calendar.getInstance();
10263 calDeadline.setTimeInMillis(currentTime);
10264
10265 // Move time up to the next day, ranging from 1am to 3pm.
10266 calDeadline.set(Calendar.DAY_OF_YEAR, calDeadline.get(Calendar.DAY_OF_YEAR) + 1);
10267 calDeadline.set(Calendar.MILLISECOND, 0);
10268 calDeadline.set(Calendar.SECOND, 0);
10269 calDeadline.set(Calendar.MINUTE, 0);
10270 calDeadline.set(Calendar.HOUR_OF_DAY, 1);
10271 mNextMinDailyDeadline = calDeadline.getTimeInMillis();
10272 calDeadline.set(Calendar.HOUR_OF_DAY, 3);
10273 mNextMaxDailyDeadline = calDeadline.getTimeInMillis();
10274 }
10275
10276 public void recordDailyStatsIfNeededLocked(boolean settled) {
10277 long currentTime = System.currentTimeMillis();
10278 if (currentTime >= mNextMaxDailyDeadline) {
10279 recordDailyStatsLocked();
10280 } else if (settled && currentTime >= mNextMinDailyDeadline) {
10281 recordDailyStatsLocked();
10282 } else if (currentTime < (mDailyStartTime-(1000*60*60*24))) {
10283 recordDailyStatsLocked();
10284 }
10285 }
10286
10287 public void recordDailyStatsLocked() {
10288 DailyItem item = new DailyItem();
10289 item.mStartTime = mDailyStartTime;
10290 item.mEndTime = System.currentTimeMillis();
10291 boolean hasData = false;
10292 if (mDailyDischargeStepTracker.mNumStepDurations > 0) {
10293 hasData = true;
10294 item.mDischargeSteps = new LevelStepTracker(
10295 mDailyDischargeStepTracker.mNumStepDurations,
10296 mDailyDischargeStepTracker.mStepDurations);
10297 }
10298 if (mDailyChargeStepTracker.mNumStepDurations > 0) {
10299 hasData = true;
10300 item.mChargeSteps = new LevelStepTracker(
10301 mDailyChargeStepTracker.mNumStepDurations,
10302 mDailyChargeStepTracker.mStepDurations);
10303 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010304 if (mDailyPackageChanges != null) {
10305 hasData = true;
10306 item.mPackageChanges = mDailyPackageChanges;
10307 mDailyPackageChanges = null;
10308 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010309 mDailyDischargeStepTracker.init();
10310 mDailyChargeStepTracker.init();
10311 updateDailyDeadlineLocked();
10312
10313 if (hasData) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080010314 final long startTime = SystemClock.uptimeMillis();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010315 mDailyItems.add(item);
10316 while (mDailyItems.size() > MAX_DAILY_ITEMS) {
10317 mDailyItems.remove(0);
10318 }
10319 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
10320 try {
10321 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010010322 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010323 writeDailyItemsLocked(out);
Dianne Hackborne17b4452018-01-10 13:15:40 -080010324 final long initialTime = SystemClock.uptimeMillis() - startTime;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010325 BackgroundThread.getHandler().post(new Runnable() {
10326 @Override
10327 public void run() {
10328 synchronized (mCheckinFile) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080010329 final long startTime2 = SystemClock.uptimeMillis();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010330 FileOutputStream stream = null;
10331 try {
10332 stream = mDailyFile.startWrite();
10333 memStream.writeTo(stream);
10334 stream.flush();
10335 FileUtils.sync(stream);
10336 stream.close();
10337 mDailyFile.finishWrite(stream);
Dianne Hackborne17b4452018-01-10 13:15:40 -080010338 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
10339 "batterystats-daily",
10340 initialTime + SystemClock.uptimeMillis() - startTime2);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010341 } catch (IOException e) {
10342 Slog.w("BatteryStats",
10343 "Error writing battery daily items", e);
10344 mDailyFile.failWrite(stream);
10345 }
10346 }
10347 }
10348 });
10349 } catch (IOException e) {
10350 }
10351 }
10352 }
10353
10354 private void writeDailyItemsLocked(XmlSerializer out) throws IOException {
10355 StringBuilder sb = new StringBuilder(64);
10356 out.startDocument(null, true);
10357 out.startTag(null, "daily-items");
10358 for (int i=0; i<mDailyItems.size(); i++) {
10359 final DailyItem dit = mDailyItems.get(i);
10360 out.startTag(null, "item");
10361 out.attribute(null, "start", Long.toString(dit.mStartTime));
10362 out.attribute(null, "end", Long.toString(dit.mEndTime));
10363 writeDailyLevelSteps(out, "dis", dit.mDischargeSteps, sb);
10364 writeDailyLevelSteps(out, "chg", dit.mChargeSteps, sb);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010365 if (dit.mPackageChanges != null) {
10366 for (int j=0; j<dit.mPackageChanges.size(); j++) {
10367 PackageChange pc = dit.mPackageChanges.get(j);
10368 if (pc.mUpdate) {
10369 out.startTag(null, "upd");
10370 out.attribute(null, "pkg", pc.mPackageName);
Dianne Hackborn3accca02013-09-20 09:32:11 -070010371 out.attribute(null, "ver", Long.toString(pc.mVersionCode));
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010372 out.endTag(null, "upd");
10373 } else {
10374 out.startTag(null, "rem");
10375 out.attribute(null, "pkg", pc.mPackageName);
10376 out.endTag(null, "rem");
10377 }
10378 }
10379 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010380 out.endTag(null, "item");
10381 }
10382 out.endTag(null, "daily-items");
10383 out.endDocument();
10384 }
10385
10386 private void writeDailyLevelSteps(XmlSerializer out, String tag, LevelStepTracker steps,
10387 StringBuilder tmpBuilder) throws IOException {
10388 if (steps != null) {
10389 out.startTag(null, tag);
10390 out.attribute(null, "n", Integer.toString(steps.mNumStepDurations));
10391 for (int i=0; i<steps.mNumStepDurations; i++) {
10392 out.startTag(null, "s");
10393 tmpBuilder.setLength(0);
10394 steps.encodeEntryAt(i, tmpBuilder);
10395 out.attribute(null, "v", tmpBuilder.toString());
10396 out.endTag(null, "s");
10397 }
10398 out.endTag(null, tag);
10399 }
10400 }
10401
10402 public void readDailyStatsLocked() {
10403 Slog.d(TAG, "Reading daily items from " + mDailyFile.getBaseFile());
10404 mDailyItems.clear();
10405 FileInputStream stream;
10406 try {
10407 stream = mDailyFile.openRead();
10408 } catch (FileNotFoundException e) {
10409 return;
10410 }
10411 try {
10412 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010010413 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010414 readDailyItemsLocked(parser);
10415 } catch (XmlPullParserException e) {
10416 } finally {
10417 try {
10418 stream.close();
10419 } catch (IOException e) {
10420 }
10421 }
10422 }
10423
10424 private void readDailyItemsLocked(XmlPullParser parser) {
10425 try {
10426 int type;
10427 while ((type = parser.next()) != XmlPullParser.START_TAG
10428 && type != XmlPullParser.END_DOCUMENT) {
10429 ;
10430 }
10431
10432 if (type != XmlPullParser.START_TAG) {
10433 throw new IllegalStateException("no start tag found");
10434 }
10435
10436 int outerDepth = parser.getDepth();
10437 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10438 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10439 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10440 continue;
10441 }
10442
10443 String tagName = parser.getName();
10444 if (tagName.equals("item")) {
10445 readDailyItemTagLocked(parser);
10446 } else {
10447 Slog.w(TAG, "Unknown element under <daily-items>: "
10448 + parser.getName());
10449 XmlUtils.skipCurrentTag(parser);
10450 }
10451 }
10452
10453 } catch (IllegalStateException e) {
10454 Slog.w(TAG, "Failed parsing daily " + e);
10455 } catch (NullPointerException e) {
10456 Slog.w(TAG, "Failed parsing daily " + e);
10457 } catch (NumberFormatException e) {
10458 Slog.w(TAG, "Failed parsing daily " + e);
10459 } catch (XmlPullParserException e) {
10460 Slog.w(TAG, "Failed parsing daily " + e);
10461 } catch (IOException e) {
10462 Slog.w(TAG, "Failed parsing daily " + e);
10463 } catch (IndexOutOfBoundsException e) {
10464 Slog.w(TAG, "Failed parsing daily " + e);
10465 }
10466 }
10467
10468 void readDailyItemTagLocked(XmlPullParser parser) throws NumberFormatException,
10469 XmlPullParserException, IOException {
10470 DailyItem dit = new DailyItem();
10471 String attr = parser.getAttributeValue(null, "start");
10472 if (attr != null) {
10473 dit.mStartTime = Long.parseLong(attr);
10474 }
10475 attr = parser.getAttributeValue(null, "end");
10476 if (attr != null) {
10477 dit.mEndTime = Long.parseLong(attr);
10478 }
10479 int outerDepth = parser.getDepth();
10480 int type;
10481 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10482 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10483 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10484 continue;
10485 }
10486
10487 String tagName = parser.getName();
10488 if (tagName.equals("dis")) {
10489 readDailyItemTagDetailsLocked(parser, dit, false, "dis");
10490 } else if (tagName.equals("chg")) {
10491 readDailyItemTagDetailsLocked(parser, dit, true, "chg");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010492 } else if (tagName.equals("upd")) {
10493 if (dit.mPackageChanges == null) {
10494 dit.mPackageChanges = new ArrayList<>();
10495 }
10496 PackageChange pc = new PackageChange();
10497 pc.mUpdate = true;
10498 pc.mPackageName = parser.getAttributeValue(null, "pkg");
10499 String verStr = parser.getAttributeValue(null, "ver");
Dianne Hackborn3accca02013-09-20 09:32:11 -070010500 pc.mVersionCode = verStr != null ? Long.parseLong(verStr) : 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010501 dit.mPackageChanges.add(pc);
10502 XmlUtils.skipCurrentTag(parser);
10503 } else if (tagName.equals("rem")) {
10504 if (dit.mPackageChanges == null) {
10505 dit.mPackageChanges = new ArrayList<>();
10506 }
10507 PackageChange pc = new PackageChange();
10508 pc.mUpdate = false;
10509 pc.mPackageName = parser.getAttributeValue(null, "pkg");
10510 dit.mPackageChanges.add(pc);
10511 XmlUtils.skipCurrentTag(parser);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010512 } else {
10513 Slog.w(TAG, "Unknown element under <item>: "
10514 + parser.getName());
10515 XmlUtils.skipCurrentTag(parser);
10516 }
10517 }
10518 mDailyItems.add(dit);
10519 }
10520
10521 void readDailyItemTagDetailsLocked(XmlPullParser parser, DailyItem dit, boolean isCharge,
10522 String tag)
10523 throws NumberFormatException, XmlPullParserException, IOException {
10524 final String numAttr = parser.getAttributeValue(null, "n");
10525 if (numAttr == null) {
10526 Slog.w(TAG, "Missing 'n' attribute at " + parser.getPositionDescription());
10527 XmlUtils.skipCurrentTag(parser);
10528 return;
10529 }
10530 final int num = Integer.parseInt(numAttr);
10531 LevelStepTracker steps = new LevelStepTracker(num);
10532 if (isCharge) {
10533 dit.mChargeSteps = steps;
10534 } else {
10535 dit.mDischargeSteps = steps;
10536 }
10537 int i = 0;
10538 int outerDepth = parser.getDepth();
10539 int type;
10540 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10541 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10542 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10543 continue;
10544 }
10545
10546 String tagName = parser.getName();
10547 if ("s".equals(tagName)) {
10548 if (i < num) {
10549 String valueAttr = parser.getAttributeValue(null, "v");
10550 if (valueAttr != null) {
10551 steps.decodeEntryAt(i, valueAttr);
10552 i++;
10553 }
10554 }
10555 } else {
10556 Slog.w(TAG, "Unknown element under <" + tag + ">: "
10557 + parser.getName());
10558 XmlUtils.skipCurrentTag(parser);
10559 }
10560 }
10561 steps.mNumStepDurations = i;
10562 }
10563
10564 @Override
10565 public DailyItem getDailyItemLocked(int daysAgo) {
10566 int index = mDailyItems.size()-1-daysAgo;
10567 return index >= 0 ? mDailyItems.get(index) : null;
10568 }
10569
10570 @Override
10571 public long getCurrentDailyStartTime() {
10572 return mDailyStartTime;
10573 }
10574
10575 @Override
10576 public long getNextMinDailyDeadline() {
10577 return mNextMinDailyDeadline;
10578 }
10579
10580 @Override
10581 public long getNextMaxDailyDeadline() {
10582 return mNextMaxDailyDeadline;
10583 }
10584
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010585 @Override
10586 public boolean startIteratingOldHistoryLocked() {
10587 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
10588 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010589 if ((mHistoryIterator = mHistory) == null) {
10590 return false;
10591 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010592 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010593 mHistoryReadTmp.clear();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010594 mReadOverflow = false;
10595 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010596 return true;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010597 }
10598
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010599 @Override
10600 public boolean getNextOldHistoryLocked(HistoryItem out) {
10601 boolean end = mHistoryBuffer.dataPosition() >= mHistoryBuffer.dataSize();
10602 if (!end) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010603 readHistoryDelta(mHistoryBuffer, mHistoryReadTmp);
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010604 mReadOverflow |= mHistoryReadTmp.cmd == HistoryItem.CMD_OVERFLOW;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010605 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010606 HistoryItem cur = mHistoryIterator;
10607 if (cur == null) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010608 if (!mReadOverflow && !end) {
10609 Slog.w(TAG, "Old history ends before new history!");
10610 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010611 return false;
10612 }
10613 out.setTo(cur);
10614 mHistoryIterator = cur.next;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010615 if (!mReadOverflow) {
10616 if (end) {
10617 Slog.w(TAG, "New history ends before old history!");
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010618 } else if (!out.same(mHistoryReadTmp)) {
Dianne Hackborn8c841092013-06-24 13:46:13 -070010619 PrintWriter pw = new FastPrintWriter(new LogWriter(android.util.Log.WARN, TAG));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010620 pw.println("Histories differ!");
10621 pw.println("Old history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010622 (new HistoryPrinter()).printNextItem(pw, out, 0, false, true);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010623 pw.println("New history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010624 (new HistoryPrinter()).printNextItem(pw, mHistoryReadTmp, 0, false,
10625 true);
Dianne Hackborn8c841092013-06-24 13:46:13 -070010626 pw.flush();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010627 }
10628 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010629 return true;
10630 }
10631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010632 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010633 public void finishIteratingOldHistoryLocked() {
10634 mIteratingHistory = false;
10635 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010636 mHistoryIterator = null;
10637 }
10638
10639 public int getHistoryTotalSize() {
10640 return MAX_HISTORY_BUFFER;
10641 }
10642
10643 public int getHistoryUsedSize() {
10644 return mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010645 }
10646
10647 @Override
10648 public boolean startIteratingHistoryLocked() {
10649 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
10650 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010651 if (mHistoryBuffer.dataSize() <= 0) {
10652 return false;
10653 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010654 mHistoryBuffer.setDataPosition(0);
10655 mReadOverflow = false;
10656 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010657 mReadHistoryStrings = new String[mHistoryTagPool.size()];
10658 mReadHistoryUids = new int[mHistoryTagPool.size()];
10659 mReadHistoryChars = 0;
10660 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
10661 final HistoryTag tag = ent.getKey();
10662 final int idx = ent.getValue();
10663 mReadHistoryStrings[idx] = tag.string;
10664 mReadHistoryUids[idx] = tag.uid;
10665 mReadHistoryChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080010666 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010667 return true;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010668 }
10669
10670 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -080010671 public int getHistoryStringPoolSize() {
10672 return mReadHistoryStrings.length;
10673 }
10674
10675 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010676 public int getHistoryStringPoolBytes() {
10677 // Each entry is a fixed 12 bytes: 4 for index, 4 for uid, 4 for string size
10678 // Each string character is 2 bytes.
10679 return (mReadHistoryStrings.length * 12) + (mReadHistoryChars * 2);
10680 }
10681
10682 @Override
10683 public String getHistoryTagPoolString(int index) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080010684 return mReadHistoryStrings[index];
10685 }
10686
10687 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010688 public int getHistoryTagPoolUid(int index) {
10689 return mReadHistoryUids[index];
10690 }
10691
10692 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010693 public boolean getNextHistoryLocked(HistoryItem out) {
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010694 final int pos = mHistoryBuffer.dataPosition();
10695 if (pos == 0) {
10696 out.clear();
10697 }
10698 boolean end = pos >= mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010699 if (end) {
10700 return false;
10701 }
10702
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010703 final long lastRealtime = out.time;
10704 final long lastWalltime = out.currentTime;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010705 readHistoryDelta(mHistoryBuffer, out);
Dianne Hackborn37de0982014-05-09 09:32:18 -070010706 if (out.cmd != HistoryItem.CMD_CURRENT_TIME
10707 && out.cmd != HistoryItem.CMD_RESET && lastWalltime != 0) {
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010708 out.currentTime = lastWalltime + (out.time - lastRealtime);
10709 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010710 return true;
10711 }
10712
10713 @Override
10714 public void finishIteratingHistoryLocked() {
10715 mIteratingHistory = false;
10716 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn099bc622014-01-22 13:39:16 -080010717 mReadHistoryStrings = null;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010718 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010719
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010720 @Override
Dianne Hackbornb5e31652010-09-07 12:13:55 -070010721 public long getHistoryBaseTime() {
10722 return mHistoryBaseTime;
10723 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010724
Dianne Hackbornb5e31652010-09-07 12:13:55 -070010725 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010726 public int getStartCount() {
10727 return mStartCount;
10728 }
10729
10730 public boolean isOnBattery() {
10731 return mOnBattery;
10732 }
10733
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010734 public boolean isCharging() {
10735 return mCharging;
10736 }
10737
Mike Mac2f518a2017-09-19 16:06:03 -070010738 public boolean isScreenOn(int state) {
Chris Phoenix10a4a642017-09-25 13:21:00 -070010739 return state == Display.STATE_ON || state == Display.STATE_VR
10740 || state == Display.STATE_ON_SUSPEND;
Mike Mac2f518a2017-09-19 16:06:03 -070010741 }
10742
10743 public boolean isScreenOff(int state) {
10744 return state == Display.STATE_OFF;
10745 }
10746
10747 public boolean isScreenDoze(int state) {
10748 return state == Display.STATE_DOZE || state == Display.STATE_DOZE_SUSPEND;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010749 }
10750
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010751 void initTimes(long uptime, long realtime) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080010752 mStartClockTime = System.currentTimeMillis();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010753 mOnBatteryTimeBase.init(uptime, realtime);
10754 mOnBatteryScreenOffTimeBase.init(uptime, realtime);
Dianne Hackborn4590e522014-03-24 13:36:46 -070010755 mRealtime = 0;
10756 mUptime = 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010757 mRealtimeStart = realtime;
Dianne Hackborn4590e522014-03-24 13:36:46 -070010758 mUptimeStart = uptime;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010759 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010760
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010761 void initDischarge() {
10762 mLowDischargeAmountSinceCharge = 0;
10763 mHighDischargeAmountSinceCharge = 0;
10764 mDischargeAmountScreenOn = 0;
10765 mDischargeAmountScreenOnSinceCharge = 0;
10766 mDischargeAmountScreenOff = 0;
10767 mDischargeAmountScreenOffSinceCharge = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010768 mDischargeAmountScreenDoze = 0;
10769 mDischargeAmountScreenDozeSinceCharge = 0;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010770 mDischargeStepTracker.init();
10771 mChargeStepTracker.init();
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010772 mDischargeScreenOffCounter.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -070010773 mDischargeScreenDozeCounter.reset(false);
Mike Ma15313c92017-11-15 17:58:21 -080010774 mDischargeLightDozeCounter.reset(false);
10775 mDischargeDeepDozeCounter.reset(false);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010776 mDischargeCounter.reset(false);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010777 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010778
10779 public void resetAllStatsCmdLocked() {
10780 resetAllStatsLocked();
Joe Onoratoabded112016-02-08 16:49:39 -080010781 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -070010782 long uptime = mSecUptime * 1000;
Joe Onoratoabded112016-02-08 16:49:39 -080010783 long mSecRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010784 long realtime = mSecRealtime * 1000;
10785 mDischargeStartLevel = mHistoryCur.batteryLevel;
10786 pullPendingStateUpdatesLocked();
Dianne Hackborn40c87252014-03-19 16:55:40 -070010787 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010788 mDischargeCurrentLevel = mDischargeUnplugLevel = mDischargePlugLevel
10789 = mCurrentBatteryLevel = mHistoryCur.batteryLevel;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010790 mOnBatteryTimeBase.reset(uptime, realtime);
10791 mOnBatteryScreenOffTimeBase.reset(uptime, realtime);
10792 if ((mHistoryCur.states&HistoryItem.STATE_BATTERY_PLUGGED_FLAG) == 0) {
Mike Mac2f518a2017-09-19 16:06:03 -070010793 if (isScreenOn(mScreenState)) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010794 mDischargeScreenOnUnplugLevel = mHistoryCur.batteryLevel;
Mike Mac2f518a2017-09-19 16:06:03 -070010795 mDischargeScreenDozeUnplugLevel = 0;
10796 mDischargeScreenOffUnplugLevel = 0;
10797 } else if (isScreenDoze(mScreenState)) {
10798 mDischargeScreenOnUnplugLevel = 0;
10799 mDischargeScreenDozeUnplugLevel = mHistoryCur.batteryLevel;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010800 mDischargeScreenOffUnplugLevel = 0;
10801 } else {
10802 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010803 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010804 mDischargeScreenOffUnplugLevel = mHistoryCur.batteryLevel;
10805 }
10806 mDischargeAmountScreenOn = 0;
10807 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010808 mDischargeAmountScreenDoze = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010809 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070010810 initActiveHistoryEventsLocked(mSecRealtime, mSecUptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010811 }
10812
10813 private void resetAllStatsLocked() {
Adam Lesinski8ce36942016-05-26 16:05:35 -070010814 final long uptimeMillis = mClocks.uptimeMillis();
10815 final long elapsedRealtimeMillis = mClocks.elapsedRealtime();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010816 mStartCount = 0;
Adam Lesinski8ce36942016-05-26 16:05:35 -070010817 initTimes(uptimeMillis * 1000, elapsedRealtimeMillis * 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010818 mScreenOnTimer.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -070010819 mScreenDozeTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010820 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010821 mScreenBrightnessTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010822 }
Adam Lesinski1a76a622016-06-22 10:28:47 -070010823
10824 if (mPowerProfile != null) {
10825 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
10826 } else {
10827 mEstimatedBatteryCapacity = -1;
10828 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070010829 mMinLearnedBatteryCapacity = -1;
10830 mMaxLearnedBatteryCapacity = -1;
Jeff Browne95c3cd2014-05-02 16:59:26 -070010831 mInteractiveTimer.reset(false);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070010832 mPowerSaveModeEnabledTimer.reset(false);
Adam Lesinski8ce36942016-05-26 16:05:35 -070010833 mLastIdleTimeStart = elapsedRealtimeMillis;
Dianne Hackborn08c47a52015-10-15 12:38:14 -070010834 mLongestLightIdleTime = 0;
10835 mLongestFullIdleTime = 0;
10836 mDeviceIdleModeLightTimer.reset(false);
10837 mDeviceIdleModeFullTimer.reset(false);
10838 mDeviceLightIdlingTimer.reset(false);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010839 mDeviceIdlingTimer.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010840 mPhoneOnTimer.reset(false);
10841 mAudioOnTimer.reset(false);
10842 mVideoOnTimer.reset(false);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070010843 mFlashlightOnTimer.reset(false);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070010844 mCameraOnTimer.reset(false);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010845 mBluetoothScanTimer.reset(false);
Wink Saville52840902011-02-18 12:40:47 -080010846 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010847 mPhoneSignalStrengthsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010848 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010849 mPhoneSignalScanningTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010850 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010851 mPhoneDataConnectionsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010852 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010853 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010854 mNetworkByteActivityCounters[i].reset(false);
10855 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010856 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010857 mMobileRadioActiveTimer.reset(false);
10858 mMobileRadioActivePerAppTimer.reset(false);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010859 mMobileRadioActiveAdjustedTime.reset(false);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080010860 mMobileRadioActiveUnknownTime.reset(false);
10861 mMobileRadioActiveUnknownCount.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010862 mWifiOnTimer.reset(false);
10863 mGlobalWifiRunningTimer.reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010864 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010865 mWifiStateTimer[i].reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010866 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070010867 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
10868 mWifiSupplStateTimer[i].reset(false);
10869 }
10870 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
10871 mWifiSignalStrengthsTimer[i].reset(false);
10872 }
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080010873 mWifiMulticastWakelockTimer.reset(false);
Siddharth Rayb50a6842017-12-14 15:15:28 -080010874 mWifiActiveTimer.reset(false);
10875 mWifiActivity.reset(false);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080010876 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
10877 mGpsSignalQualityTimer[i].reset(false);
10878 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010879 mBluetoothActivity.reset(false);
10880 mModemActivity.reset(false);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080010881 mNumConnectivityChange = mLoadedNumConnectivityChange = mUnpluggedNumConnectivityChange = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010882
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010883 for (int i=0; i<mUidStats.size(); i++) {
Bookatz993a0be2017-07-21 09:03:23 -070010884 if (mUidStats.valueAt(i).reset(uptimeMillis * 1000, elapsedRealtimeMillis * 1000)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010885 mUidStats.remove(mUidStats.keyAt(i));
10886 i--;
10887 }
10888 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010889
Bookatz50df7112017-08-04 14:53:26 -070010890 if (mRpmStats.size() > 0) {
10891 for (SamplingTimer timer : mRpmStats.values()) {
10892 mOnBatteryTimeBase.remove(timer);
10893 }
10894 mRpmStats.clear();
10895 }
10896 if (mScreenOffRpmStats.size() > 0) {
10897 for (SamplingTimer timer : mScreenOffRpmStats.values()) {
10898 mOnBatteryScreenOffTimeBase.remove(timer);
10899 }
10900 mScreenOffRpmStats.clear();
10901 }
10902
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010903 if (mKernelWakelockStats.size() > 0) {
10904 for (SamplingTimer timer : mKernelWakelockStats.values()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010905 mOnBatteryScreenOffTimeBase.remove(timer);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010906 }
10907 mKernelWakelockStats.clear();
10908 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010909
James Carr3a226052016-07-01 14:49:52 -070010910 if (mKernelMemoryStats.size() > 0) {
10911 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
10912 mOnBatteryTimeBase.remove(mKernelMemoryStats.valueAt(i));
10913 }
10914 mKernelMemoryStats.clear();
10915 }
10916
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010917 if (mWakeupReasonStats.size() > 0) {
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070010918 for (SamplingTimer timer : mWakeupReasonStats.values()) {
10919 mOnBatteryTimeBase.remove(timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010920 }
10921 mWakeupReasonStats.clear();
10922 }
10923
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080010924 mLastHistoryStepDetails = null;
10925 mLastStepCpuUserTime = mLastStepCpuSystemTime = 0;
10926 mCurStepCpuUserTime = mCurStepCpuSystemTime = 0;
10927 mLastStepCpuUserTime = mCurStepCpuUserTime = 0;
10928 mLastStepCpuSystemTime = mCurStepCpuSystemTime = 0;
10929 mLastStepStatUserTime = mCurStepStatUserTime = 0;
10930 mLastStepStatSystemTime = mCurStepStatSystemTime = 0;
10931 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime = 0;
10932 mLastStepStatIrqTime = mCurStepStatIrqTime = 0;
10933 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime = 0;
10934 mLastStepStatIdleTime = mCurStepStatIdleTime = 0;
10935
Mike Ma234d1822018-03-13 18:53:21 -070010936 mNumAllUidCpuTimeReads = 0;
10937 mNumUidsRemoved = 0;
10938
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010939 initDischarge();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010940
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010941 clearHistoryLocked();
10942 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010943
Dianne Hackborn40c87252014-03-19 16:55:40 -070010944 private void initActiveHistoryEventsLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010945 for (int i=0; i<HistoryItem.EVENT_COUNT; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010946 if (!mRecordAllHistory && i == HistoryItem.EVENT_PROC) {
10947 // Not recording process starts/stops.
10948 continue;
10949 }
Dianne Hackborn37de0982014-05-09 09:32:18 -070010950 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(i);
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010951 if (active == null) {
10952 continue;
10953 }
Dianne Hackborn37de0982014-05-09 09:32:18 -070010954 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
10955 SparseIntArray uids = ent.getValue();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010956 for (int j=0; j<uids.size(); j++) {
Dianne Hackborn37de0982014-05-09 09:32:18 -070010957 addHistoryEventLocked(elapsedRealtimeMs, uptimeMs, i, ent.getKey(),
10958 uids.keyAt(j));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010959 }
10960 }
10961 }
10962 }
10963
Mike Mac2f518a2017-09-19 16:06:03 -070010964 void updateDischargeScreenLevelsLocked(int oldState, int newState) {
10965 updateOldDischargeScreenLevelLocked(oldState);
10966 updateNewDischargeScreenLevelLocked(newState);
10967 }
10968
10969 private void updateOldDischargeScreenLevelLocked(int state) {
10970 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010971 int diff = mDischargeScreenOnUnplugLevel - mDischargeCurrentLevel;
10972 if (diff > 0) {
10973 mDischargeAmountScreenOn += diff;
10974 mDischargeAmountScreenOnSinceCharge += diff;
10975 }
Mike Mac2f518a2017-09-19 16:06:03 -070010976 } else if (isScreenDoze(state)) {
10977 int diff = mDischargeScreenDozeUnplugLevel - mDischargeCurrentLevel;
10978 if (diff > 0) {
10979 mDischargeAmountScreenDoze += diff;
10980 mDischargeAmountScreenDozeSinceCharge += diff;
10981 }
10982 } else if (isScreenOff(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010983 int diff = mDischargeScreenOffUnplugLevel - mDischargeCurrentLevel;
10984 if (diff > 0) {
10985 mDischargeAmountScreenOff += diff;
10986 mDischargeAmountScreenOffSinceCharge += diff;
10987 }
10988 }
Mike Mac2f518a2017-09-19 16:06:03 -070010989 }
10990
10991 private void updateNewDischargeScreenLevelLocked(int state) {
10992 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010993 mDischargeScreenOnUnplugLevel = mDischargeCurrentLevel;
10994 mDischargeScreenOffUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010995 mDischargeScreenDozeUnplugLevel = 0;
10996 } else if (isScreenDoze(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010997 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010998 mDischargeScreenDozeUnplugLevel = mDischargeCurrentLevel;
10999 mDischargeScreenOffUnplugLevel = 0;
11000 } else if (isScreenOff(state)) {
11001 mDischargeScreenOnUnplugLevel = 0;
11002 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011003 mDischargeScreenOffUnplugLevel = mDischargeCurrentLevel;
11004 }
11005 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011006
Dianne Hackborna7c837f2014-01-15 16:20:44 -080011007 public void pullPendingStateUpdatesLocked() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -080011008 if (mOnBatteryInternal) {
Mike Mac2f518a2017-09-19 16:06:03 -070011009 updateDischargeScreenLevelsLocked(mScreenState, mScreenState);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080011010 }
Dianne Hackborna7c837f2014-01-15 16:20:44 -080011011 }
11012
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011013 private final NetworkStatsFactory mNetworkStatsFactory = new NetworkStatsFactory();
11014 private final Pools.Pool<NetworkStats> mNetworkStatsPool = new Pools.SynchronizedPool<>(6);
11015
11016 private final Object mWifiNetworkLock = new Object();
11017
11018 @GuardedBy("mWifiNetworkLock")
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011019 private String[] mWifiIfaces = EmptyArray.STRING;
11020
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011021 @GuardedBy("mWifiNetworkLock")
11022 private NetworkStats mLastWifiNetworkStats = new NetworkStats(0, -1);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011023
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011024 private final Object mModemNetworkLock = new Object();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011025
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011026 @GuardedBy("mModemNetworkLock")
11027 private String[] mModemIfaces = EmptyArray.STRING;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011028
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011029 @GuardedBy("mModemNetworkLock")
11030 private NetworkStats mLastModemNetworkStats = new NetworkStats(0, -1);
11031
11032 private NetworkStats readNetworkStatsLocked(String[] ifaces) {
11033 try {
11034 if (!ArrayUtils.isEmpty(ifaces)) {
11035 return mNetworkStatsFactory.readNetworkStatsDetail(NetworkStats.UID_ALL, ifaces,
11036 NetworkStats.TAG_NONE, mNetworkStatsPool.acquire());
11037 }
11038 } catch (IOException e) {
11039 Slog.e(TAG, "failed to read network stats for ifaces: " + Arrays.toString(ifaces));
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011040 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011041 return null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011042 }
11043
Chenjie Yu89083392018-01-11 14:53:31 -080011044 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011045 * Distribute WiFi energy info and network traffic to apps.
11046 * @param info The energy information from the WiFi controller.
11047 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011048 public void updateWifiState(@Nullable final WifiActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011049 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011050 Slog.d(TAG, "Updating wifi stats: " + Arrays.toString(mWifiIfaces));
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011051 }
11052
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011053 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070011054 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011055 synchronized (mWifiNetworkLock) {
11056 final NetworkStats latestStats = readNetworkStatsLocked(mWifiIfaces);
11057 if (latestStats != null) {
11058 delta = NetworkStats.subtract(latestStats, mLastWifiNetworkStats, null, null,
11059 mNetworkStatsPool.acquire());
11060 mNetworkStatsPool.release(mLastWifiNetworkStats);
11061 mLastWifiNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070011062 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011063 }
11064
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011065 synchronized (this) {
11066 if (!mOnBatteryInternal) {
11067 if (delta != null) {
11068 mNetworkStatsPool.release(delta);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011069 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011070 return;
11071 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011072
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011073 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
11074 SparseLongArray rxPackets = new SparseLongArray();
11075 SparseLongArray txPackets = new SparseLongArray();
11076 long totalTxPackets = 0;
11077 long totalRxPackets = 0;
11078 if (delta != null) {
11079 NetworkStats.Entry entry = new NetworkStats.Entry();
11080 final int size = delta.size();
11081 for (int i = 0; i < size; i++) {
11082 entry = delta.getValues(i, entry);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011083
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011084 if (DEBUG_ENERGY) {
11085 Slog.d(TAG, "Wifi uid " + entry.uid + ": delta rx=" + entry.rxBytes
11086 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
11087 + " txPackets=" + entry.txPackets);
11088 }
11089
11090 if (entry.rxBytes == 0 && entry.txBytes == 0) {
11091 // Skip the lookup below since there is no work to do.
11092 continue;
11093 }
11094
11095 final Uid u = getUidStatsLocked(mapUid(entry.uid));
11096 if (entry.rxBytes != 0) {
11097 u.noteNetworkActivityLocked(NETWORK_WIFI_RX_DATA, entry.rxBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -080011098 entry.rxPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011099 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11100 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_RX_DATA, entry.rxBytes,
11101 entry.rxPackets);
11102 }
11103 mNetworkByteActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
11104 entry.rxBytes);
11105 mNetworkPacketActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
11106 entry.rxPackets);
11107
11108 rxPackets.put(u.getUid(), entry.rxPackets);
11109
11110 // Sum the total number of packets so that the Rx Power can
11111 // be evenly distributed amongst the apps.
11112 totalRxPackets += entry.rxPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -080011113 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011114
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011115 if (entry.txBytes != 0) {
11116 u.noteNetworkActivityLocked(NETWORK_WIFI_TX_DATA, entry.txBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -080011117 entry.txPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011118 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11119 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_TX_DATA, entry.txBytes,
11120 entry.txPackets);
11121 }
11122 mNetworkByteActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
11123 entry.txBytes);
11124 mNetworkPacketActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
11125 entry.txPackets);
11126
11127 txPackets.put(u.getUid(), entry.txPackets);
11128
11129 // Sum the total number of packets so that the Tx Power can
11130 // be evenly distributed amongst the apps.
11131 totalTxPackets += entry.txPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -080011132 }
Adam Lesinskiba88e682015-12-08 12:06:55 -080011133 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011134 mNetworkStatsPool.release(delta);
11135 delta = null;
Adam Lesinskie08af192015-03-25 16:42:59 -070011136 }
11137
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011138 if (info != null) {
11139 mHasWifiReporting = true;
Adam Lesinskie08af192015-03-25 16:42:59 -070011140
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011141 // Measured in mAms
11142 final long txTimeMs = info.getControllerTxTimeMillis();
11143 final long rxTimeMs = info.getControllerRxTimeMillis();
Siddharth Rayb50a6842017-12-14 15:15:28 -080011144 final long scanTimeMs = info.getControllerScanTimeMillis();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011145 final long idleTimeMs = info.getControllerIdleTimeMillis();
11146 final long totalTimeMs = txTimeMs + rxTimeMs + idleTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -070011147
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011148 long leftOverRxTimeMs = rxTimeMs;
11149 long leftOverTxTimeMs = txTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -070011150
Adam Lesinskie08af192015-03-25 16:42:59 -070011151 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011152 Slog.d(TAG, "------ BEGIN WiFi power blaming ------");
11153 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
11154 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
11155 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms");
11156 Slog.d(TAG, " Total Time: " + totalTimeMs + " ms");
Siddharth Rayb50a6842017-12-14 15:15:28 -080011157 Slog.d(TAG, " Scan Time: " + scanTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070011158 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011159
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011160 long totalWifiLockTimeMs = 0;
11161 long totalScanTimeMs = 0;
11162
11163 // On the first pass, collect some totals so that we can normalize power
11164 // calculations if we need to.
11165 final int uidStatsSize = mUidStats.size();
11166 for (int i = 0; i < uidStatsSize; i++) {
11167 final Uid uid = mUidStats.valueAt(i);
11168
11169 // Sum the total scan power for all apps.
11170 totalScanTimeMs += uid.mWifiScanTimer.getTimeSinceMarkLocked(
11171 elapsedRealtimeMs * 1000) / 1000;
11172
11173 // Sum the total time holding wifi lock for all apps.
11174 totalWifiLockTimeMs += uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
11175 elapsedRealtimeMs * 1000) / 1000;
11176 }
11177
11178 if (DEBUG_ENERGY && totalScanTimeMs > rxTimeMs) {
11179 Slog.d(TAG,
11180 " !Estimated scan time > Actual rx time (" + totalScanTimeMs + " ms > "
11181 + rxTimeMs + " ms). Normalizing scan time.");
11182 }
11183 if (DEBUG_ENERGY && totalScanTimeMs > txTimeMs) {
11184 Slog.d(TAG,
11185 " !Estimated scan time > Actual tx time (" + totalScanTimeMs + " ms > "
11186 + txTimeMs + " ms). Normalizing scan time.");
11187 }
11188
11189 // Actually assign and distribute power usage to apps.
11190 for (int i = 0; i < uidStatsSize; i++) {
11191 final Uid uid = mUidStats.valueAt(i);
11192
11193 long scanTimeSinceMarkMs = uid.mWifiScanTimer.getTimeSinceMarkLocked(
11194 elapsedRealtimeMs * 1000) / 1000;
11195 if (scanTimeSinceMarkMs > 0) {
11196 // Set the new mark so that next time we get new data since this point.
11197 uid.mWifiScanTimer.setMark(elapsedRealtimeMs);
11198
11199 long scanRxTimeSinceMarkMs = scanTimeSinceMarkMs;
11200 long scanTxTimeSinceMarkMs = scanTimeSinceMarkMs;
11201
11202 // Our total scan time is more than the reported Tx/Rx time.
11203 // This is possible because the cost of a scan is approximate.
11204 // Let's normalize the result so that we evenly blame each app
11205 // scanning.
11206 //
11207 // This means that we may have apps that transmitted/received packets not be
11208 // blamed for this, but this is fine as scans are relatively more expensive.
11209 if (totalScanTimeMs > rxTimeMs) {
11210 scanRxTimeSinceMarkMs = (rxTimeMs * scanRxTimeSinceMarkMs) /
11211 totalScanTimeMs;
11212 }
11213 if (totalScanTimeMs > txTimeMs) {
11214 scanTxTimeSinceMarkMs = (txTimeMs * scanTxTimeSinceMarkMs) /
11215 totalScanTimeMs;
11216 }
11217
11218 if (DEBUG_ENERGY) {
11219 Slog.d(TAG, " ScanTime for UID " + uid.getUid() + ": Rx:"
11220 + scanRxTimeSinceMarkMs + " ms Tx:"
11221 + scanTxTimeSinceMarkMs + " ms)");
11222 }
11223
11224 ControllerActivityCounterImpl activityCounter =
11225 uid.getOrCreateWifiControllerActivityLocked();
11226 activityCounter.getRxTimeCounter().addCountLocked(scanRxTimeSinceMarkMs);
11227 activityCounter.getTxTimeCounters()[0].addCountLocked(
11228 scanTxTimeSinceMarkMs);
11229 leftOverRxTimeMs -= scanRxTimeSinceMarkMs;
11230 leftOverTxTimeMs -= scanTxTimeSinceMarkMs;
11231 }
11232
11233 // Distribute evenly the power consumed while Idle to each app holding a WiFi
11234 // lock.
11235 final long wifiLockTimeSinceMarkMs =
11236 uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
11237 elapsedRealtimeMs * 1000) / 1000;
11238 if (wifiLockTimeSinceMarkMs > 0) {
11239 // Set the new mark so that next time we get new data since this point.
11240 uid.mFullWifiLockTimer.setMark(elapsedRealtimeMs);
11241
11242 final long myIdleTimeMs = (wifiLockTimeSinceMarkMs * idleTimeMs)
11243 / totalWifiLockTimeMs;
11244 if (DEBUG_ENERGY) {
11245 Slog.d(TAG, " IdleTime for UID " + uid.getUid() + ": "
11246 + myIdleTimeMs + " ms");
11247 }
11248 uid.getOrCreateWifiControllerActivityLocked().getIdleTimeCounter()
11249 .addCountLocked(myIdleTimeMs);
11250 }
11251 }
11252
Adam Lesinskie08af192015-03-25 16:42:59 -070011253 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011254 Slog.d(TAG, " New RxPower: " + leftOverRxTimeMs + " ms");
11255 Slog.d(TAG, " New TxPower: " + leftOverTxTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070011256 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011257
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011258 // Distribute the remaining Tx power appropriately between all apps that transmitted
11259 // packets.
11260 for (int i = 0; i < txPackets.size(); i++) {
11261 final Uid uid = getUidStatsLocked(txPackets.keyAt(i));
11262 final long myTxTimeMs = (txPackets.valueAt(i) * leftOverTxTimeMs)
11263 / totalTxPackets;
11264 if (DEBUG_ENERGY) {
11265 Slog.d(TAG, " TxTime for UID " + uid.getUid() + ": " + myTxTimeMs + " ms");
11266 }
11267 uid.getOrCreateWifiControllerActivityLocked().getTxTimeCounters()[0]
11268 .addCountLocked(myTxTimeMs);
11269 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011270
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011271 // Distribute the remaining Rx power appropriately between all apps that received
11272 // packets.
11273 for (int i = 0; i < rxPackets.size(); i++) {
11274 final Uid uid = getUidStatsLocked(rxPackets.keyAt(i));
11275 final long myRxTimeMs = (rxPackets.valueAt(i) * leftOverRxTimeMs)
11276 / totalRxPackets;
11277 if (DEBUG_ENERGY) {
11278 Slog.d(TAG, " RxTime for UID " + uid.getUid() + ": " + myRxTimeMs + " ms");
11279 }
11280 uid.getOrCreateWifiControllerActivityLocked().getRxTimeCounter()
11281 .addCountLocked(myRxTimeMs);
11282 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011283
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011284 // Any left over power use will be picked up by the WiFi category in BatteryStatsHelper.
11285
11286
11287 // Update WiFi controller stats.
11288 mWifiActivity.getRxTimeCounter().addCountLocked(info.getControllerRxTimeMillis());
11289 mWifiActivity.getTxTimeCounters()[0].addCountLocked(
11290 info.getControllerTxTimeMillis());
Siddharth Rayb50a6842017-12-14 15:15:28 -080011291 mWifiActivity.getScanTimeCounter().addCountLocked(
11292 info.getControllerScanTimeMillis());
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011293 mWifiActivity.getIdleTimeCounter().addCountLocked(
11294 info.getControllerIdleTimeMillis());
11295
11296 // POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11297 final double opVolt = mPowerProfile.getAveragePower(
11298 PowerProfile.POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11299 if (opVolt != 0) {
11300 // We store the power drain as mAms.
11301 mWifiActivity.getPowerCounter().addCountLocked(
11302 (long) (info.getControllerEnergyUsed() / opVolt));
11303 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011304 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011305 }
11306 }
11307
Chenjie Yu89083392018-01-11 14:53:31 -080011308 private ModemActivityInfo mLastModemActivityInfo =
11309 new ModemActivityInfo(0, 0, 0, new int[0], 0, 0);
11310
Chenjie Yua54e54d2018-02-14 20:12:52 -080011311 private ModemActivityInfo getDeltaModemActivityInfo(ModemActivityInfo activityInfo) {
11312 if (activityInfo == null) {
11313 return null;
11314 }
11315 int[] txTimeMs = new int[ModemActivityInfo.TX_POWER_LEVELS];
11316 for (int i = 0; i < ModemActivityInfo.TX_POWER_LEVELS; i++) {
11317 txTimeMs[i] = activityInfo.getTxTimeMillis()[i]
11318 - mLastModemActivityInfo.getTxTimeMillis()[i];
11319 }
11320 ModemActivityInfo deltaInfo = new ModemActivityInfo(activityInfo.getTimestamp(),
11321 activityInfo.getSleepTimeMillis() - mLastModemActivityInfo.getSleepTimeMillis(),
11322 activityInfo.getIdleTimeMillis() - mLastModemActivityInfo.getIdleTimeMillis(),
11323 txTimeMs,
11324 activityInfo.getRxTimeMillis() - mLastModemActivityInfo.getRxTimeMillis(),
11325 activityInfo.getEnergyUsed() - mLastModemActivityInfo.getEnergyUsed());
11326 mLastModemActivityInfo = activityInfo;
11327 return deltaInfo;
11328 }
11329
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011330 /**
11331 * Distribute Cell radio energy info and network traffic to apps.
11332 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011333 public void updateMobileRadioState(@Nullable final ModemActivityInfo activityInfo) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011334 if (DEBUG_ENERGY) {
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011335 Slog.d(TAG, "Updating mobile radio stats with " + activityInfo);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011336 }
Chenjie Yua54e54d2018-02-14 20:12:52 -080011337 ModemActivityInfo deltaInfo = getDeltaModemActivityInfo(activityInfo);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011338
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011339 // Add modem tx power to history.
Chenjie Yua54e54d2018-02-14 20:12:52 -080011340 addModemTxPowerToHistory(deltaInfo);
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011341
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011342 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070011343 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011344 synchronized (mModemNetworkLock) {
11345 final NetworkStats latestStats = readNetworkStatsLocked(mModemIfaces);
11346 if (latestStats != null) {
11347 delta = NetworkStats.subtract(latestStats, mLastModemNetworkStats, null, null,
11348 mNetworkStatsPool.acquire());
11349 mNetworkStatsPool.release(mLastModemNetworkStats);
11350 mLastModemNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070011351 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011352 }
11353
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011354 synchronized (this) {
11355 if (!mOnBatteryInternal) {
11356 if (delta != null) {
11357 mNetworkStatsPool.release(delta);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011358 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011359 return;
Adam Lesinskie08af192015-03-25 16:42:59 -070011360 }
11361
Chenjie Yua54e54d2018-02-14 20:12:52 -080011362 if (deltaInfo != null) {
Siddharth Ray2038af82018-01-17 17:40:26 -080011363 mHasModemReporting = true;
11364 mModemActivity.getIdleTimeCounter().addCountLocked(
Chenjie Yua54e54d2018-02-14 20:12:52 -080011365 deltaInfo.getIdleTimeMillis());
Siddharth Rayed754702018-02-15 12:44:37 -080011366 mModemActivity.getSleepTimeCounter().addCountLocked(
11367 deltaInfo.getSleepTimeMillis());
Chenjie Yua54e54d2018-02-14 20:12:52 -080011368 mModemActivity.getRxTimeCounter().addCountLocked(deltaInfo.getRxTimeMillis());
Siddharth Ray2038af82018-01-17 17:40:26 -080011369 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
11370 mModemActivity.getTxTimeCounters()[lvl]
Chenjie Yua54e54d2018-02-14 20:12:52 -080011371 .addCountLocked(deltaInfo.getTxTimeMillis()[lvl]);
Siddharth Ray2038af82018-01-17 17:40:26 -080011372 }
11373
11374 // POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11375 final double opVolt = mPowerProfile.getAveragePower(
11376 PowerProfile.POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11377 if (opVolt != 0) {
11378 double energyUsed =
Chenjie Yua54e54d2018-02-14 20:12:52 -080011379 deltaInfo.getSleepTimeMillis() *
Siddharth Ray2038af82018-01-17 17:40:26 -080011380 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_SLEEP)
Chenjie Yua54e54d2018-02-14 20:12:52 -080011381 + deltaInfo.getIdleTimeMillis() *
Siddharth Ray2038af82018-01-17 17:40:26 -080011382 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_IDLE)
Chenjie Yua54e54d2018-02-14 20:12:52 -080011383 + deltaInfo.getRxTimeMillis() *
Siddharth Ray2038af82018-01-17 17:40:26 -080011384 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_RX);
Chenjie Yua54e54d2018-02-14 20:12:52 -080011385 int[] txTimeMs = deltaInfo.getTxTimeMillis();
Chenjie Yu89083392018-01-11 14:53:31 -080011386 for (int i = 0; i < Math.min(txTimeMs.length,
Chenjie Yua54e54d2018-02-14 20:12:52 -080011387 SignalStrength.NUM_SIGNAL_STRENGTH_BINS); i++) {
Chenjie Yu89083392018-01-11 14:53:31 -080011388 energyUsed += txTimeMs[i] * mPowerProfile.getAveragePower(
Chenjie Yua54e54d2018-02-14 20:12:52 -080011389 PowerProfile.POWER_MODEM_CONTROLLER_TX, i);
Siddharth Ray2038af82018-01-17 17:40:26 -080011390 }
11391
11392 // We store the power drain as mAms.
11393 mModemActivity.getPowerCounter().addCountLocked((long) energyUsed);
11394 }
11395 }
11396
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070011397 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011398 long radioTime = mMobileRadioActivePerAppTimer.getTimeSinceMarkLocked(
11399 elapsedRealtimeMs * 1000);
11400 mMobileRadioActivePerAppTimer.setMark(elapsedRealtimeMs);
11401
11402 long totalRxPackets = 0;
11403 long totalTxPackets = 0;
11404 if (delta != null) {
11405 NetworkStats.Entry entry = new NetworkStats.Entry();
11406 final int size = delta.size();
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011407 for (int i = 0; i < size; i++) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011408 entry = delta.getValues(i, entry);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011409 if (entry.rxPackets == 0 && entry.txPackets == 0) {
11410 continue;
11411 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011412
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011413 if (DEBUG_ENERGY) {
11414 Slog.d(TAG, "Mobile uid " + entry.uid + ": delta rx=" + entry.rxBytes
11415 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
11416 + " txPackets=" + entry.txPackets);
11417 }
11418
11419 totalRxPackets += entry.rxPackets;
11420 totalTxPackets += entry.txPackets;
11421
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011422 final Uid u = getUidStatsLocked(mapUid(entry.uid));
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011423 u.noteNetworkActivityLocked(NETWORK_MOBILE_RX_DATA, entry.rxBytes,
11424 entry.rxPackets);
11425 u.noteNetworkActivityLocked(NETWORK_MOBILE_TX_DATA, entry.txBytes,
11426 entry.txPackets);
11427 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11428 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_RX_DATA,
11429 entry.rxBytes, entry.rxPackets);
11430 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_TX_DATA,
11431 entry.txBytes, entry.txPackets);
11432 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011433
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011434 mNetworkByteActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
11435 entry.rxBytes);
11436 mNetworkByteActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
11437 entry.txBytes);
11438 mNetworkPacketActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
11439 entry.rxPackets);
11440 mNetworkPacketActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
11441 entry.txPackets);
11442 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011443
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011444 // Now distribute proportional blame to the apps that did networking.
11445 long totalPackets = totalRxPackets + totalTxPackets;
11446 if (totalPackets > 0) {
11447 for (int i = 0; i < size; i++) {
11448 entry = delta.getValues(i, entry);
11449 if (entry.rxPackets == 0 && entry.txPackets == 0) {
11450 continue;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011451 }
11452
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011453 final Uid u = getUidStatsLocked(mapUid(entry.uid));
11454
11455 // Distribute total radio active time in to this app.
11456 final long appPackets = entry.rxPackets + entry.txPackets;
11457 final long appRadioTime = (radioTime * appPackets) / totalPackets;
11458 u.noteMobileRadioActiveTimeLocked(appRadioTime);
11459
11460 // Remove this app from the totals, so that we don't lose any time
11461 // due to rounding.
11462 radioTime -= appRadioTime;
11463 totalPackets -= appPackets;
11464
Chenjie Yua54e54d2018-02-14 20:12:52 -080011465 if (deltaInfo != null) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011466 ControllerActivityCounterImpl activityCounter =
11467 u.getOrCreateModemControllerActivityLocked();
11468 if (totalRxPackets > 0 && entry.rxPackets > 0) {
Chenjie Yua54e54d2018-02-14 20:12:52 -080011469 final long rxMs = (entry.rxPackets * deltaInfo.getRxTimeMillis())
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011470 / totalRxPackets;
11471 activityCounter.getRxTimeCounter().addCountLocked(rxMs);
11472 }
11473
11474 if (totalTxPackets > 0 && entry.txPackets > 0) {
11475 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
11476 long txMs =
Chenjie Yua54e54d2018-02-14 20:12:52 -080011477 entry.txPackets * deltaInfo.getTxTimeMillis()[lvl];
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011478 txMs /= totalTxPackets;
11479 activityCounter.getTxTimeCounters()[lvl].addCountLocked(txMs);
11480 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011481 }
11482 }
11483 }
11484 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011485
11486 if (radioTime > 0) {
11487 // Whoops, there is some radio time we can't blame on an app!
11488 mMobileRadioActiveUnknownTime.addCountLocked(radioTime);
11489 mMobileRadioActiveUnknownCount.addCountLocked(1);
11490 }
11491
11492 mNetworkStatsPool.release(delta);
11493 delta = null;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011494 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011495 }
11496 }
11497
11498 /**
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011499 * Add modem tx power to history
11500 * Device is said to be in high cellular transmit power when it has spent most of the transmit
11501 * time at the highest power level.
11502 * @param activityInfo
11503 */
Siddharth Raya67fb562018-02-28 13:46:16 -080011504 private synchronized void addModemTxPowerToHistory(final ModemActivityInfo activityInfo) {
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011505 if (activityInfo == null) {
11506 return;
11507 }
11508 int[] txTimeMs = activityInfo.getTxTimeMillis();
11509 if (txTimeMs == null || txTimeMs.length != ModemActivityInfo.TX_POWER_LEVELS) {
11510 return;
11511 }
11512 final long elapsedRealtime = mClocks.elapsedRealtime();
11513 final long uptime = mClocks.uptimeMillis();
11514 int levelMaxTimeSpent = 0;
11515 for (int i = 1; i < txTimeMs.length; i++) {
11516 if (txTimeMs[i] > txTimeMs[levelMaxTimeSpent]) {
11517 levelMaxTimeSpent = i;
11518 }
11519 }
11520 if (levelMaxTimeSpent == ModemActivityInfo.TX_POWER_LEVELS - 1) {
11521 if (!mIsCellularTxPowerHigh) {
11522 mHistoryCur.states2 |= HistoryItem.STATE2_CELLULAR_HIGH_TX_POWER_FLAG;
11523 addHistoryRecordLocked(elapsedRealtime, uptime);
11524 mIsCellularTxPowerHigh = true;
11525 }
11526 return;
11527 }
11528 if (mIsCellularTxPowerHigh) {
11529 mHistoryCur.states2 &= ~HistoryItem.STATE2_CELLULAR_HIGH_TX_POWER_FLAG;
11530 addHistoryRecordLocked(elapsedRealtime, uptime);
11531 mIsCellularTxPowerHigh = false;
11532 }
11533 return;
11534 }
11535
Mike Ma561a8d92018-03-20 18:24:05 -070011536 private final class BluetoothActivityInfoCache {
11537 long idleTimeMs;
11538 long rxTimeMs;
11539 long txTimeMs;
11540 long energy;
11541
11542 SparseLongArray uidRxBytes = new SparseLongArray();
11543 SparseLongArray uidTxBytes = new SparseLongArray();
11544
11545 void set(BluetoothActivityEnergyInfo info) {
11546 idleTimeMs = info.getControllerIdleTimeMillis();
11547 rxTimeMs = info.getControllerRxTimeMillis();
11548 txTimeMs = info.getControllerTxTimeMillis();
11549 energy = info.getControllerEnergyUsed();
11550 if (info.getUidTraffic() != null) {
11551 for (UidTraffic traffic : info.getUidTraffic()) {
11552 uidRxBytes.put(traffic.getUid(), traffic.getRxBytes());
11553 uidTxBytes.put(traffic.getUid(), traffic.getTxBytes());
11554 }
11555 }
11556 }
11557 }
11558
11559 private final BluetoothActivityInfoCache mLastBluetoothActivityInfo
11560 = new BluetoothActivityInfoCache();
11561
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011562 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011563 * Distribute Bluetooth energy info and network traffic to apps.
Mike Ma561a8d92018-03-20 18:24:05 -070011564 *
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011565 * @param info The energy information from the bluetooth controller.
11566 */
11567 public void updateBluetoothStateLocked(@Nullable final BluetoothActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011568 if (DEBUG_ENERGY) {
Adam Lesinski50e47602015-12-04 17:04:54 -080011569 Slog.d(TAG, "Updating bluetooth stats: " + info);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011570 }
11571
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011572 if (info == null || !mOnBatteryInternal) {
11573 return;
11574 }
Adam Lesinskie283d332015-04-16 12:29:25 -070011575
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011576 mHasBluetoothReporting = true;
11577
Bookatz867c0d72017-03-07 18:23:42 -080011578 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Mike Ma561a8d92018-03-20 18:24:05 -070011579 final long rxTimeMs =
11580 info.getControllerRxTimeMillis() - mLastBluetoothActivityInfo.rxTimeMs;
11581 final long txTimeMs =
11582 info.getControllerTxTimeMillis() - mLastBluetoothActivityInfo.txTimeMs;
11583 final long idleTimeMs =
11584 info.getControllerIdleTimeMillis() - mLastBluetoothActivityInfo.idleTimeMs;
11585
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011586 if (DEBUG_ENERGY) {
11587 Slog.d(TAG, "------ BEGIN BLE power blaming ------");
11588 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
11589 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
Chenjie Yu89083392018-01-11 14:53:31 -080011590 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms");
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011591 }
11592
11593 long totalScanTimeMs = 0;
11594
11595 final int uidCount = mUidStats.size();
11596 for (int i = 0; i < uidCount; i++) {
11597 final Uid u = mUidStats.valueAt(i);
11598 if (u.mBluetoothScanTimer == null) {
11599 continue;
Adam Lesinskie283d332015-04-16 12:29:25 -070011600 }
Adam Lesinski50e47602015-12-04 17:04:54 -080011601
Bookatzaa4594a2017-03-24 12:39:56 -070011602 totalScanTimeMs += u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011603 elapsedRealtimeMs * 1000) / 1000;
11604 }
11605
11606 final boolean normalizeScanRxTime = (totalScanTimeMs > rxTimeMs);
11607 final boolean normalizeScanTxTime = (totalScanTimeMs > txTimeMs);
11608
11609 if (DEBUG_ENERGY) {
11610 Slog.d(TAG, "Normalizing scan power for RX=" + normalizeScanRxTime
11611 + " TX=" + normalizeScanTxTime);
11612 }
11613
11614 long leftOverRxTimeMs = rxTimeMs;
11615 long leftOverTxTimeMs = txTimeMs;
11616
11617 for (int i = 0; i < uidCount; i++) {
11618 final Uid u = mUidStats.valueAt(i);
11619 if (u.mBluetoothScanTimer == null) {
11620 continue;
11621 }
11622
Bookatzaa4594a2017-03-24 12:39:56 -070011623 long scanTimeSinceMarkMs = u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011624 elapsedRealtimeMs * 1000) / 1000;
11625 if (scanTimeSinceMarkMs > 0) {
11626 // Set the new mark so that next time we get new data since this point.
11627 u.mBluetoothScanTimer.setMark(elapsedRealtimeMs);
11628
11629 long scanTimeRxSinceMarkMs = scanTimeSinceMarkMs;
11630 long scanTimeTxSinceMarkMs = scanTimeSinceMarkMs;
11631
11632 if (normalizeScanRxTime) {
11633 // Scan time is longer than the total rx time in the controller,
11634 // so distribute the scan time proportionately. This means regular traffic
11635 // will not blamed, but scans are more expensive anyways.
11636 scanTimeRxSinceMarkMs = (rxTimeMs * scanTimeRxSinceMarkMs) / totalScanTimeMs;
11637 }
11638
11639 if (normalizeScanTxTime) {
11640 // Scan time is longer than the total tx time in the controller,
11641 // so distribute the scan time proportionately. This means regular traffic
11642 // will not blamed, but scans are more expensive anyways.
11643 scanTimeTxSinceMarkMs = (txTimeMs * scanTimeTxSinceMarkMs) / totalScanTimeMs;
11644 }
11645
11646 final ControllerActivityCounterImpl counter =
11647 u.getOrCreateBluetoothControllerActivityLocked();
11648 counter.getRxTimeCounter().addCountLocked(scanTimeRxSinceMarkMs);
11649 counter.getTxTimeCounters()[0].addCountLocked(scanTimeTxSinceMarkMs);
11650
11651 leftOverRxTimeMs -= scanTimeRxSinceMarkMs;
11652 leftOverTxTimeMs -= scanTimeTxSinceMarkMs;
11653 }
11654 }
11655
11656 if (DEBUG_ENERGY) {
Mike Ma561a8d92018-03-20 18:24:05 -070011657 Slog.d(TAG, "Left over time for traffic RX=" + leftOverRxTimeMs + " TX="
11658 + leftOverTxTimeMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011659 }
11660
11661 //
11662 // Now distribute blame to apps that did bluetooth traffic.
11663 //
11664
11665 long totalTxBytes = 0;
11666 long totalRxBytes = 0;
11667
11668 final UidTraffic[] uidTraffic = info.getUidTraffic();
Mike Ma561a8d92018-03-20 18:24:05 -070011669 final int numUids = uidTraffic != null ? uidTraffic.length : 0;
11670 for (int i = 0; i < numUids; i++) {
11671 final UidTraffic traffic = uidTraffic[i];
11672 final long rxBytes = traffic.getRxBytes() - mLastBluetoothActivityInfo.uidRxBytes.get(
11673 traffic.getUid());
11674 final long txBytes = traffic.getTxBytes() - mLastBluetoothActivityInfo.uidTxBytes.get(
11675 traffic.getUid());
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011676
11677 // Add to the global counters.
Mike Ma561a8d92018-03-20 18:24:05 -070011678 mNetworkByteActivityCounters[NETWORK_BT_RX_DATA].addCountLocked(rxBytes);
11679 mNetworkByteActivityCounters[NETWORK_BT_TX_DATA].addCountLocked(txBytes);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011680
11681 // Add to the UID counters.
11682 final Uid u = getUidStatsLocked(mapUid(traffic.getUid()));
Mike Ma561a8d92018-03-20 18:24:05 -070011683 u.noteNetworkActivityLocked(NETWORK_BT_RX_DATA, rxBytes, 0);
11684 u.noteNetworkActivityLocked(NETWORK_BT_TX_DATA, txBytes, 0);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011685
11686 // Calculate the total traffic.
Mike Ma561a8d92018-03-20 18:24:05 -070011687 totalRxBytes += rxBytes;
11688 totalTxBytes += txBytes;
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011689 }
11690
Mike Ma561a8d92018-03-20 18:24:05 -070011691 if ((totalTxBytes != 0 || totalRxBytes != 0) && (leftOverRxTimeMs != 0
11692 || leftOverTxTimeMs != 0)) {
11693 for (int i = 0; i < numUids; i++) {
11694 final UidTraffic traffic = uidTraffic[i];
11695 final int uid = traffic.getUid();
11696 final long rxBytes =
11697 traffic.getRxBytes() - mLastBluetoothActivityInfo.uidRxBytes.get(uid);
11698 final long txBytes =
11699 traffic.getTxBytes() - mLastBluetoothActivityInfo.uidTxBytes.get(uid);
Adam Lesinski50e47602015-12-04 17:04:54 -080011700
Mike Ma561a8d92018-03-20 18:24:05 -070011701 final Uid u = getUidStatsLocked(mapUid(uid));
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011702 final ControllerActivityCounterImpl counter =
11703 u.getOrCreateBluetoothControllerActivityLocked();
11704
Mike Ma561a8d92018-03-20 18:24:05 -070011705 if (totalRxBytes > 0 && rxBytes > 0) {
11706 final long timeRxMs = (leftOverRxTimeMs * rxBytes) / totalRxBytes;
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011707 if (DEBUG_ENERGY) {
Mike Ma561a8d92018-03-20 18:24:05 -070011708 Slog.d(TAG, "UID=" + uid + " rx_bytes=" + rxBytes + " rx_time=" + timeRxMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011709 }
11710 counter.getRxTimeCounter().addCountLocked(timeRxMs);
11711 leftOverRxTimeMs -= timeRxMs;
11712 }
11713
Mike Ma561a8d92018-03-20 18:24:05 -070011714 if (totalTxBytes > 0 && txBytes > 0) {
11715 final long timeTxMs = (leftOverTxTimeMs * txBytes) / totalTxBytes;
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011716 if (DEBUG_ENERGY) {
Mike Ma561a8d92018-03-20 18:24:05 -070011717 Slog.d(TAG, "UID=" + uid + " tx_bytes=" + txBytes + " tx_time=" + timeTxMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011718 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011719 counter.getTxTimeCounters()[0].addCountLocked(timeTxMs);
11720 leftOverTxTimeMs -= timeTxMs;
11721 }
Adam Lesinski50e47602015-12-04 17:04:54 -080011722 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011723 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011724
Chenjie Yu89083392018-01-11 14:53:31 -080011725 mBluetoothActivity.getRxTimeCounter().addCountLocked(rxTimeMs);
11726 mBluetoothActivity.getTxTimeCounters()[0].addCountLocked(txTimeMs);
11727 mBluetoothActivity.getIdleTimeCounter().addCountLocked(idleTimeMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011728
11729 // POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11730 final double opVolt = mPowerProfile.getAveragePower(
11731 PowerProfile.POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11732 if (opVolt != 0) {
11733 // We store the power drain as mAms.
11734 mBluetoothActivity.getPowerCounter().addCountLocked(
Mike Ma561a8d92018-03-20 18:24:05 -070011735 (long) ((info.getControllerEnergyUsed() - mLastBluetoothActivityInfo.energy)
11736 / opVolt));
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011737 }
Mike Ma561a8d92018-03-20 18:24:05 -070011738 mLastBluetoothActivityInfo.set(info);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011739 }
11740
11741 /**
Bookatz0b8a0502017-09-13 11:51:52 -070011742 * Read and record Resource Power Manager (RPM) state and voter times.
11743 * If RPM stats were fetched more recently than RPM_STATS_UPDATE_FREQ_MS ago, uses the old data
11744 * instead of fetching it anew.
Bookatz50df7112017-08-04 14:53:26 -070011745 */
11746 public void updateRpmStatsLocked() {
11747 if (mPlatformIdleStateCallback == null) return;
Bookatz0b8a0502017-09-13 11:51:52 -070011748 long now = SystemClock.elapsedRealtime();
11749 if (now - mLastRpmStatsUpdateTimeMs >= RPM_STATS_UPDATE_FREQ_MS) {
11750 mPlatformIdleStateCallback.fillLowPowerStats(mTmpRpmStats);
11751 mLastRpmStatsUpdateTimeMs = now;
11752 }
Bookatz50df7112017-08-04 14:53:26 -070011753
11754 for (Map.Entry<String, RpmStats.PowerStatePlatformSleepState> pstate
11755 : mTmpRpmStats.mPlatformLowPowerStats.entrySet()) {
11756
11757 // Update values for this platform state.
11758 final String pName = pstate.getKey();
11759 final long pTimeUs = pstate.getValue().mTimeMs * 1000;
11760 final int pCount = pstate.getValue().mCount;
11761 getRpmTimerLocked(pName).update(pTimeUs, pCount);
Bookatz82b341172017-09-07 19:06:08 -070011762 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11763 getScreenOffRpmTimerLocked(pName).update(pTimeUs, pCount);
11764 }
Bookatz50df7112017-08-04 14:53:26 -070011765
11766 // Update values for each voter of this platform state.
11767 for (Map.Entry<String, RpmStats.PowerStateElement> voter
11768 : pstate.getValue().mVoters.entrySet()) {
11769 final String vName = pName + "." + voter.getKey();
11770 final long vTimeUs = voter.getValue().mTimeMs * 1000;
11771 final int vCount = voter.getValue().mCount;
11772 getRpmTimerLocked(vName).update(vTimeUs, vCount);
Bookatz82b341172017-09-07 19:06:08 -070011773 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11774 getScreenOffRpmTimerLocked(vName).update(vTimeUs, vCount);
11775 }
Bookatz50df7112017-08-04 14:53:26 -070011776 }
11777 }
11778
11779 for (Map.Entry<String, RpmStats.PowerStateSubsystem> subsys
11780 : mTmpRpmStats.mSubsystemLowPowerStats.entrySet()) {
11781
11782 final String subsysName = subsys.getKey();
11783 for (Map.Entry<String, RpmStats.PowerStateElement> sstate
11784 : subsys.getValue().mStates.entrySet()) {
11785 final String name = subsysName + "." + sstate.getKey();
11786 final long timeUs = sstate.getValue().mTimeMs * 1000;
11787 final int count = sstate.getValue().mCount;
11788 getRpmTimerLocked(name).update(timeUs, count);
Bookatz82b341172017-09-07 19:06:08 -070011789 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11790 getScreenOffRpmTimerLocked(name).update(timeUs, count);
11791 }
Bookatz50df7112017-08-04 14:53:26 -070011792 }
11793 }
11794 }
11795
11796 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011797 * Read and distribute kernel wake lock use across apps.
11798 */
11799 public void updateKernelWakelocksLocked() {
11800 final KernelWakelockStats wakelockStats = mKernelWakelockReader.readKernelWakelockStats(
11801 mTmpWakelockStats);
11802 if (wakelockStats == null) {
11803 // Not crashing might make board bringup easier.
11804 Slog.w(TAG, "Couldn't get kernel wake lock stats");
11805 return;
11806 }
11807
11808 for (Map.Entry<String, KernelWakelockStats.Entry> ent : wakelockStats.entrySet()) {
11809 String name = ent.getKey();
11810 KernelWakelockStats.Entry kws = ent.getValue();
11811
11812 SamplingTimer kwlt = mKernelWakelockStats.get(name);
11813 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -070011814 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011815 mKernelWakelockStats.put(name, kwlt);
11816 }
Adam Lesinskid84ad302016-05-17 18:31:02 -070011817
Adam Lesinski757c6ea2016-04-21 09:55:41 -070011818 kwlt.update(kws.mTotalTime, kws.mCount);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011819 kwlt.setUpdateVersion(kws.mVersion);
11820 }
11821
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011822 int numWakelocksSetStale = 0;
Adam Lesinskid84ad302016-05-17 18:31:02 -070011823 // Set timers to stale if they didn't appear in /d/wakeup_sources (or /proc/wakelocks)
11824 // this time.
11825 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
11826 SamplingTimer st = ent.getValue();
11827 if (st.getUpdateVersion() != wakelockStats.kernelWakelockVersion) {
11828 st.endSample();
11829 numWakelocksSetStale++;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011830 }
11831 }
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011832
Adam Lesinskid84ad302016-05-17 18:31:02 -070011833 // Record whether we've seen a non-zero time (for debugging b/22716723).
11834 if (wakelockStats.isEmpty()) {
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011835 Slog.wtf(TAG, "All kernel wakelocks had time of zero");
11836 }
11837
11838 if (numWakelocksSetStale == mKernelWakelockStats.size()) {
11839 Slog.wtf(TAG, "All kernel wakelocks were set stale. new version=" +
11840 wakelockStats.kernelWakelockVersion);
11841 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011842 }
11843
Adam Lesinski72478f02015-06-17 15:39:43 -070011844 // We use an anonymous class to access these variables,
11845 // so they can't live on the stack or they'd have to be
11846 // final MutableLong objects (more allocations).
11847 // Used in updateCpuTimeLocked().
11848 long mTempTotalCpuUserTimeUs;
11849 long mTempTotalCpuSystemTimeUs;
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011850 long[][] mWakeLockAllocationsUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070011851
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011852 /**
James Carr3a226052016-07-01 14:49:52 -070011853 * Reads the newest memory stats from the kernel.
11854 */
11855 public void updateKernelMemoryBandwidthLocked() {
11856 mKernelMemoryBandwidthStats.updateStats();
11857 LongSparseLongArray bandwidthEntries = mKernelMemoryBandwidthStats.getBandwidthEntries();
11858 final int bandwidthEntryCount = bandwidthEntries.size();
11859 int index;
11860 for (int i = 0; i < bandwidthEntryCount; i++) {
11861 SamplingTimer timer;
11862 if ((index = mKernelMemoryStats.indexOfKey(bandwidthEntries.keyAt(i))) >= 0) {
11863 timer = mKernelMemoryStats.valueAt(index);
11864 } else {
11865 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
11866 mKernelMemoryStats.put(bandwidthEntries.keyAt(i), timer);
11867 }
11868 timer.update(bandwidthEntries.valueAt(i), 1);
11869 if (DEBUG_MEMORY) {
11870 Slog.d(TAG, String.format("Added entry %d and updated timer to: "
11871 + "mUnpluggedReportedTotalTime %d size %d", bandwidthEntries.keyAt(i),
11872 mKernelMemoryStats.get(
11873 bandwidthEntries.keyAt(i)).mUnpluggedReportedTotalTime,
11874 mKernelMemoryStats.size()));
11875 }
11876 }
11877 }
11878
Sudheer Shankac57729a2018-02-09 15:44:42 -080011879 public boolean isOnBatteryLocked() {
11880 return mOnBatteryTimeBase.isRunning();
11881 }
11882
11883 public boolean isOnBatteryScreenOffLocked() {
11884 return mOnBatteryScreenOffTimeBase.isRunning();
11885 }
11886
James Carr3a226052016-07-01 14:49:52 -070011887 /**
Adam Lesinski72478f02015-06-17 15:39:43 -070011888 * Read and distribute CPU usage across apps. If their are partial wakelocks being held
11889 * and we are on battery with screen off, we give more of the cpu time to those apps holding
11890 * wakelocks. If the screen is on, we just assign the actual cpu time an app used.
Sudheer Shankac57729a2018-02-09 15:44:42 -080011891 * It's possible this will be invoked after the internal battery/screen states are updated, so
11892 * passing the appropriate battery/screen states to try attribute the cpu times to correct
11893 * buckets.
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011894 */
Andreas Gampe3f24e692018-02-05 13:24:28 -080011895 @GuardedBy("this")
Sudheer Shankac57729a2018-02-09 15:44:42 -080011896 public void updateCpuTimeLocked(boolean onBattery, boolean onBatteryScreenOff) {
Adam Lesinski52290c9c2015-09-21 16:54:52 -070011897 if (mPowerProfile == null) {
11898 return;
11899 }
11900
Adam Lesinski72478f02015-06-17 15:39:43 -070011901 if (DEBUG_ENERGY_CPU) {
11902 Slog.d(TAG, "!Cpu updating!");
11903 }
11904
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011905 if (mCpuFreqs == null) {
11906 mCpuFreqs = mKernelUidCpuFreqTimeReader.readFreqs(mPowerProfile);
11907 }
11908
Sudheer Shanka38383232017-07-25 09:55:03 -070011909 // Calculate the wakelocks we have to distribute amongst. The system is excluded as it is
11910 // usually holding the wakelock on behalf of an app.
11911 // And Only distribute cpu power to wakelocks if the screen is off and we're on battery.
11912 ArrayList<StopwatchTimer> partialTimersToConsider = null;
Sudheer Shankac57729a2018-02-09 15:44:42 -080011913 if (onBatteryScreenOff) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011914 partialTimersToConsider = new ArrayList<>();
11915 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070011916 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070011917 // Since the collection and blaming of wakelocks can be scheduled to run after
11918 // some delay, the mPartialTimers list may have new entries. We can't blame
11919 // the newly added timer for past cpu time, so we only consider timers that
11920 // were present for one round of collection. Once a timer has gone through
11921 // a round of collection, its mInList field is set to true.
Adam Lesinski72478f02015-06-17 15:39:43 -070011922 if (timer.mInList && timer.mUid != null && timer.mUid.mUid != Process.SYSTEM_UID) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011923 partialTimersToConsider.add(timer);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011924 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011925 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011926 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011927 markPartialTimersAsEligible();
Adam Lesinski72478f02015-06-17 15:39:43 -070011928
Sudheer Shanka38383232017-07-25 09:55:03 -070011929 // When the battery is not on, we don't attribute the cpu times to any timers but we still
11930 // need to take the snapshots.
Sudheer Shankac57729a2018-02-09 15:44:42 -080011931 if (!onBattery) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011932 mKernelUidCpuTimeReader.readDelta(null);
11933 mKernelUidCpuFreqTimeReader.readDelta(null);
Mike Ma234d1822018-03-13 18:53:21 -070011934 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080011935 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
11936 mKernelUidCpuActiveTimeReader.readDelta(null);
11937 mKernelUidCpuClusterTimeReader.readDelta(null);
Mike Ma234d1822018-03-13 18:53:21 -070011938 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080011939 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011940 for (int cluster = mKernelCpuSpeedReaders.length - 1; cluster >= 0; --cluster) {
11941 mKernelCpuSpeedReaders[cluster].readDelta();
11942 }
11943 return;
11944 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011945
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070011946 mUserInfoProvider.refreshUserIds();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011947 final SparseLongArray updatedUids = mKernelUidCpuFreqTimeReader.perClusterTimesAvailable()
11948 ? null : new SparseLongArray();
Sudheer Shankac57729a2018-02-09 15:44:42 -080011949 readKernelUidCpuTimesLocked(partialTimersToConsider, updatedUids, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011950 // updatedUids=null means /proc/uid_time_in_state provides snapshots of per-cluster cpu
11951 // freqs, so no need to approximate these values.
11952 if (updatedUids != null) {
Sudheer Shankac57729a2018-02-09 15:44:42 -080011953 updateClusterSpeedTimes(updatedUids, onBattery);
Sudheer Shanka671985f2017-05-19 11:33:42 -070011954 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080011955 readKernelUidCpuFreqTimesLocked(partialTimersToConsider, onBattery, onBatteryScreenOff);
Mike Ma234d1822018-03-13 18:53:21 -070011956 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080011957 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
Sudheer Shankac57729a2018-02-09 15:44:42 -080011958 readKernelUidCpuActiveTimesLocked(onBattery);
11959 readKernelUidCpuClusterTimesLocked(onBattery);
Mike Ma234d1822018-03-13 18:53:21 -070011960 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080011961 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011962 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070011963
Sudheer Shanka38383232017-07-25 09:55:03 -070011964 /**
11965 * Mark the current partial timers as gone through a collection so that they will be
11966 * considered in the next cpu times distribution to wakelock holders.
11967 */
11968 @VisibleForTesting
11969 public void markPartialTimersAsEligible() {
11970 if (ArrayUtils.referenceEquals(mPartialTimers, mLastPartialTimers)) {
11971 // No difference, so each timer is now considered for the next collection.
11972 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
11973 mPartialTimers.get(i).mInList = true;
11974 }
11975 } else {
11976 // The lists are different, meaning we added (or removed a timer) since the last
11977 // collection.
11978 for (int i = mLastPartialTimers.size() - 1; i >= 0; --i) {
11979 mLastPartialTimers.get(i).mInList = false;
11980 }
11981 mLastPartialTimers.clear();
Adam Lesinski72478f02015-06-17 15:39:43 -070011982
Sudheer Shanka38383232017-07-25 09:55:03 -070011983 // Mark the current timers as gone through a collection.
11984 final int numPartialTimers = mPartialTimers.size();
11985 for (int i = 0; i < numPartialTimers; ++i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070011986 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070011987 timer.mInList = true;
11988 mLastPartialTimers.add(timer);
Adam Lesinski72478f02015-06-17 15:39:43 -070011989 }
11990 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011991 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011992
Sudheer Shanka38383232017-07-25 09:55:03 -070011993 /**
11994 * Take snapshot of cpu times (aggregated over all uids) at different frequencies and
11995 * calculate cpu times spent by each uid at different frequencies.
11996 *
11997 * @param updatedUids The uids for which times spent at different frequencies are calculated.
11998 */
11999 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012000 public void updateClusterSpeedTimes(@NonNull SparseLongArray updatedUids, boolean onBattery) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070012001 long totalCpuClustersTimeMs = 0;
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012002 // Read the time spent for each cluster at various cpu frequencies.
Sudheer Shankaaf857412017-07-21 00:14:24 -070012003 final long[][] clusterSpeedTimesMs = new long[mKernelCpuSpeedReaders.length][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012004 for (int cluster = 0; cluster < mKernelCpuSpeedReaders.length; cluster++) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070012005 clusterSpeedTimesMs[cluster] = mKernelCpuSpeedReaders[cluster].readDelta();
12006 if (clusterSpeedTimesMs[cluster] != null) {
12007 for (int speed = clusterSpeedTimesMs[cluster].length - 1; speed >= 0; --speed) {
12008 totalCpuClustersTimeMs += clusterSpeedTimesMs[cluster][speed];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012009 }
12010 }
12011 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070012012 if (totalCpuClustersTimeMs != 0) {
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012013 // We have cpu times per freq aggregated over all uids but we need the times per uid.
12014 // So, we distribute total time spent by an uid to different cpu freqs based on the
12015 // amount of time cpu was running at that freq.
12016 final int updatedUidsCount = updatedUids.size();
12017 for (int i = 0; i < updatedUidsCount; ++i) {
12018 final Uid u = getUidStatsLocked(updatedUids.keyAt(i));
Sudheer Shankaaf857412017-07-21 00:14:24 -070012019 final long appCpuTimeUs = updatedUids.valueAt(i);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012020 // Add the cpu speeds to this UID.
12021 final int numClusters = mPowerProfile.getNumCpuClusters();
Sudheer Shanka38383232017-07-25 09:55:03 -070012022 if (u.mCpuClusterSpeedTimesUs == null ||
12023 u.mCpuClusterSpeedTimesUs.length != numClusters) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070012024 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012025 }
12026
Sudheer Shankaaf857412017-07-21 00:14:24 -070012027 for (int cluster = 0; cluster < clusterSpeedTimesMs.length; cluster++) {
12028 final int speedsInCluster = clusterSpeedTimesMs[cluster].length;
12029 if (u.mCpuClusterSpeedTimesUs[cluster] == null || speedsInCluster !=
12030 u.mCpuClusterSpeedTimesUs[cluster].length) {
12031 u.mCpuClusterSpeedTimesUs[cluster]
12032 = new LongSamplingCounter[speedsInCluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012033 }
12034
Sudheer Shankaaf857412017-07-21 00:14:24 -070012035 final LongSamplingCounter[] cpuSpeeds = u.mCpuClusterSpeedTimesUs[cluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012036 for (int speed = 0; speed < speedsInCluster; speed++) {
12037 if (cpuSpeeds[speed] == null) {
12038 cpuSpeeds[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
12039 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070012040 cpuSpeeds[speed].addCountLocked(appCpuTimeUs
12041 * clusterSpeedTimesMs[cluster][speed]
Sudheer Shankac57729a2018-02-09 15:44:42 -080012042 / totalCpuClustersTimeMs, onBattery);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012043 }
12044 }
12045 }
12046 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012047 }
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012048
Sudheer Shanka38383232017-07-25 09:55:03 -070012049 /**
12050 * Take a snapshot of the cpu times spent by each uid and update the corresponding counters.
12051 * If {@param partialTimers} is not null and empty, then we assign a portion of cpu times to
12052 * wakelock holders.
12053 *
12054 * @param partialTimers The wakelock holders among which the cpu times will be distributed.
12055 * @param updatedUids If not null, then the uids found in the snapshot will be added to this.
12056 */
12057 @VisibleForTesting
12058 public void readKernelUidCpuTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers,
Sudheer Shankac57729a2018-02-09 15:44:42 -080012059 @Nullable SparseLongArray updatedUids, boolean onBattery) {
Sudheer Shanka38383232017-07-25 09:55:03 -070012060 mTempTotalCpuUserTimeUs = mTempTotalCpuSystemTimeUs = 0;
12061 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
12062 final long startTimeMs = mClocks.uptimeMillis();
Adam Lesinski72478f02015-06-17 15:39:43 -070012063
Sudheer Shanka38383232017-07-25 09:55:03 -070012064 mKernelUidCpuTimeReader.readDelta((uid, userTimeUs, systemTimeUs) -> {
12065 uid = mapUid(uid);
12066 if (Process.isIsolated(uid)) {
12067 // This could happen if the isolated uid mapping was removed before that process
12068 // was actually killed.
12069 mKernelUidCpuTimeReader.removeUid(uid);
12070 Slog.d(TAG, "Got readings for an isolated uid with no mapping: " + uid);
12071 return;
12072 }
12073 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12074 Slog.d(TAG, "Got readings for an invalid user's uid " + uid);
12075 mKernelUidCpuTimeReader.removeUid(uid);
12076 return;
12077 }
12078 final Uid u = getUidStatsLocked(uid);
12079
12080 // Accumulate the total system and user time.
12081 mTempTotalCpuUserTimeUs += userTimeUs;
12082 mTempTotalCpuSystemTimeUs += systemTimeUs;
12083
12084 StringBuilder sb = null;
12085 if (DEBUG_ENERGY_CPU) {
12086 sb = new StringBuilder();
12087 sb.append(" got time for uid=").append(u.mUid).append(": u=");
12088 TimeUtils.formatDuration(userTimeUs / 1000, sb);
12089 sb.append(" s=");
12090 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
12091 sb.append("\n");
12092 }
12093
12094 if (numWakelocks > 0) {
12095 // We have wakelocks being held, so only give a portion of the
12096 // time to the process. The rest will be distributed among wakelock
12097 // holders.
12098 userTimeUs = (userTimeUs * WAKE_LOCK_WEIGHT) / 100;
12099 systemTimeUs = (systemTimeUs * WAKE_LOCK_WEIGHT) / 100;
12100 }
12101
12102 if (sb != null) {
12103 sb.append(" adding to uid=").append(u.mUid).append(": u=");
12104 TimeUtils.formatDuration(userTimeUs / 1000, sb);
12105 sb.append(" s=");
12106 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
12107 Slog.d(TAG, sb.toString());
12108 }
12109
Sudheer Shankac57729a2018-02-09 15:44:42 -080012110 u.mUserCpuTime.addCountLocked(userTimeUs, onBattery);
12111 u.mSystemCpuTime.addCountLocked(systemTimeUs, onBattery);
Sudheer Shanka38383232017-07-25 09:55:03 -070012112 if (updatedUids != null) {
12113 updatedUids.put(u.getUid(), userTimeUs + systemTimeUs);
12114 }
12115 });
12116
12117 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12118 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12119 Slog.d(TAG, "Reading cpu stats took " + elapsedTimeMs + "ms");
12120 }
12121
12122 if (numWakelocks > 0) {
12123 // Distribute a portion of the total cpu time to wakelock holders.
12124 mTempTotalCpuUserTimeUs = (mTempTotalCpuUserTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
12125 mTempTotalCpuSystemTimeUs =
12126 (mTempTotalCpuSystemTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
12127
12128 for (int i = 0; i < numWakelocks; ++i) {
12129 final StopwatchTimer timer = partialTimers.get(i);
12130 final int userTimeUs = (int) (mTempTotalCpuUserTimeUs / (numWakelocks - i));
12131 final int systemTimeUs = (int) (mTempTotalCpuSystemTimeUs / (numWakelocks - i));
12132
12133 if (DEBUG_ENERGY_CPU) {
12134 final StringBuilder sb = new StringBuilder();
12135 sb.append(" Distributing wakelock uid=").append(timer.mUid.mUid)
12136 .append(": u=");
12137 TimeUtils.formatDuration(userTimeUs / 1000, sb);
12138 sb.append(" s=");
12139 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
12140 Slog.d(TAG, sb.toString());
12141 }
12142
Sudheer Shankac57729a2018-02-09 15:44:42 -080012143 timer.mUid.mUserCpuTime.addCountLocked(userTimeUs, onBattery);
12144 timer.mUid.mSystemCpuTime.addCountLocked(systemTimeUs, onBattery);
Sudheer Shanka38383232017-07-25 09:55:03 -070012145 if (updatedUids != null) {
12146 final int uid = timer.mUid.getUid();
12147 updatedUids.put(uid, updatedUids.get(uid, 0) + userTimeUs + systemTimeUs);
12148 }
12149
12150 final Uid.Proc proc = timer.mUid.getProcessStatsLocked("*wakelock*");
Sudheer Shankac57729a2018-02-09 15:44:42 -080012151 proc.addCpuTimeLocked(userTimeUs / 1000, systemTimeUs / 1000, onBattery);
Sudheer Shanka38383232017-07-25 09:55:03 -070012152
12153 mTempTotalCpuUserTimeUs -= userTimeUs;
12154 mTempTotalCpuSystemTimeUs -= systemTimeUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070012155 }
12156 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070012157 }
12158
Sudheer Shanka38383232017-07-25 09:55:03 -070012159 /**
12160 * Take a snapshot of the cpu times spent by each uid in each freq and update the
12161 * corresponding counters.
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012162 *
12163 * @param partialTimers The wakelock holders among which the cpu freq times will be distributed.
Sudheer Shanka38383232017-07-25 09:55:03 -070012164 */
12165 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012166 public void readKernelUidCpuFreqTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers,
12167 boolean onBattery, boolean onBatteryScreenOff) {
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012168 final boolean perClusterTimesAvailable =
12169 mKernelUidCpuFreqTimeReader.perClusterTimesAvailable();
12170 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
12171 final int numClusters = mPowerProfile.getNumCpuClusters();
12172 mWakeLockAllocationsUs = null;
Sudheer Shankaac5b88f2017-12-11 15:36:35 -080012173 final long startTimeMs = mClocks.uptimeMillis();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012174 mKernelUidCpuFreqTimeReader.readDelta((uid, cpuFreqTimeMs) -> {
12175 uid = mapUid(uid);
12176 if (Process.isIsolated(uid)) {
12177 mKernelUidCpuFreqTimeReader.removeUid(uid);
12178 Slog.d(TAG, "Got freq readings for an isolated uid with no mapping: " + uid);
12179 return;
Sudheer Shanka38383232017-07-25 09:55:03 -070012180 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012181 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12182 Slog.d(TAG, "Got freq readings for an invalid user's uid " + uid);
12183 mKernelUidCpuFreqTimeReader.removeUid(uid);
12184 return;
12185 }
12186 final Uid u = getUidStatsLocked(uid);
12187 if (u.mCpuFreqTimeMs == null || u.mCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
12188 u.mCpuFreqTimeMs = new LongSamplingCounterArray(mOnBatteryTimeBase);
12189 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080012190 u.mCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012191 if (u.mScreenOffCpuFreqTimeMs == null ||
12192 u.mScreenOffCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
12193 u.mScreenOffCpuFreqTimeMs = new LongSamplingCounterArray(
12194 mOnBatteryScreenOffTimeBase);
12195 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080012196 u.mScreenOffCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs, onBatteryScreenOff);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012197
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012198 if (perClusterTimesAvailable) {
12199 if (u.mCpuClusterSpeedTimesUs == null ||
12200 u.mCpuClusterSpeedTimesUs.length != numClusters) {
12201 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070012202 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012203 if (numWakelocks > 0 && mWakeLockAllocationsUs == null) {
12204 mWakeLockAllocationsUs = new long[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070012205 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012206
12207 int freqIndex = 0;
12208 for (int cluster = 0; cluster < numClusters; ++cluster) {
12209 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
12210 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
12211 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
12212 u.mCpuClusterSpeedTimesUs[cluster]
12213 = new LongSamplingCounter[speedsInCluster];
12214 }
12215 if (numWakelocks > 0 && mWakeLockAllocationsUs[cluster] == null) {
12216 mWakeLockAllocationsUs[cluster] = new long[speedsInCluster];
12217 }
12218 final LongSamplingCounter[] cpuTimesUs = u.mCpuClusterSpeedTimesUs[cluster];
12219 for (int speed = 0; speed < speedsInCluster; ++speed) {
12220 if (cpuTimesUs[speed] == null) {
12221 cpuTimesUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
12222 }
12223 final long appAllocationUs;
12224 if (mWakeLockAllocationsUs != null) {
12225 appAllocationUs =
12226 (cpuFreqTimeMs[freqIndex] * 1000 * WAKE_LOCK_WEIGHT) / 100;
12227 mWakeLockAllocationsUs[cluster][speed] +=
12228 (cpuFreqTimeMs[freqIndex] * 1000 - appAllocationUs);
12229 } else {
12230 appAllocationUs = cpuFreqTimeMs[freqIndex] * 1000;
12231 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080012232 cpuTimesUs[speed].addCountLocked(appAllocationUs, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012233 freqIndex++;
12234 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012235 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012236 }
12237 });
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012238
Sudheer Shankaac5b88f2017-12-11 15:36:35 -080012239 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12240 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12241 Slog.d(TAG, "Reading cpu freq times took " + elapsedTimeMs + "ms");
12242 }
12243
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012244 if (mWakeLockAllocationsUs != null) {
12245 for (int i = 0; i < numWakelocks; ++i) {
12246 final Uid u = partialTimers.get(i).mUid;
12247 if (u.mCpuClusterSpeedTimesUs == null ||
12248 u.mCpuClusterSpeedTimesUs.length != numClusters) {
12249 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
12250 }
12251
12252 for (int cluster = 0; cluster < numClusters; ++cluster) {
12253 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
12254 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
12255 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
12256 u.mCpuClusterSpeedTimesUs[cluster]
12257 = new LongSamplingCounter[speedsInCluster];
12258 }
12259 final LongSamplingCounter[] cpuTimeUs = u.mCpuClusterSpeedTimesUs[cluster];
12260 for (int speed = 0; speed < speedsInCluster; ++speed) {
12261 if (cpuTimeUs[speed] == null) {
12262 cpuTimeUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
12263 }
12264 final long allocationUs =
12265 mWakeLockAllocationsUs[cluster][speed] / (numWakelocks - i);
Sudheer Shankac57729a2018-02-09 15:44:42 -080012266 cpuTimeUs[speed].addCountLocked(allocationUs, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012267 mWakeLockAllocationsUs[cluster][speed] -= allocationUs;
12268 }
12269 }
12270 }
12271 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012272 }
12273
Mike Ma3d422c32017-10-25 11:08:57 -070012274 /**
12275 * Take a snapshot of the cpu active times spent by each uid and update the corresponding
12276 * counters.
12277 */
12278 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012279 public void readKernelUidCpuActiveTimesLocked(boolean onBattery) {
Mike Ma3d422c32017-10-25 11:08:57 -070012280 final long startTimeMs = mClocks.uptimeMillis();
Mike Ma2ab01442018-02-13 14:22:47 -080012281 mKernelUidCpuActiveTimeReader.readDelta((uid, cpuActiveTimesMs) -> {
Mike Ma3d422c32017-10-25 11:08:57 -070012282 uid = mapUid(uid);
12283 if (Process.isIsolated(uid)) {
12284 mKernelUidCpuActiveTimeReader.removeUid(uid);
12285 Slog.w(TAG, "Got active times for an isolated uid with no mapping: " + uid);
12286 return;
12287 }
12288 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12289 Slog.w(TAG, "Got active times for an invalid user's uid " + uid);
12290 mKernelUidCpuActiveTimeReader.removeUid(uid);
12291 return;
12292 }
12293 final Uid u = getUidStatsLocked(uid);
Mike Ma2ab01442018-02-13 14:22:47 -080012294 u.mCpuActiveTimeMs.addCountLocked(cpuActiveTimesMs, onBattery);
Mike Ma3d422c32017-10-25 11:08:57 -070012295 });
12296
12297 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12298 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12299 Slog.d(TAG, "Reading cpu active times took " + elapsedTimeMs + "ms");
12300 }
12301 }
12302
12303 /**
12304 * Take a snapshot of the cpu cluster times spent by each uid and update the corresponding
12305 * counters.
12306 */
12307 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012308 public void readKernelUidCpuClusterTimesLocked(boolean onBattery) {
Mike Ma3d422c32017-10-25 11:08:57 -070012309 final long startTimeMs = mClocks.uptimeMillis();
Mike Ma2ab01442018-02-13 14:22:47 -080012310 mKernelUidCpuClusterTimeReader.readDelta((uid, cpuClusterTimesMs) -> {
Mike Ma3d422c32017-10-25 11:08:57 -070012311 uid = mapUid(uid);
12312 if (Process.isIsolated(uid)) {
12313 mKernelUidCpuClusterTimeReader.removeUid(uid);
12314 Slog.w(TAG, "Got cluster times for an isolated uid with no mapping: " + uid);
12315 return;
12316 }
12317 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12318 Slog.w(TAG, "Got cluster times for an invalid user's uid " + uid);
12319 mKernelUidCpuClusterTimeReader.removeUid(uid);
12320 return;
12321 }
12322 final Uid u = getUidStatsLocked(uid);
Mike Ma2ab01442018-02-13 14:22:47 -080012323 u.mCpuClusterTimesMs.addCountLocked(cpuClusterTimesMs, onBattery);
Mike Ma3d422c32017-10-25 11:08:57 -070012324 });
12325
12326 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12327 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12328 Slog.d(TAG, "Reading cpu cluster times took " + elapsedTimeMs + "ms");
12329 }
12330 }
12331
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012332 boolean setChargingLocked(boolean charging) {
12333 if (mCharging != charging) {
12334 mCharging = charging;
12335 if (charging) {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012336 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012337 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012338 mHistoryCur.states2 &= ~HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012339 }
12340 mHandler.sendEmptyMessage(MSG_REPORT_CHARGING);
12341 return true;
12342 }
12343 return false;
12344 }
12345
Andreas Gampe3f24e692018-02-05 13:24:28 -080012346 @GuardedBy("this")
Mike Mac2f518a2017-09-19 16:06:03 -070012347 protected void setOnBatteryLocked(final long mSecRealtime, final long mSecUptime,
12348 final boolean onBattery, final int oldStatus, final int level, final int chargeUAh) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012349 boolean doWrite = false;
12350 Message m = mHandler.obtainMessage(MSG_REPORT_POWER_CHANGE);
12351 m.arg1 = onBattery ? 1 : 0;
12352 mHandler.sendMessage(m);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012353
Dianne Hackborn40c87252014-03-19 16:55:40 -070012354 final long uptime = mSecUptime * 1000;
12355 final long realtime = mSecRealtime * 1000;
Mike Mac2f518a2017-09-19 16:06:03 -070012356 final int screenState = mScreenState;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012357 if (onBattery) {
12358 // We will reset our status if we are unplugging after the
12359 // battery was last full, or the level is at 100, or
12360 // we have gone through a significant charge (from a very low
12361 // level to a now very high level).
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080012362 boolean reset = false;
Dianne Hackborn9a755432014-05-15 17:05:22 -070012363 if (!mNoAutoReset && (oldStatus == BatteryManager.BATTERY_STATUS_FULL
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012364 || level >= 90
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070012365 || (mDischargeCurrentLevel < 20 && level >= 80)
12366 || (getHighDischargeAmountSinceCharge() >= 200
12367 && mHistoryBuffer.dataSize() >= MAX_HISTORY_BUFFER))) {
Dianne Hackborn73d6a822014-09-29 10:52:47 -070012368 Slog.i(TAG, "Resetting battery stats: level=" + level + " status=" + oldStatus
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070012369 + " dischargeLevel=" + mDischargeCurrentLevel
Dianne Hackborn73d6a822014-09-29 10:52:47 -070012370 + " lowAmount=" + getLowDischargeAmountSinceCharge()
12371 + " highAmount=" + getHighDischargeAmountSinceCharge());
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012372 // Before we write, collect a snapshot of the final aggregated
12373 // stats to be reported in the next checkin. Only do this if we have
12374 // a sufficient amount of data to make it interesting.
12375 if (getLowDischargeAmountSinceCharge() >= 20) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080012376 final long startTime = SystemClock.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012377 final Parcel parcel = Parcel.obtain();
12378 writeSummaryToParcel(parcel, true);
Dianne Hackborne17b4452018-01-10 13:15:40 -080012379 final long initialTime = SystemClock.uptimeMillis() - startTime;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012380 BackgroundThread.getHandler().post(new Runnable() {
12381 @Override public void run() {
12382 synchronized (mCheckinFile) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080012383 final long startTime2 = SystemClock.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012384 FileOutputStream stream = null;
12385 try {
12386 stream = mCheckinFile.startWrite();
12387 stream.write(parcel.marshall());
12388 stream.flush();
12389 FileUtils.sync(stream);
12390 stream.close();
12391 mCheckinFile.finishWrite(stream);
Dianne Hackborne17b4452018-01-10 13:15:40 -080012392 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
12393 "batterystats-checkin",
12394 initialTime + SystemClock.uptimeMillis() - startTime2);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012395 } catch (IOException e) {
12396 Slog.w("BatteryStats",
12397 "Error writing checkin battery statistics", e);
12398 mCheckinFile.failWrite(stream);
12399 } finally {
12400 parcel.recycle();
12401 }
12402 }
12403 }
12404 });
12405 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012406 doWrite = true;
12407 resetAllStatsLocked();
Ying Wai (Daniel) Fan442ab762017-01-31 22:00:10 -080012408 if (chargeUAh > 0 && level > 0) {
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012409 // Only use the reported coulomb charge value if it is supported and reported.
Ying Wai (Daniel) Fan9238b612017-01-18 15:50:19 -080012410 mEstimatedBatteryCapacity = (int) ((chargeUAh / 1000) / (level / 100.0));
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012411 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012412 mDischargeStartLevel = level;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080012413 reset = true;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012414 mDischargeStepTracker.init();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012415 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012416 if (mCharging) {
12417 setChargingLocked(false);
12418 }
12419 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080012420 mOnBattery = mOnBatteryInternal = true;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012421 mLastDischargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070012422 mMinDischargeStepLevel = level;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012423 mDischargeStepTracker.clearTime();
12424 mDailyDischargeStepTracker.clearTime();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012425 mInitStepMode = mCurStepMode;
12426 mModStepMode = 0;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012427 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012428 mHistoryCur.batteryLevel = (byte)level;
12429 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
12430 if (DEBUG_HISTORY) Slog.v(TAG, "Battery unplugged to: "
12431 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012432 if (reset) {
12433 mRecordingHistory = true;
12434 startRecordingHistory(mSecRealtime, mSecUptime, reset);
12435 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070012436 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012437 mDischargeCurrentLevel = mDischargeUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070012438 if (isScreenOn(screenState)) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012439 mDischargeScreenOnUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070012440 mDischargeScreenDozeUnplugLevel = 0;
12441 mDischargeScreenOffUnplugLevel = 0;
12442 } else if (isScreenDoze(screenState)) {
12443 mDischargeScreenOnUnplugLevel = 0;
12444 mDischargeScreenDozeUnplugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012445 mDischargeScreenOffUnplugLevel = 0;
12446 } else {
12447 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012448 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012449 mDischargeScreenOffUnplugLevel = level;
12450 }
12451 mDischargeAmountScreenOn = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012452 mDischargeAmountScreenDoze = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012453 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012454 updateTimeBasesLocked(true, screenState, uptime, realtime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012455 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012456 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080012457 mOnBattery = mOnBatteryInternal = false;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012458 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012459 mHistoryCur.batteryLevel = (byte)level;
12460 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
12461 if (DEBUG_HISTORY) Slog.v(TAG, "Battery plugged to: "
12462 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -070012463 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012464 mDischargeCurrentLevel = mDischargePlugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012465 if (level < mDischargeUnplugLevel) {
12466 mLowDischargeAmountSinceCharge += mDischargeUnplugLevel-level-1;
12467 mHighDischargeAmountSinceCharge += mDischargeUnplugLevel-level;
12468 }
Mike Mac2f518a2017-09-19 16:06:03 -070012469 updateDischargeScreenLevelsLocked(screenState, screenState);
12470 updateTimeBasesLocked(false, screenState, uptime, realtime);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012471 mChargeStepTracker.init();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012472 mLastChargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070012473 mMaxChargeStepLevel = level;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012474 mInitStepMode = mCurStepMode;
12475 mModStepMode = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012476 }
12477 if (doWrite || (mLastWriteTime + (60 * 1000)) < mSecRealtime) {
12478 if (mFile != null) {
12479 writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012480 }
12481 }
12482 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012483
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012484 private void startRecordingHistory(final long elapsedRealtimeMs, final long uptimeMs,
12485 boolean reset) {
12486 mRecordingHistory = true;
12487 mHistoryCur.currentTime = System.currentTimeMillis();
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012488 addHistoryBufferLocked(elapsedRealtimeMs,
Dianne Hackborn37de0982014-05-09 09:32:18 -070012489 reset ? HistoryItem.CMD_RESET : HistoryItem.CMD_CURRENT_TIME,
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012490 mHistoryCur);
12491 mHistoryCur.currentTime = 0;
12492 if (reset) {
12493 initActiveHistoryEventsLocked(elapsedRealtimeMs, uptimeMs);
12494 }
12495 }
12496
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012497 private void recordCurrentTimeChangeLocked(final long currentTime, final long elapsedRealtimeMs,
12498 final long uptimeMs) {
12499 if (mRecordingHistory) {
12500 mHistoryCur.currentTime = currentTime;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012501 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_CURRENT_TIME, mHistoryCur);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012502 mHistoryCur.currentTime = 0;
12503 }
12504 }
12505
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080012506 private void recordShutdownLocked(final long elapsedRealtimeMs, final long uptimeMs) {
12507 if (mRecordingHistory) {
12508 mHistoryCur.currentTime = System.currentTimeMillis();
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012509 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_SHUTDOWN, mHistoryCur);
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080012510 mHistoryCur.currentTime = 0;
12511 }
12512 }
12513
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012514 private void scheduleSyncExternalStatsLocked(String reason, int updateFlags) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012515 if (mExternalSync != null) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012516 mExternalSync.scheduleSync(reason, updateFlags);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070012517 }
12518 }
12519
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012520 // This should probably be exposed in the API, though it's not critical
Bookatz1a1b0462018-01-12 11:47:03 -080012521 public static final int BATTERY_PLUGGED_NONE = OsProtoEnums.BATTERY_PLUGGED_NONE; // = 0
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012522
Andreas Gampe3f24e692018-02-05 13:24:28 -080012523 @GuardedBy("this")
Bookatz8c6571b2017-10-24 15:04:41 -070012524 public void setBatteryStateLocked(final int status, final int health, final int plugType,
12525 final int level, /* not final */ int temp, final int volt, final int chargeUAh,
12526 final int chargeFullUAh) {
Adam Lesinski29ddfe52017-03-29 19:29:00 -070012527 // Temperature is encoded without the signed bit, so clamp any negative temperatures to 0.
12528 temp = Math.max(0, temp);
12529
Bookatz8c6571b2017-10-24 15:04:41 -070012530 reportChangesToStatsLog(mHaveBatteryLevel ? mHistoryCur : null,
Tej Singh40298312018-02-16 00:15:09 -080012531 status, plugType, level);
Bookatz8c6571b2017-10-24 15:04:41 -070012532
Sudheer Shankac57729a2018-02-09 15:44:42 -080012533 final boolean onBattery = isOnBattery(plugType, status);
Joe Onoratoabded112016-02-08 16:49:39 -080012534 final long uptime = mClocks.uptimeMillis();
12535 final long elapsedRealtime = mClocks.elapsedRealtime();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012536 if (!mHaveBatteryLevel) {
12537 mHaveBatteryLevel = true;
12538 // We start out assuming that the device is plugged in (not
12539 // on battery). If our first report is now that we are indeed
12540 // plugged in, then twiddle our state to correctly reflect that
12541 // since we won't be going through the full setOnBattery().
12542 if (onBattery == mOnBattery) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012543 if (onBattery) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012544 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012545 } else {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012546 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012547 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012548 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012549 // Always start out assuming charging, that will be updated later.
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012550 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012551 mHistoryCur.batteryStatus = (byte)status;
12552 mHistoryCur.batteryLevel = (byte)level;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012553 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012554 mMaxChargeStepLevel = mMinDischargeStepLevel =
12555 mLastChargeStepLevel = mLastDischargeStepLevel = level;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012556 mLastChargingStateLevel = level;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012557 } else if (mCurrentBatteryLevel != level || mOnBattery != onBattery) {
12558 recordDailyStatsIfNeededLocked(level >= 100 && onBattery);
12559 }
12560 int oldStatus = mHistoryCur.batteryStatus;
12561 if (onBattery) {
12562 mDischargeCurrentLevel = level;
12563 if (!mRecordingHistory) {
12564 mRecordingHistory = true;
12565 startRecordingHistory(elapsedRealtime, uptime, true);
12566 }
Todd Poynor1acf06a2017-12-07 19:19:35 -080012567 } else if (level < 96 &&
12568 status != BatteryManager.BATTERY_STATUS_UNKNOWN) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012569 if (!mRecordingHistory) {
12570 mRecordingHistory = true;
12571 startRecordingHistory(elapsedRealtime, uptime, true);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012572 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070012573 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012574 mCurrentBatteryLevel = level;
12575 if (mDischargePlugLevel < 0) {
12576 mDischargePlugLevel = level;
Marco Nelissend8593312009-04-30 14:45:06 -070012577 }
Adam Lesinski926969b2016-04-28 17:31:12 -070012578
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012579 if (onBattery != mOnBattery) {
12580 mHistoryCur.batteryLevel = (byte)level;
12581 mHistoryCur.batteryStatus = (byte)status;
12582 mHistoryCur.batteryHealth = (byte)health;
12583 mHistoryCur.batteryPlugType = (byte)plugType;
12584 mHistoryCur.batteryTemperature = (short)temp;
12585 mHistoryCur.batteryVoltage = (char)volt;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012586 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
12587 // Only record discharges
12588 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
12589 mDischargeCounter.addCountLocked(chargeDiff);
12590 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070012591 if (isScreenDoze(mScreenState)) {
12592 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
12593 }
Mike Ma15313c92017-11-15 17:58:21 -080012594 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
12595 mDischargeLightDozeCounter.addCountLocked(chargeDiff);
12596 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
12597 mDischargeDeepDozeCounter.addCountLocked(chargeDiff);
12598 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012599 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012600 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012601 setOnBatteryLocked(elapsedRealtime, uptime, onBattery, oldStatus, level, chargeUAh);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012602 } else {
12603 boolean changed = false;
12604 if (mHistoryCur.batteryLevel != level) {
12605 mHistoryCur.batteryLevel = (byte)level;
12606 changed = true;
Marco Nelissend8593312009-04-30 14:45:06 -070012607
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012608 // TODO(adamlesinski): Schedule the creation of a HistoryStepDetails record
12609 // which will pull external stats.
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012610 scheduleSyncExternalStatsLocked("battery-level", ExternalStatsSync.UPDATE_ALL);
Evan Millarc64edde2009-04-18 12:26:32 -070012611 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012612 if (mHistoryCur.batteryStatus != status) {
12613 mHistoryCur.batteryStatus = (byte)status;
12614 changed = true;
12615 }
12616 if (mHistoryCur.batteryHealth != health) {
12617 mHistoryCur.batteryHealth = (byte)health;
12618 changed = true;
12619 }
12620 if (mHistoryCur.batteryPlugType != plugType) {
12621 mHistoryCur.batteryPlugType = (byte)plugType;
12622 changed = true;
12623 }
12624 if (temp >= (mHistoryCur.batteryTemperature+10)
12625 || temp <= (mHistoryCur.batteryTemperature-10)) {
12626 mHistoryCur.batteryTemperature = (short)temp;
12627 changed = true;
12628 }
12629 if (volt > (mHistoryCur.batteryVoltage+20)
12630 || volt < (mHistoryCur.batteryVoltage-20)) {
12631 mHistoryCur.batteryVoltage = (char)volt;
12632 changed = true;
12633 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012634 if (chargeUAh >= (mHistoryCur.batteryChargeUAh+10)
12635 || chargeUAh <= (mHistoryCur.batteryChargeUAh-10)) {
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012636 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
12637 // Only record discharges
12638 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
12639 mDischargeCounter.addCountLocked(chargeDiff);
12640 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070012641 if (isScreenDoze(mScreenState)) {
12642 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
12643 }
Mike Ma15313c92017-11-15 17:58:21 -080012644 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
12645 mDischargeLightDozeCounter.addCountLocked(chargeDiff);
12646 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
12647 mDischargeDeepDozeCounter.addCountLocked(chargeDiff);
12648 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012649 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012650 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski926969b2016-04-28 17:31:12 -070012651 changed = true;
12652 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012653 long modeBits = (((long)mInitStepMode) << STEP_LEVEL_INITIAL_MODE_SHIFT)
12654 | (((long)mModStepMode) << STEP_LEVEL_MODIFIED_MODE_SHIFT)
12655 | (((long)(level&0xff)) << STEP_LEVEL_LEVEL_SHIFT);
12656 if (onBattery) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012657 changed |= setChargingLocked(false);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012658 if (mLastDischargeStepLevel != level && mMinDischargeStepLevel > level) {
12659 mDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
12660 modeBits, elapsedRealtime);
12661 mDailyDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
12662 modeBits, elapsedRealtime);
12663 mLastDischargeStepLevel = level;
12664 mMinDischargeStepLevel = level;
12665 mInitStepMode = mCurStepMode;
12666 mModStepMode = 0;
12667 }
12668 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012669 if (level >= 90) {
12670 // If the battery level is at least 90%, always consider the device to be
12671 // charging even if it happens to go down a level.
12672 changed |= setChargingLocked(true);
12673 mLastChargeStepLevel = level;
12674 } if (!mCharging) {
12675 if (mLastChargeStepLevel < level) {
12676 // We have not reporting that we are charging, but the level has now
12677 // gone up, so consider the state to be charging.
12678 changed |= setChargingLocked(true);
12679 mLastChargeStepLevel = level;
12680 }
12681 } else {
12682 if (mLastChargeStepLevel > level) {
12683 // We had reported that the device was charging, but here we are with
12684 // power connected and the level going down. Looks like the current
12685 // power supplied isn't enough, so consider the device to now be
12686 // discharging.
12687 changed |= setChargingLocked(false);
12688 mLastChargeStepLevel = level;
12689 }
12690 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012691 if (mLastChargeStepLevel != level && mMaxChargeStepLevel < level) {
12692 mChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
12693 modeBits, elapsedRealtime);
12694 mDailyChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
12695 modeBits, elapsedRealtime);
12696 mLastChargeStepLevel = level;
12697 mMaxChargeStepLevel = level;
12698 mInitStepMode = mCurStepMode;
12699 mModStepMode = 0;
Evan Millarc64edde2009-04-18 12:26:32 -070012700 }
12701 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012702 if (changed) {
12703 addHistoryRecordLocked(elapsedRealtime, uptime);
12704 }
Evan Millarc64edde2009-04-18 12:26:32 -070012705 }
Todd Poynor1acf06a2017-12-07 19:19:35 -080012706 if (!onBattery &&
12707 (status == BatteryManager.BATTERY_STATUS_FULL ||
12708 status == BatteryManager.BATTERY_STATUS_UNKNOWN)) {
12709 // We don't record history while we are plugged in and fully charged
12710 // (or when battery is not present). The next time we are
12711 // unplugged, history will be cleared.
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012712 mRecordingHistory = DEBUG;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080012713 }
Adam Lesinski041d9172016-12-12 12:03:56 -080012714
Jocelyn Dangc627d102017-04-14 13:15:14 -070012715 if (mMinLearnedBatteryCapacity == -1) {
12716 mMinLearnedBatteryCapacity = chargeFullUAh;
12717 } else {
12718 Math.min(mMinLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski041d9172016-12-12 12:03:56 -080012719 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070012720 mMaxLearnedBatteryCapacity = Math.max(mMaxLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski33dac552015-03-09 15:24:48 -070012721 }
12722
Sudheer Shankac57729a2018-02-09 15:44:42 -080012723 public static boolean isOnBattery(int plugType, int status) {
12724 return plugType == BATTERY_PLUGGED_NONE && status != BatteryManager.BATTERY_STATUS_UNKNOWN;
12725 }
12726
Bookatz8c6571b2017-10-24 15:04:41 -070012727 // Inform StatsLog of setBatteryState changes.
12728 // If this is the first reporting, pass in recentPast == null.
12729 private void reportChangesToStatsLog(HistoryItem recentPast,
Tej Singh40298312018-02-16 00:15:09 -080012730 final int status, final int plugType, final int level) {
Bookatz8c6571b2017-10-24 15:04:41 -070012731
12732 if (recentPast == null || recentPast.batteryStatus != status) {
12733 StatsLog.write(StatsLog.CHARGING_STATE_CHANGED, status);
12734 }
12735 if (recentPast == null || recentPast.batteryPlugType != plugType) {
12736 StatsLog.write(StatsLog.PLUGGED_STATE_CHANGED, plugType);
12737 }
12738 if (recentPast == null || recentPast.batteryLevel != level) {
12739 StatsLog.write(StatsLog.BATTERY_LEVEL_CHANGED, level);
12740 }
Bookatz8c6571b2017-10-24 15:04:41 -070012741 }
12742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012743 public long getAwakeTimeBattery() {
12744 return computeBatteryUptime(getBatteryUptimeLocked(), STATS_CURRENT);
12745 }
12746
12747 public long getAwakeTimePlugged() {
Joe Onoratoabded112016-02-08 16:49:39 -080012748 return (mClocks.uptimeMillis() * 1000) - getAwakeTimeBattery();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012749 }
12750
12751 @Override
12752 public long computeUptime(long curTime, int which) {
12753 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012754 case STATS_SINCE_CHARGED: return mUptime + (curTime-mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012755 case STATS_CURRENT: return (curTime-mUptimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070012756 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getUptimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012757 }
12758 return 0;
12759 }
12760
12761 @Override
12762 public long computeRealtime(long curTime, int which) {
12763 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012764 case STATS_SINCE_CHARGED: return mRealtime + (curTime-mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012765 case STATS_CURRENT: return (curTime-mRealtimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070012766 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getRealtimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012767 }
12768 return 0;
12769 }
12770
12771 @Override
12772 public long computeBatteryUptime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012773 return mOnBatteryTimeBase.computeUptime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012774 }
12775
12776 @Override
12777 public long computeBatteryRealtime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012778 return mOnBatteryTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012779 }
12780
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012781 @Override
12782 public long computeBatteryScreenOffUptime(long curTime, int which) {
12783 return mOnBatteryScreenOffTimeBase.computeUptime(curTime, which);
12784 }
12785
12786 @Override
12787 public long computeBatteryScreenOffRealtime(long curTime, int which) {
12788 return mOnBatteryScreenOffTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012789 }
12790
Dianne Hackborn260c5022014-04-29 11:23:16 -070012791 private long computeTimePerLevel(long[] steps, int numSteps) {
12792 // For now we'll do a simple average across all steps.
12793 if (numSteps <= 0) {
12794 return -1;
12795 }
12796 long total = 0;
12797 for (int i=0; i<numSteps; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012798 total += steps[i] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012799 }
12800 return total / numSteps;
12801 /*
12802 long[] buckets = new long[numSteps];
12803 int numBuckets = 0;
12804 int numToAverage = 4;
12805 int i = 0;
12806 while (i < numSteps) {
12807 long totalTime = 0;
12808 int num = 0;
12809 for (int j=0; j<numToAverage && (i+j)<numSteps; j++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012810 totalTime += steps[i+j] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012811 num++;
12812 }
12813 buckets[numBuckets] = totalTime / num;
12814 numBuckets++;
12815 numToAverage *= 2;
12816 i += num;
12817 }
12818 if (numBuckets < 1) {
12819 return -1;
12820 }
12821 long averageTime = buckets[numBuckets-1];
12822 for (i=numBuckets-2; i>=0; i--) {
12823 averageTime = (averageTime + buckets[i]) / 2;
12824 }
12825 return averageTime;
12826 */
12827 }
12828
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012829 @Override
12830 public long computeBatteryTimeRemaining(long curTime) {
12831 if (!mOnBattery) {
12832 return -1;
12833 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070012834 /* Simple implementation just looks at the average discharge per level across the
12835 entire sample period.
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012836 int discharge = (getLowDischargeAmountSinceCharge()+getHighDischargeAmountSinceCharge())/2;
12837 if (discharge < 2) {
12838 return -1;
12839 }
12840 long duration = computeBatteryRealtime(curTime, STATS_SINCE_CHARGED);
12841 if (duration < 1000*1000) {
12842 return -1;
12843 }
12844 long usPerLevel = duration/discharge;
12845 return usPerLevel * mCurrentBatteryLevel;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012846 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012847 if (mDischargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012848 return -1;
12849 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012850 long msPerLevel = mDischargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012851 if (msPerLevel <= 0) {
12852 return -1;
12853 }
12854 return (msPerLevel * mCurrentBatteryLevel) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012855 }
12856
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012857 @Override
12858 public LevelStepTracker getDischargeLevelStepTracker() {
12859 return mDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012860 }
12861
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012862 @Override
12863 public LevelStepTracker getDailyDischargeLevelStepTracker() {
12864 return mDailyDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012865 }
12866
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012867 @Override
12868 public long computeChargeTimeRemaining(long curTime) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012869 if (mOnBattery) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012870 // Not yet working.
12871 return -1;
12872 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070012873 /* Broken
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012874 int curLevel = mCurrentBatteryLevel;
12875 int plugLevel = mDischargePlugLevel;
12876 if (plugLevel < 0 || curLevel < (plugLevel+1)) {
12877 return -1;
12878 }
12879 long duration = computeBatteryRealtime(curTime, STATS_SINCE_UNPLUGGED);
12880 if (duration < 1000*1000) {
12881 return -1;
12882 }
12883 long usPerLevel = duration/(curLevel-plugLevel);
12884 return usPerLevel * (100-curLevel);
Dianne Hackborn260c5022014-04-29 11:23:16 -070012885 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012886 if (mChargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012887 return -1;
12888 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012889 long msPerLevel = mChargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012890 if (msPerLevel <= 0) {
12891 return -1;
12892 }
12893 return (msPerLevel * (100-mCurrentBatteryLevel)) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012894 }
12895
Siddharth Raya1fd0572017-11-13 14:20:47 -080012896 /*@hide */
12897 public CellularBatteryStats getCellularBatteryStats() {
12898 CellularBatteryStats s = new CellularBatteryStats();
12899 final int which = STATS_SINCE_CHARGED;
12900 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12901 final ControllerActivityCounter counter = getModemControllerActivity();
Siddharth Rayed754702018-02-15 12:44:37 -080012902 final long sleepTimeMs = counter.getSleepTimeCounter().getCountLocked(which);
Siddharth Raya1fd0572017-11-13 14:20:47 -080012903 final long idleTimeMs = counter.getIdleTimeCounter().getCountLocked(which);
12904 final long rxTimeMs = counter.getRxTimeCounter().getCountLocked(which);
12905 final long energyConsumedMaMs = counter.getPowerCounter().getCountLocked(which);
12906 long[] timeInRatMs = new long[BatteryStats.NUM_DATA_CONNECTION_TYPES];
12907 for (int i = 0; i < timeInRatMs.length; i++) {
12908 timeInRatMs[i] = getPhoneDataConnectionTime(i, rawRealTime, which) / 1000;
12909 }
12910 long[] timeInRxSignalStrengthLevelMs = new long[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
12911 for (int i = 0; i < timeInRxSignalStrengthLevelMs.length; i++) {
12912 timeInRxSignalStrengthLevelMs[i]
12913 = getPhoneSignalStrengthTime(i, rawRealTime, which) / 1000;
12914 }
12915 long[] txTimeMs = new long[Math.min(ModemActivityInfo.TX_POWER_LEVELS,
12916 counter.getTxTimeCounters().length)];
12917 long totalTxTimeMs = 0;
12918 for (int i = 0; i < txTimeMs.length; i++) {
12919 txTimeMs[i] = counter.getTxTimeCounters()[i].getCountLocked(which);
12920 totalTxTimeMs += txTimeMs[i];
12921 }
Siddharth Raya1fd0572017-11-13 14:20:47 -080012922 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
12923 s.setKernelActiveTimeMs(getMobileRadioActiveTime(rawRealTime, which) / 1000);
12924 s.setNumPacketsTx(getNetworkActivityPackets(NETWORK_MOBILE_TX_DATA, which));
12925 s.setNumBytesTx(getNetworkActivityBytes(NETWORK_MOBILE_TX_DATA, which));
12926 s.setNumPacketsRx(getNetworkActivityPackets(NETWORK_MOBILE_RX_DATA, which));
12927 s.setNumBytesRx(getNetworkActivityBytes(NETWORK_MOBILE_RX_DATA, which));
12928 s.setSleepTimeMs(sleepTimeMs);
12929 s.setIdleTimeMs(idleTimeMs);
12930 s.setRxTimeMs(rxTimeMs);
12931 s.setEnergyConsumedMaMs(energyConsumedMaMs);
12932 s.setTimeInRatMs(timeInRatMs);
12933 s.setTimeInRxSignalStrengthLevelMs(timeInRxSignalStrengthLevelMs);
12934 s.setTxTimeMs(txTimeMs);
12935 return s;
12936 }
12937
Siddharth Rayb50a6842017-12-14 15:15:28 -080012938 /*@hide */
12939 public WifiBatteryStats getWifiBatteryStats() {
12940 WifiBatteryStats s = new WifiBatteryStats();
12941 final int which = STATS_SINCE_CHARGED;
12942 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12943 final ControllerActivityCounter counter = getWifiControllerActivity();
12944 final long idleTimeMs = counter.getIdleTimeCounter().getCountLocked(which);
12945 final long scanTimeMs = counter.getScanTimeCounter().getCountLocked(which);
12946 final long rxTimeMs = counter.getRxTimeCounter().getCountLocked(which);
12947 final long txTimeMs = counter.getTxTimeCounters()[0].getCountLocked(which);
12948 final long totalControllerActivityTimeMs
12949 = computeBatteryRealtime(SystemClock.elapsedRealtime() * 1000, which) / 1000;
12950 final long sleepTimeMs
12951 = totalControllerActivityTimeMs - (idleTimeMs + rxTimeMs + txTimeMs);
12952 final long energyConsumedMaMs = counter.getPowerCounter().getCountLocked(which);
12953 long numAppScanRequest = 0;
12954 for (int i = 0; i < mUidStats.size(); i++) {
12955 numAppScanRequest += mUidStats.valueAt(i).mWifiScanTimer.getCountLocked(which);
12956 }
12957 long[] timeInStateMs = new long[NUM_WIFI_STATES];
12958 for (int i=0; i<NUM_WIFI_STATES; i++) {
12959 timeInStateMs[i] = getWifiStateTime(i, rawRealTime, which) / 1000;
12960 }
12961 long[] timeInSupplStateMs = new long[NUM_WIFI_SUPPL_STATES];
12962 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
12963 timeInSupplStateMs[i] = getWifiSupplStateTime(i, rawRealTime, which) / 1000;
12964 }
12965 long[] timeSignalStrengthTimeMs = new long[NUM_WIFI_SIGNAL_STRENGTH_BINS];
12966 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
12967 timeSignalStrengthTimeMs[i] = getWifiSignalStrengthTime(i, rawRealTime, which) / 1000;
12968 }
12969 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
12970 s.setKernelActiveTimeMs(getWifiActiveTime(rawRealTime, which) / 1000);
12971 s.setNumPacketsTx(getNetworkActivityPackets(NETWORK_WIFI_TX_DATA, which));
12972 s.setNumBytesTx(getNetworkActivityBytes(NETWORK_WIFI_TX_DATA, which));
12973 s.setNumPacketsRx(getNetworkActivityPackets(NETWORK_WIFI_RX_DATA, which));
12974 s.setNumBytesRx(getNetworkActivityBytes(NETWORK_WIFI_RX_DATA, which));
12975 s.setSleepTimeMs(sleepTimeMs);
12976 s.setIdleTimeMs(idleTimeMs);
12977 s.setRxTimeMs(rxTimeMs);
12978 s.setTxTimeMs(txTimeMs);
12979 s.setScanTimeMs(scanTimeMs);
12980 s.setEnergyConsumedMaMs(energyConsumedMaMs);
12981 s.setNumAppScanRequest(numAppScanRequest);
12982 s.setTimeInStateMs(timeInStateMs);
12983 s.setTimeInSupplicantStateMs(timeInSupplStateMs);
12984 s.setTimeInRxSignalStrengthLevelMs(timeSignalStrengthTimeMs);
12985 return s;
12986 }
12987
Siddharth Ray78ccaf52017-12-23 16:16:21 -080012988 /*@hide */
12989 public GpsBatteryStats getGpsBatteryStats() {
12990 GpsBatteryStats s = new GpsBatteryStats();
12991 final int which = STATS_SINCE_CHARGED;
12992 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12993 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
12994 s.setEnergyConsumedMaMs(getGpsBatteryDrainMaMs());
12995 long[] time = new long[GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS];
12996 for (int i=0; i<time.length; i++) {
12997 time[i] = getGpsSignalQualityTime(i, rawRealTime, which) / 1000;
12998 }
12999 s.setTimeInGpsSignalQualityLevel(time);
13000 return s;
13001 }
13002
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013003 @Override
13004 public LevelStepTracker getChargeLevelStepTracker() {
13005 return mChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070013006 }
13007
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013008 @Override
13009 public LevelStepTracker getDailyChargeLevelStepTracker() {
13010 return mDailyChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070013011 }
13012
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013013 @Override
13014 public ArrayList<PackageChange> getDailyPackageChanges() {
13015 return mDailyPackageChanges;
13016 }
13017
Joe Onoratoe1acd632016-02-23 13:25:10 -080013018 protected long getBatteryUptimeLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080013019 return mOnBatteryTimeBase.getUptime(mClocks.uptimeMillis() * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013020 }
13021
13022 @Override
13023 public long getBatteryUptime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013024 return mOnBatteryTimeBase.getUptime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013025 }
13026
13027 @Override
13028 public long getBatteryRealtime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013029 return mOnBatteryTimeBase.getRealtime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013030 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -070013031
The Android Open Source Project10592532009-03-18 17:39:46 -070013032 @Override
Evan Millar633a1742009-04-02 16:36:33 -070013033 public int getDischargeStartLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070013034 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070013035 return getDischargeStartLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070013036 }
13037 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013038
Evan Millar633a1742009-04-02 16:36:33 -070013039 public int getDischargeStartLevelLocked() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013040 return mDischargeUnplugLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070013041 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013042
The Android Open Source Project10592532009-03-18 17:39:46 -070013043 @Override
Evan Millar633a1742009-04-02 16:36:33 -070013044 public int getDischargeCurrentLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070013045 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070013046 return getDischargeCurrentLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070013047 }
13048 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013049
Evan Millar633a1742009-04-02 16:36:33 -070013050 public int getDischargeCurrentLevelLocked() {
Dianne Hackborne4a59512010-12-07 11:08:07 -080013051 return mDischargeCurrentLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070013052 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013053
Amith Yamasanie43530a2009-08-21 13:11:37 -070013054 @Override
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013055 public int getLowDischargeAmountSinceCharge() {
13056 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080013057 int val = mLowDischargeAmountSinceCharge;
13058 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
13059 val += mDischargeUnplugLevel-mDischargeCurrentLevel-1;
13060 }
13061 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013062 }
13063 }
13064
13065 @Override
13066 public int getHighDischargeAmountSinceCharge() {
13067 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080013068 int val = mHighDischargeAmountSinceCharge;
13069 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
13070 val += mDischargeUnplugLevel-mDischargeCurrentLevel;
13071 }
13072 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013073 }
13074 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070013075
13076 @Override
13077 public int getDischargeAmount(int which) {
13078 int dischargeAmount = which == STATS_SINCE_CHARGED
13079 ? getHighDischargeAmountSinceCharge()
13080 : (getDischargeStartLevel() - getDischargeCurrentLevel());
13081 if (dischargeAmount < 0) {
13082 dischargeAmount = 0;
13083 }
13084 return dischargeAmount;
13085 }
13086
Mike Mac2f518a2017-09-19 16:06:03 -070013087 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013088 public int getDischargeAmountScreenOn() {
13089 synchronized(this) {
13090 int val = mDischargeAmountScreenOn;
Mike Mac2f518a2017-09-19 16:06:03 -070013091 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013092 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
13093 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
13094 }
13095 return val;
13096 }
13097 }
13098
Mike Mac2f518a2017-09-19 16:06:03 -070013099 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013100 public int getDischargeAmountScreenOnSinceCharge() {
13101 synchronized(this) {
13102 int val = mDischargeAmountScreenOnSinceCharge;
Mike Mac2f518a2017-09-19 16:06:03 -070013103 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013104 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
13105 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
13106 }
13107 return val;
13108 }
13109 }
13110
Mike Mac2f518a2017-09-19 16:06:03 -070013111 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013112 public int getDischargeAmountScreenOff() {
13113 synchronized(this) {
13114 int val = mDischargeAmountScreenOff;
Mike Mac2f518a2017-09-19 16:06:03 -070013115 if (mOnBattery && isScreenOff(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013116 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
13117 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
13118 }
Mike Mac2f518a2017-09-19 16:06:03 -070013119 // For backward compatibility, doze discharge is counted into screen off.
13120 return val + getDischargeAmountScreenDoze();
13121 }
13122 }
13123
13124 @Override
13125 public int getDischargeAmountScreenOffSinceCharge() {
13126 synchronized(this) {
13127 int val = mDischargeAmountScreenOffSinceCharge;
13128 if (mOnBattery && isScreenOff(mScreenState)
13129 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
13130 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
13131 }
13132 // For backward compatibility, doze discharge is counted into screen off.
13133 return val + getDischargeAmountScreenDozeSinceCharge();
13134 }
13135 }
13136
13137 @Override
13138 public int getDischargeAmountScreenDoze() {
13139 synchronized(this) {
13140 int val = mDischargeAmountScreenDoze;
13141 if (mOnBattery && isScreenDoze(mScreenState)
13142 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
13143 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
13144 }
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013145 return val;
13146 }
13147 }
13148
Mike Mac2f518a2017-09-19 16:06:03 -070013149 @Override
13150 public int getDischargeAmountScreenDozeSinceCharge() {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013151 synchronized(this) {
Mike Mac2f518a2017-09-19 16:06:03 -070013152 int val = mDischargeAmountScreenDozeSinceCharge;
13153 if (mOnBattery && isScreenDoze(mScreenState)
13154 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
13155 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013156 }
13157 return val;
13158 }
13159 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013161 /**
13162 * Retrieve the statistics object for a particular uid, creating if needed.
13163 */
13164 public Uid getUidStatsLocked(int uid) {
13165 Uid u = mUidStats.get(uid);
13166 if (u == null) {
Joe Onoratoabded112016-02-08 16:49:39 -080013167 u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013168 mUidStats.put(uid, u);
13169 }
13170 return u;
13171 }
13172
Sudheer Shankab2f83c12017-11-13 19:25:01 -080013173 /**
13174 * Retrieve the statistics object for a particular uid. Returns null if the object is not
13175 * available.
13176 */
13177 public Uid getAvailableUidStatsLocked(int uid) {
13178 Uid u = mUidStats.get(uid);
13179 return u;
13180 }
13181
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070013182 public void onCleanupUserLocked(int userId) {
13183 final int firstUidForUser = UserHandle.getUid(userId, 0);
13184 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
Mike Ma234d1822018-03-13 18:53:21 -070013185 mPendingRemovedUids.add(
13186 new UidToRemove(firstUidForUser, lastUidForUser, mClocks.elapsedRealtime()));
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070013187 }
13188
13189 public void onUserRemovedLocked(int userId) {
13190 final int firstUidForUser = UserHandle.getUid(userId, 0);
13191 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
13192 mUidStats.put(firstUidForUser, null);
13193 mUidStats.put(lastUidForUser, null);
13194 final int firstIndex = mUidStats.indexOfKey(firstUidForUser);
13195 final int lastIndex = mUidStats.indexOfKey(lastUidForUser);
13196 mUidStats.removeAtRange(firstIndex, lastIndex - firstIndex + 1);
13197 }
13198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013199 /**
13200 * Remove the statistics object for a particular uid.
13201 */
13202 public void removeUidStatsLocked(int uid) {
13203 mUidStats.remove(uid);
Mike Ma234d1822018-03-13 18:53:21 -070013204 mPendingRemovedUids.add(new UidToRemove(uid, mClocks.elapsedRealtime()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013205 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -070013206
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013207 /**
13208 * Retrieve the statistics object for a particular process, creating
13209 * if needed.
13210 */
13211 public Uid.Proc getProcessStatsLocked(int uid, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013212 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013213 Uid u = getUidStatsLocked(uid);
13214 return u.getProcessStatsLocked(name);
13215 }
13216
13217 /**
13218 * Retrieve the statistics object for a particular process, creating
13219 * if needed.
13220 */
13221 public Uid.Pkg getPackageStatsLocked(int uid, String pkg) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013222 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013223 Uid u = getUidStatsLocked(uid);
13224 return u.getPackageStatsLocked(pkg);
13225 }
13226
13227 /**
13228 * Retrieve the statistics object for a particular service, creating
13229 * if needed.
13230 */
13231 public Uid.Pkg.Serv getServiceStatsLocked(int uid, String pkg, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013232 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013233 Uid u = getUidStatsLocked(uid);
13234 return u.getServiceStatsLocked(pkg, name);
13235 }
13236
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013237 public void shutdownLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080013238 recordShutdownLocked(mClocks.elapsedRealtime(), mClocks.uptimeMillis());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013239 writeSyncLocked();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013240 mShuttingDown = true;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013241 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013242
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013243 public boolean trackPerProcStateCpuTimes() {
13244 return mConstants.TRACK_CPU_TIMES_BY_PROC_STATE && mPerProcStateCpuTimesAvailable;
13245 }
13246
13247 public void systemServicesReady(Context context) {
13248 mConstants.startObserving(context.getContentResolver());
Mike Mafbc01fc2018-04-02 10:28:28 -070013249 registerUsbStateReceiver(context);
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013250 }
13251
13252 @VisibleForTesting
13253 public final class Constants extends ContentObserver {
13254 public static final String KEY_TRACK_CPU_TIMES_BY_PROC_STATE
13255 = "track_cpu_times_by_proc_state";
Mike Mafae87da2018-01-19 20:07:20 -080013256 public static final String KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME
13257 = "track_cpu_active_cluster_time";
Sudheer Shankac20379e2018-02-15 00:06:21 -080013258 public static final String KEY_PROC_STATE_CPU_TIMES_READ_DELAY_MS
13259 = "proc_state_cpu_times_read_delay_ms";
Mike Ma2ab01442018-02-13 14:22:47 -080013260 public static final String KEY_KERNEL_UID_READERS_THROTTLE_TIME
13261 = "kernel_uid_readers_throttle_time";
Mike Ma234d1822018-03-13 18:53:21 -070013262 public static final String KEY_UID_REMOVE_DELAY_MS
13263 = "uid_remove_delay_ms";
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013264
13265 private static final boolean DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE = true;
Mike Mafae87da2018-01-19 20:07:20 -080013266 private static final boolean DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME = true;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013267 private static final long DEFAULT_PROC_STATE_CPU_TIMES_READ_DELAY_MS = 5_000;
Mike Ma2ab01442018-02-13 14:22:47 -080013268 private static final long DEFAULT_KERNEL_UID_READERS_THROTTLE_TIME = 10_000;
Mike Ma234d1822018-03-13 18:53:21 -070013269 private static final long DEFAULT_UID_REMOVE_DELAY_MS = 5L * 60L * 1000L;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013270
13271 public boolean TRACK_CPU_TIMES_BY_PROC_STATE = DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE;
Mike Mafae87da2018-01-19 20:07:20 -080013272 public boolean TRACK_CPU_ACTIVE_CLUSTER_TIME = DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013273 public long PROC_STATE_CPU_TIMES_READ_DELAY_MS = DEFAULT_PROC_STATE_CPU_TIMES_READ_DELAY_MS;
Mike Ma2ab01442018-02-13 14:22:47 -080013274 public long KERNEL_UID_READERS_THROTTLE_TIME = DEFAULT_KERNEL_UID_READERS_THROTTLE_TIME;
Mike Ma234d1822018-03-13 18:53:21 -070013275 public long UID_REMOVE_DELAY_MS = DEFAULT_UID_REMOVE_DELAY_MS;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013276
13277 private ContentResolver mResolver;
13278 private final KeyValueListParser mParser = new KeyValueListParser(',');
13279
13280 public Constants(Handler handler) {
13281 super(handler);
13282 }
13283
13284 public void startObserving(ContentResolver resolver) {
13285 mResolver = resolver;
13286 mResolver.registerContentObserver(
13287 Settings.Global.getUriFor(Settings.Global.BATTERY_STATS_CONSTANTS),
13288 false /* notifyForDescendants */, this);
13289 updateConstants();
13290 }
13291
13292 @Override
13293 public void onChange(boolean selfChange, Uri uri) {
13294 updateConstants();
13295 }
13296
13297 private void updateConstants() {
13298 synchronized (BatteryStatsImpl.this) {
13299 try {
13300 mParser.setString(Settings.Global.getString(mResolver,
13301 Settings.Global.BATTERY_STATS_CONSTANTS));
13302 } catch (IllegalArgumentException e) {
13303 // Failed to parse the settings string, log this and move on
13304 // with defaults.
13305 Slog.e(TAG, "Bad batterystats settings", e);
13306 }
13307
13308 updateTrackCpuTimesByProcStateLocked(TRACK_CPU_TIMES_BY_PROC_STATE,
13309 mParser.getBoolean(KEY_TRACK_CPU_TIMES_BY_PROC_STATE,
13310 DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE));
Mike Mafae87da2018-01-19 20:07:20 -080013311 TRACK_CPU_ACTIVE_CLUSTER_TIME = mParser.getBoolean(
13312 KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME, DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME);
Sudheer Shankac20379e2018-02-15 00:06:21 -080013313 updateProcStateCpuTimesReadDelayMs(PROC_STATE_CPU_TIMES_READ_DELAY_MS,
13314 mParser.getLong(KEY_PROC_STATE_CPU_TIMES_READ_DELAY_MS,
Mike Ma2ab01442018-02-13 14:22:47 -080013315 DEFAULT_PROC_STATE_CPU_TIMES_READ_DELAY_MS));
13316 updateKernelUidReadersThrottleTime(KERNEL_UID_READERS_THROTTLE_TIME,
13317 mParser.getLong(KEY_KERNEL_UID_READERS_THROTTLE_TIME,
13318 DEFAULT_KERNEL_UID_READERS_THROTTLE_TIME));
Mike Ma234d1822018-03-13 18:53:21 -070013319 updateUidRemoveDelay(
13320 mParser.getLong(KEY_UID_REMOVE_DELAY_MS, DEFAULT_UID_REMOVE_DELAY_MS));
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013321 }
13322 }
13323
13324 private void updateTrackCpuTimesByProcStateLocked(boolean wasEnabled, boolean isEnabled) {
13325 TRACK_CPU_TIMES_BY_PROC_STATE = isEnabled;
13326 if (isEnabled && !wasEnabled) {
13327 mKernelSingleUidTimeReader.markDataAsStale(true);
13328 mExternalSync.scheduleCpuSyncDueToSettingChange();
Sudheer Shankac20379e2018-02-15 00:06:21 -080013329
Mike Ma234d1822018-03-13 18:53:21 -070013330 mNumSingleUidCpuTimeReads = 0;
13331 mNumBatchedSingleUidCpuTimeReads = 0;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013332 mCpuTimeReadsTrackingStartTime = mClocks.uptimeMillis();
13333 }
13334 }
13335
13336 private void updateProcStateCpuTimesReadDelayMs(long oldDelayMillis, long newDelayMillis) {
13337 PROC_STATE_CPU_TIMES_READ_DELAY_MS = newDelayMillis;
13338 if (oldDelayMillis != newDelayMillis) {
Mike Ma234d1822018-03-13 18:53:21 -070013339 mNumSingleUidCpuTimeReads = 0;
13340 mNumBatchedSingleUidCpuTimeReads = 0;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013341 mCpuTimeReadsTrackingStartTime = mClocks.uptimeMillis();
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013342 }
13343 }
13344
Mike Ma2ab01442018-02-13 14:22:47 -080013345 private void updateKernelUidReadersThrottleTime(long oldTimeMs, long newTimeMs) {
13346 KERNEL_UID_READERS_THROTTLE_TIME = newTimeMs;
13347 if (oldTimeMs != newTimeMs) {
Mike Ma69d8b3e2018-02-23 14:51:26 -080013348 mKernelUidCpuTimeReader.setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
Mike Ma2ab01442018-02-13 14:22:47 -080013349 mKernelUidCpuFreqTimeReader.setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
13350 mKernelUidCpuActiveTimeReader.setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
13351 mKernelUidCpuClusterTimeReader
13352 .setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
13353 }
13354 }
13355
Mike Ma234d1822018-03-13 18:53:21 -070013356 private void updateUidRemoveDelay(long newTimeMs) {
13357 UID_REMOVE_DELAY_MS = newTimeMs;
13358 clearPendingRemovedUids();
13359 }
13360
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013361 public void dumpLocked(PrintWriter pw) {
13362 pw.print(KEY_TRACK_CPU_TIMES_BY_PROC_STATE); pw.print("=");
13363 pw.println(TRACK_CPU_TIMES_BY_PROC_STATE);
Mike Mafae87da2018-01-19 20:07:20 -080013364 pw.print(KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME); pw.print("=");
13365 pw.println(TRACK_CPU_ACTIVE_CLUSTER_TIME);
Sudheer Shankac20379e2018-02-15 00:06:21 -080013366 pw.print(KEY_PROC_STATE_CPU_TIMES_READ_DELAY_MS); pw.print("=");
13367 pw.println(PROC_STATE_CPU_TIMES_READ_DELAY_MS);
Mike Ma2ab01442018-02-13 14:22:47 -080013368 pw.print(KEY_KERNEL_UID_READERS_THROTTLE_TIME); pw.print("=");
13369 pw.println(KERNEL_UID_READERS_THROTTLE_TIME);
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013370 }
13371 }
13372
Andreas Gampe3f24e692018-02-05 13:24:28 -080013373 @GuardedBy("this")
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013374 public void dumpConstantsLocked(PrintWriter pw) {
13375 mConstants.dumpLocked(pw);
13376 }
13377
Mike Ma234d1822018-03-13 18:53:21 -070013378 @GuardedBy("this")
13379 public void dumpCpuStatsLocked(PrintWriter pw) {
13380 int size = mUidStats.size();
13381 pw.println("Per UID CPU user & system time in ms:");
13382 for (int i = 0; i < size; i++) {
13383 int u = mUidStats.keyAt(i);
13384 Uid uid = mUidStats.get(u);
13385 pw.print(" "); pw.print(u); pw.print(": ");
13386 pw.print(uid.getUserCpuTimeUs(STATS_SINCE_CHARGED) / 1000); pw.print(" ");
13387 pw.println(uid.getSystemCpuTimeUs(STATS_SINCE_CHARGED) / 1000);
13388 }
13389 pw.println("Per UID CPU active time in ms:");
13390 for (int i = 0; i < size; i++) {
13391 int u = mUidStats.keyAt(i);
13392 Uid uid = mUidStats.get(u);
13393 if (uid.getCpuActiveTime() > 0) {
13394 pw.print(" "); pw.print(u); pw.print(": "); pw.println(uid.getCpuActiveTime());
13395 }
13396 }
13397 pw.println("Per UID CPU cluster time in ms:");
13398 for (int i = 0; i < size; i++) {
13399 int u = mUidStats.keyAt(i);
13400 long[] times = mUidStats.get(u).getCpuClusterTimes();
13401 if (times != null) {
13402 pw.print(" "); pw.print(u); pw.print(": "); pw.println(Arrays.toString(times));
13403 }
13404 }
13405 pw.println("Per UID CPU frequency time in ms:");
13406 for (int i = 0; i < size; i++) {
13407 int u = mUidStats.keyAt(i);
13408 long[] times = mUidStats.get(u).getCpuFreqTimes(STATS_SINCE_CHARGED);
13409 if (times != null) {
13410 pw.print(" "); pw.print(u); pw.print(": "); pw.println(Arrays.toString(times));
13411 }
13412 }
13413 }
13414
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013415 Parcel mPendingWrite = null;
13416 final ReentrantLock mWriteLock = new ReentrantLock();
13417
13418 public void writeAsyncLocked() {
13419 writeLocked(false);
13420 }
13421
13422 public void writeSyncLocked() {
13423 writeLocked(true);
13424 }
13425
13426 void writeLocked(boolean sync) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013427 if (mFile == null) {
13428 Slog.w("BatteryStats", "writeLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013429 return;
13430 }
13431
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013432 if (mShuttingDown) {
13433 return;
13434 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013435
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013436 Parcel out = Parcel.obtain();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013437 writeSummaryToParcel(out, true);
Joe Onoratoabded112016-02-08 16:49:39 -080013438 mLastWriteTime = mClocks.elapsedRealtime();
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013439
13440 if (mPendingWrite != null) {
13441 mPendingWrite.recycle();
13442 }
13443 mPendingWrite = out;
13444
13445 if (sync) {
13446 commitPendingDataToDisk();
13447 } else {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013448 BackgroundThread.getHandler().post(new Runnable() {
13449 @Override public void run() {
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013450 commitPendingDataToDisk();
13451 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013452 });
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013453 }
13454 }
13455
13456 public void commitPendingDataToDisk() {
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070013457 final Parcel next;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013458 synchronized (this) {
13459 next = mPendingWrite;
13460 mPendingWrite = null;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070013461 if (next == null) {
13462 return;
13463 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013464 }
13465
Amith Yamasanid2450862017-02-07 15:58:24 -080013466 mWriteLock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013467 try {
Dianne Hackborne17b4452018-01-10 13:15:40 -080013468 final long startTime = SystemClock.uptimeMillis();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013469 FileOutputStream stream = new FileOutputStream(mFile.chooseForWrite());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013470 stream.write(next.marshall());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013471 stream.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070013472 FileUtils.sync(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013473 stream.close();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013474 mFile.commit();
Dianne Hackborne17b4452018-01-10 13:15:40 -080013475 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
13476 "batterystats", SystemClock.uptimeMillis() - startTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013477 } catch (IOException e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013478 Slog.w("BatteryStats", "Error writing battery statistics", e);
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013479 mFile.rollback();
13480 } finally {
13481 next.recycle();
13482 mWriteLock.unlock();
Suchi Amalapurapu8550f252009-09-29 15:20:32 -070013483 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013484 }
13485
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013486 public void readLocked() {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013487 if (mDailyFile != null) {
13488 readDailyStatsLocked();
13489 }
13490
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013491 if (mFile == null) {
13492 Slog.w("BatteryStats", "readLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013493 return;
13494 }
13495
13496 mUidStats.clear();
13497
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013498 try {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013499 File file = mFile.chooseForRead();
13500 if (!file.exists()) {
13501 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013502 }
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013503 FileInputStream stream = new FileInputStream(file);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013504
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013505 byte[] raw = BatteryStatsHelper.readFully(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013506 Parcel in = Parcel.obtain();
13507 in.unmarshall(raw, 0, raw.length);
13508 in.setDataPosition(0);
13509 stream.close();
13510
13511 readSummaryFromParcel(in);
Dianne Hackborn00e25212014-02-19 10:49:24 -080013512 } catch(Exception e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013513 Slog.e("BatteryStats", "Error reading battery statistics", e);
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013514 resetAllStatsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013515 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013516
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013517 mEndPlatformVersion = Build.ID;
13518
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013519 if (mHistoryBuffer.dataPosition() > 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013520 mRecordingHistory = true;
Joe Onoratoabded112016-02-08 16:49:39 -080013521 final long elapsedRealtime = mClocks.elapsedRealtime();
13522 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013523 if (USE_OLD_HISTORY) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013524 addHistoryRecordLocked(elapsedRealtime, uptime, HistoryItem.CMD_START, mHistoryCur);
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013525 }
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000013526 addHistoryBufferLocked(elapsedRealtime, HistoryItem.CMD_START, mHistoryCur);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013527 startRecordingHistory(elapsedRealtime, uptime, false);
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013528 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013529
13530 recordDailyStatsIfNeededLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013531 }
13532
13533 public int describeContents() {
13534 return 0;
13535 }
13536
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013537 void readHistory(Parcel in, boolean andOldHistory) throws ParcelFormatException {
Dianne Hackbornae384452011-06-28 12:33:48 -070013538 final long historyBaseTime = in.readLong();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013539
13540 mHistoryBuffer.setDataSize(0);
13541 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013542 mHistoryTagPool.clear();
13543 mNextHistoryTagIdx = 0;
13544 mNumHistoryTagChars = 0;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013545
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013546 int numTags = in.readInt();
13547 for (int i=0; i<numTags; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080013548 int idx = in.readInt();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013549 String str = in.readString();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013550 if (str == null) {
13551 throw new ParcelFormatException("null history tag string");
13552 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013553 int uid = in.readInt();
13554 HistoryTag tag = new HistoryTag();
13555 tag.string = str;
13556 tag.uid = uid;
13557 tag.poolIdx = idx;
13558 mHistoryTagPool.put(tag, idx);
13559 if (idx >= mNextHistoryTagIdx) {
13560 mNextHistoryTagIdx = idx+1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013561 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013562 mNumHistoryTagChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013563 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013564
13565 int bufSize = in.readInt();
13566 int curPos = in.dataPosition();
13567 if (bufSize >= (MAX_MAX_HISTORY_BUFFER*3)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013568 throw new ParcelFormatException("File corrupt: history data buffer too large " +
13569 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013570 } else if ((bufSize&~3) != bufSize) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013571 throw new ParcelFormatException("File corrupt: history data buffer not aligned " +
13572 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013573 } else {
13574 if (DEBUG_HISTORY) Slog.i(TAG, "***************** READING NEW HISTORY: " + bufSize
13575 + " bytes at " + curPos);
13576 mHistoryBuffer.appendFrom(in, curPos, bufSize);
13577 in.setDataPosition(curPos + bufSize);
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013578 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013579
Dianne Hackbornae384452011-06-28 12:33:48 -070013580 if (andOldHistory) {
13581 readOldHistory(in);
13582 }
13583
13584 if (DEBUG_HISTORY) {
13585 StringBuilder sb = new StringBuilder(128);
13586 sb.append("****************** OLD mHistoryBaseTime: ");
13587 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13588 Slog.i(TAG, sb.toString());
13589 }
13590 mHistoryBaseTime = historyBaseTime;
13591 if (DEBUG_HISTORY) {
13592 StringBuilder sb = new StringBuilder(128);
13593 sb.append("****************** NEW mHistoryBaseTime: ");
13594 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13595 Slog.i(TAG, sb.toString());
13596 }
13597
13598 // We are just arbitrarily going to insert 1 minute from the sample of
13599 // the last run until samples in this run.
13600 if (mHistoryBaseTime > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -080013601 long oldnow = mClocks.elapsedRealtime();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013602 mHistoryBaseTime = mHistoryBaseTime - oldnow + 1;
Dianne Hackbornae384452011-06-28 12:33:48 -070013603 if (DEBUG_HISTORY) {
13604 StringBuilder sb = new StringBuilder(128);
13605 sb.append("****************** ADJUSTED mHistoryBaseTime: ");
13606 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13607 Slog.i(TAG, sb.toString());
13608 }
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -070013609 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013610 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013611
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013612 void readOldHistory(Parcel in) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013613 if (!USE_OLD_HISTORY) {
13614 return;
13615 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013616 mHistory = mHistoryEnd = mHistoryCache = null;
13617 long time;
Conley Owens5e3357f2011-05-02 09:59:30 -070013618 while (in.dataAvail() > 0 && (time=in.readLong()) >= 0) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013619 HistoryItem rec = new HistoryItem(time, in);
13620 addHistoryRecordLocked(rec);
13621 }
13622 }
13623
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013624 void writeHistory(Parcel out, boolean inclData, boolean andOldHistory) {
Dianne Hackbornae384452011-06-28 12:33:48 -070013625 if (DEBUG_HISTORY) {
13626 StringBuilder sb = new StringBuilder(128);
13627 sb.append("****************** WRITING mHistoryBaseTime: ");
13628 TimeUtils.formatDuration(mHistoryBaseTime, sb);
Dianne Hackborn40c87252014-03-19 16:55:40 -070013629 sb.append(" mLastHistoryElapsedRealtime: ");
13630 TimeUtils.formatDuration(mLastHistoryElapsedRealtime, sb);
Dianne Hackbornae384452011-06-28 12:33:48 -070013631 Slog.i(TAG, sb.toString());
13632 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070013633 out.writeLong(mHistoryBaseTime + mLastHistoryElapsedRealtime);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013634 if (!inclData) {
13635 out.writeInt(0);
13636 out.writeInt(0);
13637 return;
13638 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013639 out.writeInt(mHistoryTagPool.size());
13640 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
13641 HistoryTag tag = ent.getKey();
Dianne Hackborn099bc622014-01-22 13:39:16 -080013642 out.writeInt(ent.getValue());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013643 out.writeString(tag.string);
13644 out.writeInt(tag.uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -080013645 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013646 out.writeInt(mHistoryBuffer.dataSize());
13647 if (DEBUG_HISTORY) Slog.i(TAG, "***************** WRITING HISTORY: "
13648 + mHistoryBuffer.dataSize() + " bytes at " + out.dataPosition());
13649 out.appendFrom(mHistoryBuffer, 0, mHistoryBuffer.dataSize());
Dianne Hackbornae384452011-06-28 12:33:48 -070013650
13651 if (andOldHistory) {
13652 writeOldHistory(out);
13653 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013654 }
13655
13656 void writeOldHistory(Parcel out) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013657 if (!USE_OLD_HISTORY) {
13658 return;
13659 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013660 HistoryItem rec = mHistory;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013661 while (rec != null) {
13662 if (rec.time >= 0) rec.writeToParcel(out, 0);
13663 rec = rec.next;
13664 }
13665 out.writeLong(-1);
13666 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013667
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013668 public void readSummaryFromParcel(Parcel in) throws ParcelFormatException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013669 final int version = in.readInt();
13670 if (version != VERSION) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013671 Slog.w("BatteryStats", "readFromParcel: version got " + version
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013672 + ", expected " + VERSION + "; erasing old stats");
13673 return;
13674 }
13675
Dianne Hackbornae384452011-06-28 12:33:48 -070013676 readHistory(in, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013678 mStartCount = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013679 mUptime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013680 mRealtime = in.readLong();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080013681 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013682 mStartPlatformVersion = in.readString();
13683 mEndPlatformVersion = in.readString();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013684 mOnBatteryTimeBase.readSummaryFromParcel(in);
13685 mOnBatteryScreenOffTimeBase.readSummaryFromParcel(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013686 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013687 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070013688 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013689 mCurrentBatteryLevel = in.readInt();
Adam Lesinskif9b20a92016-06-17 17:30:01 -070013690 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070013691 mMinLearnedBatteryCapacity = in.readInt();
13692 mMaxLearnedBatteryCapacity = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013693 mLowDischargeAmountSinceCharge = in.readInt();
13694 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013695 mDischargeAmountScreenOnSinceCharge = in.readInt();
13696 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070013697 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013698 mDischargeStepTracker.readFromParcel(in);
13699 mChargeStepTracker.readFromParcel(in);
13700 mDailyDischargeStepTracker.readFromParcel(in);
13701 mDailyChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070013702 mDischargeCounter.readSummaryFromParcelLocked(in);
13703 mDischargeScreenOffCounter.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070013704 mDischargeScreenDozeCounter.readSummaryFromParcelLocked(in);
Mike Ma15313c92017-11-15 17:58:21 -080013705 mDischargeLightDozeCounter.readSummaryFromParcelLocked(in);
13706 mDischargeDeepDozeCounter.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013707 int NPKG = in.readInt();
13708 if (NPKG > 0) {
13709 mDailyPackageChanges = new ArrayList<>(NPKG);
13710 while (NPKG > 0) {
13711 NPKG--;
13712 PackageChange pc = new PackageChange();
13713 pc.mPackageName = in.readString();
13714 pc.mUpdate = in.readInt() != 0;
Dianne Hackborn3accca02013-09-20 09:32:11 -070013715 pc.mVersionCode = in.readLong();
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013716 mDailyPackageChanges.add(pc);
13717 }
13718 } else {
13719 mDailyPackageChanges = null;
13720 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013721 mDailyStartTime = in.readLong();
13722 mNextMinDailyDeadline = in.readLong();
13723 mNextMaxDailyDeadline = in.readLong();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013724
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013725 mStartCount++;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013726
Jeff Browne95c3cd2014-05-02 16:59:26 -070013727 mScreenState = Display.STATE_UNKNOWN;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013728 mScreenOnTimer.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070013729 mScreenDozeTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn617f8772009-03-31 15:04:46 -070013730 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
13731 mScreenBrightnessTimer[i].readSummaryFromParcelLocked(in);
13732 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070013733 mInteractive = false;
13734 mInteractiveTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013735 mPhoneOn = false;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070013736 mPowerSaveModeEnabledTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070013737 mLongestLightIdleTime = in.readLong();
13738 mLongestFullIdleTime = in.readLong();
13739 mDeviceIdleModeLightTimer.readSummaryFromParcelLocked(in);
13740 mDeviceIdleModeFullTimer.readSummaryFromParcelLocked(in);
13741 mDeviceLightIdlingTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013742 mDeviceIdlingTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013743 mPhoneOnTimer.readSummaryFromParcelLocked(in);
Wink Saville52840902011-02-18 12:40:47 -080013744 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn627bba72009-03-24 22:32:56 -070013745 mPhoneSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
13746 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070013747 mPhoneSignalScanningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013748 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
13749 mPhoneDataConnectionsTimer[i].readSummaryFromParcelLocked(in);
13750 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013751 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013752 mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
13753 mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013754 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013755 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborne13c4c02014-02-11 17:18:35 -080013756 mMobileRadioActiveTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080013757 mMobileRadioActivePerAppTimer.readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013758 mMobileRadioActiveAdjustedTime.readSummaryFromParcelLocked(in);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013759 mMobileRadioActiveUnknownTime.readSummaryFromParcelLocked(in);
13760 mMobileRadioActiveUnknownCount.readSummaryFromParcelLocked(in);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080013761 mWifiMulticastWakelockTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070013762 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
The Android Open Source Project10592532009-03-18 17:39:46 -070013763 mWifiOn = false;
13764 mWifiOnTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013765 mGlobalWifiRunning = false;
13766 mGlobalWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080013767 for (int i=0; i<NUM_WIFI_STATES; i++) {
13768 mWifiStateTimer[i].readSummaryFromParcelLocked(in);
13769 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070013770 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
13771 mWifiSupplStateTimer[i].readSummaryFromParcelLocked(in);
13772 }
13773 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
13774 mWifiSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
13775 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080013776 mWifiActiveTimer.readSummaryFromParcelLocked(in);
13777 mWifiActivity.readSummaryFromParcel(in);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080013778 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
13779 mGpsSignalQualityTimer[i].readSummaryFromParcelLocked(in);
13780 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080013781 mBluetoothActivity.readSummaryFromParcel(in);
13782 mModemActivity.readSummaryFromParcel(in);
13783 mHasWifiReporting = in.readInt() != 0;
13784 mHasBluetoothReporting = in.readInt() != 0;
13785 mHasModemReporting = in.readInt() != 0;
Adam Lesinski33dac552015-03-09 15:24:48 -070013786
Dianne Hackborn1e01d162014-12-04 17:46:42 -080013787 mNumConnectivityChange = mLoadedNumConnectivityChange = in.readInt();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013788 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -070013789 mFlashlightOnTimer.readSummaryFromParcelLocked(in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013790 mCameraOnNesting = 0;
13791 mCameraOnTimer.readSummaryFromParcelLocked(in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013792 mBluetoothScanNesting = 0;
13793 mBluetoothScanTimer.readSummaryFromParcelLocked(in);
Siddharth Rayf5e796a2018-01-22 18:18:17 -080013794 mIsCellularTxPowerHigh = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013795
Bookatz50df7112017-08-04 14:53:26 -070013796 int NRPMS = in.readInt();
13797 if (NRPMS > 10000) {
13798 throw new ParcelFormatException("File corrupt: too many rpm stats " + NRPMS);
13799 }
13800 for (int irpm = 0; irpm < NRPMS; irpm++) {
13801 if (in.readInt() != 0) {
13802 String rpmName = in.readString();
13803 getRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
13804 }
13805 }
13806 int NSORPMS = in.readInt();
13807 if (NSORPMS > 10000) {
13808 throw new ParcelFormatException("File corrupt: too many screen-off rpm stats " + NSORPMS);
13809 }
13810 for (int irpm = 0; irpm < NSORPMS; irpm++) {
13811 if (in.readInt() != 0) {
13812 String rpmName = in.readString();
13813 getScreenOffRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
13814 }
13815 }
13816
Evan Millarc64edde2009-04-18 12:26:32 -070013817 int NKW = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013818 if (NKW > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013819 throw new ParcelFormatException("File corrupt: too many kernel wake locks " + NKW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013820 }
Evan Millarc64edde2009-04-18 12:26:32 -070013821 for (int ikw = 0; ikw < NKW; ikw++) {
13822 if (in.readInt() != 0) {
13823 String kwltName = in.readString();
13824 getKernelWakelockTimerLocked(kwltName).readSummaryFromParcelLocked(in);
13825 }
13826 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070013827
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013828 int NWR = in.readInt();
13829 if (NWR > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013830 throw new ParcelFormatException("File corrupt: too many wakeup reasons " + NWR);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013831 }
13832 for (int iwr = 0; iwr < NWR; iwr++) {
13833 if (in.readInt() != 0) {
13834 String reasonName = in.readString();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070013835 getWakeupReasonTimerLocked(reasonName).readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013836 }
13837 }
13838
James Carr3a226052016-07-01 14:49:52 -070013839 int NMS = in.readInt();
13840 for (int ims = 0; ims < NMS; ims++) {
13841 if (in.readInt() != 0) {
13842 long kmstName = in.readLong();
13843 getKernelMemoryTimerLocked(kmstName).readSummaryFromParcelLocked(in);
13844 }
13845 }
13846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013847 final int NU = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013848 if (NU > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013849 throw new ParcelFormatException("File corrupt: too many uids " + NU);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013850 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013851 for (int iu = 0; iu < NU; iu++) {
13852 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080013853 Uid u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013854 mUidStats.put(uid, u);
13855
Bookatz867c0d72017-03-07 18:23:42 -080013856 u.mOnBatteryBackgroundTimeBase.readSummaryFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -070013857 u.mOnBatteryScreenOffBackgroundTimeBase.readSummaryFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -080013858
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013859 u.mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013860 if (in.readInt() != 0) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013861 u.mWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013862 }
The Android Open Source Project10592532009-03-18 17:39:46 -070013863 u.mFullWifiLockOut = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013864 if (in.readInt() != 0) {
13865 u.mFullWifiLockTimer.readSummaryFromParcelLocked(in);
13866 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070013867 u.mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013868 if (in.readInt() != 0) {
Nick Pelly6ccaa542012-06-15 15:22:47 -070013869 u.mWifiScanTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013870 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070013871 u.mWifiBatchedScanBinStarted = Uid.NO_BATCHED_SCAN_STARTED;
13872 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
13873 if (in.readInt() != 0) {
13874 u.makeWifiBatchedScanBin(i, null);
13875 u.mWifiBatchedScanTimer[i].readSummaryFromParcelLocked(in);
13876 }
13877 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070013878 u.mWifiMulticastEnabled = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013879 if (in.readInt() != 0) {
13880 u.mWifiMulticastTimer.readSummaryFromParcelLocked(in);
13881 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013882 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013883 u.createAudioTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013884 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013885 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013886 u.createVideoTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13887 }
13888 if (in.readInt() != 0) {
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013889 u.createFlashlightTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13890 }
13891 if (in.readInt() != 0) {
13892 u.createCameraTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13893 }
13894 if (in.readInt() != 0) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013895 u.createForegroundActivityTimerLocked().readSummaryFromParcelLocked(in);
13896 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013897 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070013898 u.createForegroundServiceTimerLocked().readSummaryFromParcelLocked(in);
13899 }
13900 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -070013901 u.createAggregatedPartialWakelockTimerLocked().readSummaryFromParcelLocked(in);
13902 }
13903 if (in.readInt() != 0) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013904 u.createBluetoothScanTimerLocked().readSummaryFromParcelLocked(in);
13905 }
Bookatz956f36bf2017-04-28 09:48:17 -070013906 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -070013907 u.createBluetoothUnoptimizedScanTimerLocked().readSummaryFromParcelLocked(in);
13908 }
13909 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -070013910 u.createBluetoothScanResultCounterLocked().readSummaryFromParcelLocked(in);
13911 }
Bookatzb1f04f32017-05-19 13:57:32 -070013912 if (in.readInt() != 0) {
13913 u.createBluetoothScanResultBgCounterLocked().readSummaryFromParcelLocked(in);
13914 }
Dianne Hackborna8d10942015-11-19 17:55:19 -080013915 u.mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -070013916 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
13917 if (in.readInt() != 0) {
13918 u.makeProcessState(i, null);
13919 u.mProcessStateTimer[i].readSummaryFromParcelLocked(in);
13920 }
13921 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013922 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013923 u.createVibratorOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013924 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070013925
Dianne Hackborn617f8772009-03-31 15:04:46 -070013926 if (in.readInt() != 0) {
13927 if (u.mUserActivityCounters == null) {
13928 u.initUserActivityLocked();
13929 }
13930 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
13931 u.mUserActivityCounters[i].readSummaryFromParcelLocked(in);
13932 }
13933 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013934
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013935 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013936 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013937 u.initNetworkActivityLocked();
13938 }
13939 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013940 u.mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
13941 u.mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013942 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013943 u.mMobileRadioActiveTime.readSummaryFromParcelLocked(in);
13944 u.mMobileRadioActiveCount.readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013945 }
13946
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013947 u.mUserCpuTime.readSummaryFromParcelLocked(in);
13948 u.mSystemCpuTime.readSummaryFromParcelLocked(in);
13949
Adam Lesinski6832f392015-09-05 18:05:40 -070013950 if (in.readInt() != 0) {
13951 final int numClusters = in.readInt();
13952 if (mPowerProfile != null && mPowerProfile.getNumCpuClusters() != numClusters) {
13953 throw new ParcelFormatException("Incompatible cpu cluster arrangement");
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013954 }
Adam Lesinski6832f392015-09-05 18:05:40 -070013955
Sudheer Shankaaf857412017-07-21 00:14:24 -070013956 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -070013957 for (int cluster = 0; cluster < numClusters; cluster++) {
Adam Lesinski6832f392015-09-05 18:05:40 -070013958 if (in.readInt() != 0) {
Adam Lesinskia57a5402015-09-28 10:21:33 -070013959 final int NSB = in.readInt();
13960 if (mPowerProfile != null &&
13961 mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != NSB) {
13962 throw new ParcelFormatException("File corrupt: too many speed bins " +
13963 NSB);
13964 }
13965
Sudheer Shankaaf857412017-07-21 00:14:24 -070013966 u.mCpuClusterSpeedTimesUs[cluster] = new LongSamplingCounter[NSB];
Adam Lesinski6832f392015-09-05 18:05:40 -070013967 for (int speed = 0; speed < NSB; speed++) {
13968 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070013969 u.mCpuClusterSpeedTimesUs[cluster][speed] = new LongSamplingCounter(
Adam Lesinski6832f392015-09-05 18:05:40 -070013970 mOnBatteryTimeBase);
Sudheer Shankaaf857412017-07-21 00:14:24 -070013971 u.mCpuClusterSpeedTimesUs[cluster][speed].readSummaryFromParcelLocked(in);
Adam Lesinski6832f392015-09-05 18:05:40 -070013972 }
13973 }
Adam Lesinskia57a5402015-09-28 10:21:33 -070013974 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070013975 u.mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -070013976 }
13977 }
13978 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070013979 u.mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013980 }
13981
Sudheer Shanka59f5c002017-05-15 10:57:15 -070013982 u.mCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
13983 in, mOnBatteryTimeBase);
13984 u.mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
13985 in, mOnBatteryScreenOffTimeBase);
Mike Ma3d422c32017-10-25 11:08:57 -070013986
13987 u.mCpuActiveTimeMs.readSummaryFromParcelLocked(in);
13988 u.mCpuClusterTimesMs.readSummaryFromParcelLocked(in);
13989
Sudheer Shankab2f83c12017-11-13 19:25:01 -080013990 int length = in.readInt();
13991 if (length == Uid.NUM_PROCESS_STATE) {
13992 u.mProcStateTimeMs = new LongSamplingCounterArray[length];
13993 for (int procState = 0; procState < length; ++procState) {
13994 u.mProcStateTimeMs[procState]
13995 = LongSamplingCounterArray.readSummaryFromParcelLocked(
13996 in, mOnBatteryTimeBase);
13997 }
13998 } else {
13999 u.mProcStateTimeMs = null;
14000 }
14001 length = in.readInt();
14002 if (length == Uid.NUM_PROCESS_STATE) {
14003 u.mProcStateScreenOffTimeMs = new LongSamplingCounterArray[length];
14004 for (int procState = 0; procState < length; ++procState) {
14005 u.mProcStateScreenOffTimeMs[procState]
14006 = LongSamplingCounterArray.readSummaryFromParcelLocked(
14007 in, mOnBatteryScreenOffTimeBase);
14008 }
14009 } else {
14010 u.mProcStateScreenOffTimeMs = null;
14011 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070014012
14013 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -070014014 u.mMobileRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
14015 u.mMobileRadioApWakeupCount.readSummaryFromParcelLocked(in);
14016 } else {
14017 u.mMobileRadioApWakeupCount = null;
14018 }
14019
14020 if (in.readInt() != 0) {
14021 u.mWifiRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
14022 u.mWifiRadioApWakeupCount.readSummaryFromParcelLocked(in);
14023 } else {
14024 u.mWifiRadioApWakeupCount = null;
14025 }
14026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014027 int NW = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070014028 if (NW > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014029 throw new ParcelFormatException("File corrupt: too many wake locks " + NW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014030 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014031 for (int iw = 0; iw < NW; iw++) {
14032 String wlName = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014033 u.readWakeSummaryFromParcelLocked(wlName, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014034 }
14035
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014036 int NS = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070014037 if (NS > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014038 throw new ParcelFormatException("File corrupt: too many syncs " + NS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014039 }
14040 for (int is = 0; is < NS; is++) {
14041 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014042 u.readSyncSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014043 }
14044
14045 int NJ = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070014046 if (NJ > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014047 throw new ParcelFormatException("File corrupt: too many job timers " + NJ);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014048 }
14049 for (int ij = 0; ij < NJ; ij++) {
14050 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014051 u.readJobSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014052 }
14053
Dianne Hackborn94326cb2017-06-28 16:17:20 -070014054 u.readJobCompletionsFromParcelLocked(in);
14055
Amith Yamasani977e11f2018-02-16 11:29:54 -080014056 u.mJobsDeferredEventCount.readSummaryFromParcelLocked(in);
14057 u.mJobsDeferredCount.readSummaryFromParcelLocked(in);
14058 u.mJobsFreshnessTimeMs.readSummaryFromParcelLocked(in);
14059 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
14060 if (in.readInt() != 0) {
14061 u.mJobsFreshnessBuckets[i] = new Counter(u.mBsi.mOnBatteryTimeBase);
14062 u.mJobsFreshnessBuckets[i].readSummaryFromParcelLocked(in);
14063 }
14064 }
14065
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014066 int NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014067 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014068 throw new ParcelFormatException("File corrupt: too many sensors " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014069 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014070 for (int is = 0; is < NP; is++) {
14071 int seNumber = in.readInt();
14072 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -080014073 u.getSensorTimerLocked(seNumber, true).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014074 }
14075 }
14076
14077 NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014078 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014079 throw new ParcelFormatException("File corrupt: too many processes " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014080 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014081 for (int ip = 0; ip < NP; ip++) {
14082 String procName = in.readString();
14083 Uid.Proc p = u.getProcessStatsLocked(procName);
14084 p.mUserTime = p.mLoadedUserTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014085 p.mSystemTime = p.mLoadedSystemTime = in.readLong();
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014086 p.mForegroundTime = p.mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014087 p.mStarts = p.mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014088 p.mNumCrashes = p.mLoadedNumCrashes = in.readInt();
14089 p.mNumAnrs = p.mLoadedNumAnrs = in.readInt();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014090 p.readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014091 }
14092
14093 NP = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014094 if (NP > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014095 throw new ParcelFormatException("File corrupt: too many packages " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014096 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014097 for (int ip = 0; ip < NP; ip++) {
14098 String pkgName = in.readString();
14099 Uid.Pkg p = u.getPackageStatsLocked(pkgName);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014100 final int NWA = in.readInt();
14101 if (NWA > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014102 throw new ParcelFormatException("File corrupt: too many wakeup alarms " + NWA);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014103 }
14104 p.mWakeupAlarms.clear();
14105 for (int iwa=0; iwa<NWA; iwa++) {
14106 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -070014107 Counter c = new Counter(mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014108 c.readSummaryFromParcelLocked(in);
14109 p.mWakeupAlarms.put(tag, c);
14110 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014111 NS = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014112 if (NS > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014113 throw new ParcelFormatException("File corrupt: too many services " + NS);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014114 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014115 for (int is = 0; is < NS; is++) {
14116 String servName = in.readString();
14117 Uid.Pkg.Serv s = u.getServiceStatsLocked(pkgName, servName);
14118 s.mStartTime = s.mLoadedStartTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014119 s.mStarts = s.mLoadedStarts = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014120 s.mLaunches = s.mLoadedLaunches = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014121 }
14122 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014123 }
14124 }
14125
14126 /**
14127 * Writes a summary of the statistics to a Parcel, in a format suitable to be written to
14128 * disk. This format does not allow a lossless round-trip.
14129 *
14130 * @param out the Parcel to be written to.
14131 */
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070014132 public void writeSummaryToParcel(Parcel out, boolean inclHistory) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080014133 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014134
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014135 // Pull the clock time. This may update the time and make a new history entry
14136 // if we had originally pulled a time before the RTC was set.
14137 long startClockTime = getStartClockTime();
14138
Joe Onoratoabded112016-02-08 16:49:39 -080014139 final long NOW_SYS = mClocks.uptimeMillis() * 1000;
14140 final long NOWREAL_SYS = mClocks.elapsedRealtime() * 1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014141
14142 out.writeInt(VERSION);
14143
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070014144 writeHistory(out, inclHistory, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014145
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014146 out.writeInt(mStartCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014147 out.writeLong(computeUptime(NOW_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014148 out.writeLong(computeRealtime(NOWREAL_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014149 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014150 out.writeString(mStartPlatformVersion);
14151 out.writeString(mEndPlatformVersion);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014152 mOnBatteryTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
14153 mOnBatteryScreenOffTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014154 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014155 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070014156 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014157 out.writeInt(mCurrentBatteryLevel);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014158 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070014159 out.writeInt(mMinLearnedBatteryCapacity);
14160 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborne4a59512010-12-07 11:08:07 -080014161 out.writeInt(getLowDischargeAmountSinceCharge());
14162 out.writeInt(getHighDischargeAmountSinceCharge());
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014163 out.writeInt(getDischargeAmountScreenOnSinceCharge());
14164 out.writeInt(getDischargeAmountScreenOffSinceCharge());
Mike Mac2f518a2017-09-19 16:06:03 -070014165 out.writeInt(getDischargeAmountScreenDozeSinceCharge());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014166 mDischargeStepTracker.writeToParcel(out);
14167 mChargeStepTracker.writeToParcel(out);
14168 mDailyDischargeStepTracker.writeToParcel(out);
14169 mDailyChargeStepTracker.writeToParcel(out);
Adam Lesinski67c134f2016-06-10 15:15:08 -070014170 mDischargeCounter.writeSummaryFromParcelLocked(out);
14171 mDischargeScreenOffCounter.writeSummaryFromParcelLocked(out);
Mike Mac2f518a2017-09-19 16:06:03 -070014172 mDischargeScreenDozeCounter.writeSummaryFromParcelLocked(out);
Mike Ma15313c92017-11-15 17:58:21 -080014173 mDischargeLightDozeCounter.writeSummaryFromParcelLocked(out);
14174 mDischargeDeepDozeCounter.writeSummaryFromParcelLocked(out);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014175 if (mDailyPackageChanges != null) {
14176 final int NPKG = mDailyPackageChanges.size();
14177 out.writeInt(NPKG);
14178 for (int i=0; i<NPKG; i++) {
14179 PackageChange pc = mDailyPackageChanges.get(i);
14180 out.writeString(pc.mPackageName);
14181 out.writeInt(pc.mUpdate ? 1 : 0);
Dianne Hackborn3accca02013-09-20 09:32:11 -070014182 out.writeLong(pc.mVersionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014183 }
14184 } else {
14185 out.writeInt(0);
14186 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014187 out.writeLong(mDailyStartTime);
14188 out.writeLong(mNextMinDailyDeadline);
14189 out.writeLong(mNextMaxDailyDeadline);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014190
14191 mScreenOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Mike Mac2f518a2017-09-19 16:06:03 -070014192 mScreenDozeTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070014193 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014194 mScreenBrightnessTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070014195 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070014196 mInteractiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070014197 mPowerSaveModeEnabledTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014198 out.writeLong(mLongestLightIdleTime);
14199 out.writeLong(mLongestFullIdleTime);
14200 mDeviceIdleModeLightTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14201 mDeviceIdleModeFullTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14202 mDeviceLightIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014203 mDeviceIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014204 mPhoneOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Wink Saville52840902011-02-18 12:40:47 -080014205 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014206 mPhoneSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070014207 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014208 mPhoneSignalScanningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070014209 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014210 mPhoneDataConnectionsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070014211 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014212 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014213 mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
14214 mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014215 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014216 mMobileRadioActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14217 mMobileRadioActivePerAppTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014218 mMobileRadioActiveAdjustedTime.writeSummaryFromParcelLocked(out);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080014219 mMobileRadioActiveUnknownTime.writeSummaryFromParcelLocked(out);
14220 mMobileRadioActiveUnknownCount.writeSummaryFromParcelLocked(out);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014221 mWifiMulticastWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014222 mWifiOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14223 mGlobalWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080014224 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014225 mWifiStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080014226 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014227 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
14228 mWifiSupplStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14229 }
14230 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
14231 mWifiSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14232 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014233 mWifiActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14234 mWifiActivity.writeSummaryToParcel(out);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014235 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14236 mGpsSignalQualityTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14237 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014238 mBluetoothActivity.writeSummaryToParcel(out);
14239 mModemActivity.writeSummaryToParcel(out);
14240 out.writeInt(mHasWifiReporting ? 1 : 0);
14241 out.writeInt(mHasBluetoothReporting ? 1 : 0);
14242 out.writeInt(mHasModemReporting ? 1 : 0);
14243
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014244 out.writeInt(mNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070014245 mFlashlightOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014246 mCameraOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014247 mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014248
Bookatz50df7112017-08-04 14:53:26 -070014249 out.writeInt(mRpmStats.size());
14250 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
14251 Timer rpmt = ent.getValue();
14252 if (rpmt != null) {
14253 out.writeInt(1);
14254 out.writeString(ent.getKey());
14255 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14256 } else {
14257 out.writeInt(0);
14258 }
14259 }
14260 out.writeInt(mScreenOffRpmStats.size());
14261 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
14262 Timer rpmt = ent.getValue();
14263 if (rpmt != null) {
14264 out.writeInt(1);
14265 out.writeString(ent.getKey());
14266 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14267 } else {
14268 out.writeInt(0);
14269 }
14270 }
14271
Evan Millarc64edde2009-04-18 12:26:32 -070014272 out.writeInt(mKernelWakelockStats.size());
14273 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
14274 Timer kwlt = ent.getValue();
14275 if (kwlt != null) {
14276 out.writeInt(1);
14277 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014278 kwlt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14279 } else {
14280 out.writeInt(0);
14281 }
14282 }
14283
14284 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014285 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
14286 SamplingTimer timer = ent.getValue();
14287 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014288 out.writeInt(1);
14289 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014290 timer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Evan Millarc64edde2009-04-18 12:26:32 -070014291 } else {
14292 out.writeInt(0);
14293 }
14294 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014295
James Carr3a226052016-07-01 14:49:52 -070014296 out.writeInt(mKernelMemoryStats.size());
14297 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
14298 Timer kmt = mKernelMemoryStats.valueAt(i);
14299 if (kmt != null) {
14300 out.writeInt(1);
14301 out.writeLong(mKernelMemoryStats.keyAt(i));
14302 kmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14303 } else {
14304 out.writeInt(0);
14305 }
14306 }
14307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014308 final int NU = mUidStats.size();
14309 out.writeInt(NU);
14310 for (int iu = 0; iu < NU; iu++) {
14311 out.writeInt(mUidStats.keyAt(iu));
14312 Uid u = mUidStats.valueAt(iu);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014313
Bookatz867c0d72017-03-07 18:23:42 -080014314 u.mOnBatteryBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatzc8c44962017-05-11 12:12:54 -070014315 u.mOnBatteryScreenOffBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatz867c0d72017-03-07 18:23:42 -080014316
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014317 if (u.mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014318 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014319 u.mWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014320 } else {
14321 out.writeInt(0);
14322 }
14323 if (u.mFullWifiLockTimer != null) {
14324 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014325 u.mFullWifiLockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014326 } else {
14327 out.writeInt(0);
14328 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070014329 if (u.mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014330 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014331 u.mWifiScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014332 } else {
14333 out.writeInt(0);
14334 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070014335 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
14336 if (u.mWifiBatchedScanTimer[i] != null) {
14337 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014338 u.mWifiBatchedScanTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Robert Greenwalta029ea12013-09-25 16:38:12 -070014339 } else {
14340 out.writeInt(0);
14341 }
14342 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014343 if (u.mWifiMulticastTimer != null) {
14344 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014345 u.mWifiMulticastTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014346 } else {
14347 out.writeInt(0);
14348 }
14349 if (u.mAudioTurnedOnTimer != null) {
14350 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014351 u.mAudioTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014352 } else {
14353 out.writeInt(0);
14354 }
14355 if (u.mVideoTurnedOnTimer != null) {
14356 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014357 u.mVideoTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014358 } else {
14359 out.writeInt(0);
14360 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014361 if (u.mFlashlightTurnedOnTimer != null) {
14362 out.writeInt(1);
14363 u.mFlashlightTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14364 } else {
14365 out.writeInt(0);
14366 }
14367 if (u.mCameraTurnedOnTimer != null) {
14368 out.writeInt(1);
14369 u.mCameraTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14370 } else {
14371 out.writeInt(0);
14372 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014373 if (u.mForegroundActivityTimer != null) {
14374 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014375 u.mForegroundActivityTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014376 } else {
14377 out.writeInt(0);
14378 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070014379 if (u.mForegroundServiceTimer != null) {
14380 out.writeInt(1);
14381 u.mForegroundServiceTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14382 } else {
14383 out.writeInt(0);
14384 }
Bookatzc8c44962017-05-11 12:12:54 -070014385 if (u.mAggregatedPartialWakelockTimer != null) {
14386 out.writeInt(1);
14387 u.mAggregatedPartialWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14388 } else {
14389 out.writeInt(0);
14390 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014391 if (u.mBluetoothScanTimer != null) {
14392 out.writeInt(1);
14393 u.mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14394 } else {
14395 out.writeInt(0);
14396 }
Bookatzb1f04f32017-05-19 13:57:32 -070014397 if (u.mBluetoothUnoptimizedScanTimer != null) {
14398 out.writeInt(1);
14399 u.mBluetoothUnoptimizedScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14400 } else {
14401 out.writeInt(0);
14402 }
Bookatz956f36bf2017-04-28 09:48:17 -070014403 if (u.mBluetoothScanResultCounter != null) {
14404 out.writeInt(1);
14405 u.mBluetoothScanResultCounter.writeSummaryFromParcelLocked(out);
14406 } else {
14407 out.writeInt(0);
14408 }
Bookatzb1f04f32017-05-19 13:57:32 -070014409 if (u.mBluetoothScanResultBgCounter != null) {
14410 out.writeInt(1);
14411 u.mBluetoothScanResultBgCounter.writeSummaryFromParcelLocked(out);
14412 } else {
14413 out.writeInt(0);
14414 }
Dianne Hackborn61659e52014-07-09 16:13:01 -070014415 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
14416 if (u.mProcessStateTimer[i] != null) {
14417 out.writeInt(1);
14418 u.mProcessStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14419 } else {
14420 out.writeInt(0);
14421 }
14422 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014423 if (u.mVibratorOnTimer != null) {
14424 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014425 u.mVibratorOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014426 } else {
14427 out.writeInt(0);
14428 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014429
Dianne Hackborn617f8772009-03-31 15:04:46 -070014430 if (u.mUserActivityCounters == null) {
14431 out.writeInt(0);
14432 } else {
14433 out.writeInt(1);
14434 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
14435 u.mUserActivityCounters[i].writeSummaryFromParcelLocked(out);
14436 }
14437 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014438
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014439 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014440 out.writeInt(0);
14441 } else {
14442 out.writeInt(1);
14443 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014444 u.mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
14445 u.mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014446 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080014447 u.mMobileRadioActiveTime.writeSummaryFromParcelLocked(out);
14448 u.mMobileRadioActiveCount.writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014449 }
14450
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014451 u.mUserCpuTime.writeSummaryFromParcelLocked(out);
14452 u.mSystemCpuTime.writeSummaryFromParcelLocked(out);
14453
Sudheer Shankaaf857412017-07-21 00:14:24 -070014454 if (u.mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -070014455 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -070014456 out.writeInt(u.mCpuClusterSpeedTimesUs.length);
14457 for (LongSamplingCounter[] cpuSpeeds : u.mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -070014458 if (cpuSpeeds != null) {
14459 out.writeInt(1);
14460 out.writeInt(cpuSpeeds.length);
14461 for (LongSamplingCounter c : cpuSpeeds) {
14462 if (c != null) {
14463 out.writeInt(1);
14464 c.writeSummaryFromParcelLocked(out);
14465 } else {
14466 out.writeInt(0);
14467 }
14468 }
14469 } else {
14470 out.writeInt(0);
14471 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014472 }
Adam Lesinski6832f392015-09-05 18:05:40 -070014473 } else {
14474 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014475 }
14476
Sudheer Shanka59f5c002017-05-15 10:57:15 -070014477 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mCpuFreqTimeMs);
14478 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mScreenOffCpuFreqTimeMs);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070014479
Mike Ma3d422c32017-10-25 11:08:57 -070014480 u.mCpuActiveTimeMs.writeSummaryFromParcelLocked(out);
14481 u.mCpuClusterTimesMs.writeSummaryToParcelLocked(out);
14482
Sudheer Shankab2f83c12017-11-13 19:25:01 -080014483 if (u.mProcStateTimeMs != null) {
14484 out.writeInt(u.mProcStateTimeMs.length);
14485 for (LongSamplingCounterArray counters : u.mProcStateTimeMs) {
14486 LongSamplingCounterArray.writeSummaryToParcelLocked(out, counters);
14487 }
14488 } else {
14489 out.writeInt(0);
14490 }
14491 if (u.mProcStateScreenOffTimeMs != null) {
14492 out.writeInt(u.mProcStateScreenOffTimeMs.length);
14493 for (LongSamplingCounterArray counters : u.mProcStateScreenOffTimeMs) {
14494 LongSamplingCounterArray.writeSummaryToParcelLocked(out, counters);
14495 }
14496 } else {
14497 out.writeInt(0);
14498 }
14499
Adam Lesinski5f056f62016-07-14 16:56:08 -070014500 if (u.mMobileRadioApWakeupCount != null) {
14501 out.writeInt(1);
14502 u.mMobileRadioApWakeupCount.writeSummaryFromParcelLocked(out);
14503 } else {
14504 out.writeInt(0);
14505 }
14506
14507 if (u.mWifiRadioApWakeupCount != null) {
14508 out.writeInt(1);
14509 u.mWifiRadioApWakeupCount.writeSummaryFromParcelLocked(out);
14510 } else {
14511 out.writeInt(0);
14512 }
14513
Dianne Hackbornd953c532014-08-16 18:17:38 -070014514 final ArrayMap<String, Uid.Wakelock> wakeStats = u.mWakelockStats.getMap();
14515 int NW = wakeStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014516 out.writeInt(NW);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014517 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014518 out.writeString(wakeStats.keyAt(iw));
14519 Uid.Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014520 if (wl.mTimerFull != null) {
14521 out.writeInt(1);
14522 wl.mTimerFull.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14523 } else {
14524 out.writeInt(0);
14525 }
14526 if (wl.mTimerPartial != null) {
14527 out.writeInt(1);
14528 wl.mTimerPartial.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14529 } else {
14530 out.writeInt(0);
14531 }
14532 if (wl.mTimerWindow != null) {
14533 out.writeInt(1);
14534 wl.mTimerWindow.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14535 } else {
14536 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014537 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070014538 if (wl.mTimerDraw != null) {
Adam Lesinski9425fe22015-06-19 12:02:13 -070014539 out.writeInt(1);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070014540 wl.mTimerDraw.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9425fe22015-06-19 12:02:13 -070014541 } else {
14542 out.writeInt(0);
14543 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014544 }
14545
Bookatz2bffb5b2017-04-13 11:59:33 -070014546 final ArrayMap<String, DualTimer> syncStats = u.mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014547 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014548 out.writeInt(NS);
14549 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014550 out.writeString(syncStats.keyAt(is));
14551 syncStats.valueAt(is).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014552 }
14553
Bookatzaa4594a2017-03-24 12:39:56 -070014554 final ArrayMap<String, DualTimer> jobStats = u.mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014555 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014556 out.writeInt(NJ);
14557 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014558 out.writeString(jobStats.keyAt(ij));
14559 jobStats.valueAt(ij).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014560 }
14561
Dianne Hackborn94326cb2017-06-28 16:17:20 -070014562 u.writeJobCompletionsToParcelLocked(out);
14563
Amith Yamasani977e11f2018-02-16 11:29:54 -080014564 u.mJobsDeferredEventCount.writeSummaryFromParcelLocked(out);
14565 u.mJobsDeferredCount.writeSummaryFromParcelLocked(out);
14566 u.mJobsFreshnessTimeMs.writeSummaryFromParcelLocked(out);
14567 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
14568 if (u.mJobsFreshnessBuckets[i] != null) {
Adam Lesinski14082082018-02-23 12:35:55 -080014569 out.writeInt(1);
Amith Yamasani977e11f2018-02-16 11:29:54 -080014570 u.mJobsFreshnessBuckets[i].writeSummaryFromParcelLocked(out);
14571 } else {
14572 out.writeInt(0);
14573 }
14574 }
14575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014576 int NSE = u.mSensorStats.size();
14577 out.writeInt(NSE);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014578 for (int ise=0; ise<NSE; ise++) {
14579 out.writeInt(u.mSensorStats.keyAt(ise));
14580 Uid.Sensor se = u.mSensorStats.valueAt(ise);
14581 if (se.mTimer != null) {
14582 out.writeInt(1);
14583 se.mTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14584 } else {
14585 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014586 }
14587 }
14588
14589 int NP = u.mProcessStats.size();
14590 out.writeInt(NP);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014591 for (int ip=0; ip<NP; ip++) {
14592 out.writeString(u.mProcessStats.keyAt(ip));
14593 Uid.Proc ps = u.mProcessStats.valueAt(ip);
14594 out.writeLong(ps.mUserTime);
14595 out.writeLong(ps.mSystemTime);
14596 out.writeLong(ps.mForegroundTime);
14597 out.writeInt(ps.mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014598 out.writeInt(ps.mNumCrashes);
14599 out.writeInt(ps.mNumAnrs);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014600 ps.writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014601 }
14602
14603 NP = u.mPackageStats.size();
14604 out.writeInt(NP);
14605 if (NP > 0) {
14606 for (Map.Entry<String, BatteryStatsImpl.Uid.Pkg> ent
14607 : u.mPackageStats.entrySet()) {
14608 out.writeString(ent.getKey());
14609 Uid.Pkg ps = ent.getValue();
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014610 final int NWA = ps.mWakeupAlarms.size();
14611 out.writeInt(NWA);
14612 for (int iwa=0; iwa<NWA; iwa++) {
14613 out.writeString(ps.mWakeupAlarms.keyAt(iwa));
14614 ps.mWakeupAlarms.valueAt(iwa).writeSummaryFromParcelLocked(out);
14615 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014616 NS = ps.mServiceStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014617 out.writeInt(NS);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014618 for (int is=0; is<NS; is++) {
14619 out.writeString(ps.mServiceStats.keyAt(is));
14620 BatteryStatsImpl.Uid.Pkg.Serv ss = ps.mServiceStats.valueAt(is);
14621 long time = ss.getStartTimeToNowLocked(
14622 mOnBatteryTimeBase.getUptime(NOW_SYS));
14623 out.writeLong(time);
14624 out.writeInt(ss.mStarts);
14625 out.writeInt(ss.mLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014626 }
14627 }
14628 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014629 }
14630 }
14631
14632 public void readFromParcel(Parcel in) {
14633 readFromParcelLocked(in);
14634 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014635
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014636 void readFromParcelLocked(Parcel in) {
14637 int magic = in.readInt();
14638 if (magic != MAGIC) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014639 throw new ParcelFormatException("Bad magic number: #" + Integer.toHexString(magic));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014640 }
14641
Dianne Hackbornae384452011-06-28 12:33:48 -070014642 readHistory(in, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014643
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014644 mStartCount = in.readInt();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080014645 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014646 mStartPlatformVersion = in.readString();
14647 mEndPlatformVersion = in.readString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014648 mUptime = in.readLong();
14649 mUptimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014650 mRealtime = in.readLong();
14651 mRealtimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014652 mOnBattery = in.readInt() != 0;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014653 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070014654 mMinLearnedBatteryCapacity = in.readInt();
14655 mMaxLearnedBatteryCapacity = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014656 mOnBatteryInternal = false; // we are no longer really running.
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014657 mOnBatteryTimeBase.readFromParcel(in);
14658 mOnBatteryScreenOffTimeBase.readFromParcel(in);
14659
Jeff Browne95c3cd2014-05-02 16:59:26 -070014660 mScreenState = Display.STATE_UNKNOWN;
Joe Onoratoabded112016-02-08 16:49:39 -080014661 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070014662 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014663 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014664 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
14665 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014666 }
Dianne Hackborn29325132014-05-21 15:01:03 -070014667 mInteractive = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014668 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014669 mPhoneOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014670 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
14671 mOnBatteryTimeBase, in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014672 mLongestLightIdleTime = in.readLong();
14673 mLongestFullIdleTime = in.readLong();
Joe Onoratoabded112016-02-08 16:49:39 -080014674 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -14, null,
14675 mOnBatteryTimeBase, in);
14676 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -11, null,
14677 mOnBatteryTimeBase, in);
14678 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null,
14679 mOnBatteryTimeBase, in);
14680 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase, in);
14681 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014682 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014683 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014684 null, mOnBatteryTimeBase, in);
14685 }
Joe Onoratoabded112016-02-08 16:49:39 -080014686 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
14687 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014688 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014689 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014690 null, mOnBatteryTimeBase, in);
14691 }
14692 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
14693 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
14694 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
14695 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014696 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Joe Onoratoabded112016-02-08 16:49:39 -080014697 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null,
14698 mOnBatteryTimeBase, in);
Kweku Adams87b19ec2017-10-09 12:40:03 -070014699 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
Joe Onoratoabded112016-02-08 16:49:39 -080014700 mOnBatteryTimeBase, in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014701 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014702 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
14703 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase, in);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014704 mWifiMulticastWakelockTimer = new StopwatchTimer(mClocks, null, -4, null,
14705 mOnBatteryTimeBase, in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070014706 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014707 mWifiOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014708 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014709 mGlobalWifiRunning = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014710 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null,
14711 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014712 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014713 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014714 null, mOnBatteryTimeBase, in);
14715 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014716 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014717 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070014718 null, mOnBatteryTimeBase, in);
14719 }
14720 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014721 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070014722 null, mOnBatteryTimeBase, in);
14723 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014724 mWifiActiveTimer = new StopwatchTimer(mClocks, null, -900, null,
14725 mOnBatteryTimeBase, in);
14726 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14727 NUM_WIFI_TX_LEVELS, in);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014728 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14729 mGpsSignalQualityTimer[i] = new StopwatchTimer(mClocks, null, -1000-i,
14730 null, mOnBatteryTimeBase, in);
14731 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014732 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14733 NUM_BT_TX_LEVELS, in);
14734 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14735 ModemActivityInfo.TX_POWER_LEVELS, in);
14736 mHasWifiReporting = in.readInt() != 0;
14737 mHasBluetoothReporting = in.readInt() != 0;
14738 mHasModemReporting = in.readInt() != 0;
14739
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014740 mNumConnectivityChange = in.readInt();
14741 mLoadedNumConnectivityChange = in.readInt();
14742 mUnpluggedNumConnectivityChange = in.readInt();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014743 mAudioOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014744 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014745 mVideoOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014746 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014747 mFlashlightOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014748 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014749 mCameraOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014750 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014751 mBluetoothScanNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014752 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase, in);
Siddharth Rayf5e796a2018-01-22 18:18:17 -080014753 mIsCellularTxPowerHigh = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014754 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014755 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070014756 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014757 mCurrentBatteryLevel = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014758 mLowDischargeAmountSinceCharge = in.readInt();
14759 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014760 mDischargeAmountScreenOn = in.readInt();
14761 mDischargeAmountScreenOnSinceCharge = in.readInt();
14762 mDischargeAmountScreenOff = in.readInt();
14763 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070014764 mDischargeAmountScreenDoze = in.readInt();
14765 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014766 mDischargeStepTracker.readFromParcel(in);
14767 mChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070014768 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070014769 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase, in);
14770 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Ma15313c92017-11-15 17:58:21 -080014771 mDischargeLightDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
14772 mDischargeDeepDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014773 mLastWriteTime = in.readLong();
14774
Bookatz50df7112017-08-04 14:53:26 -070014775 mRpmStats.clear();
14776 int NRPMS = in.readInt();
14777 for (int irpm = 0; irpm < NRPMS; irpm++) {
14778 if (in.readInt() != 0) {
14779 String rpmName = in.readString();
14780 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
14781 mRpmStats.put(rpmName, rpmt);
14782 }
14783 }
14784 mScreenOffRpmStats.clear();
14785 int NSORPMS = in.readInt();
14786 for (int irpm = 0; irpm < NSORPMS; irpm++) {
14787 if (in.readInt() != 0) {
14788 String rpmName = in.readString();
14789 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
14790 mScreenOffRpmStats.put(rpmName, rpmt);
14791 }
14792 }
14793
Evan Millarc64edde2009-04-18 12:26:32 -070014794 mKernelWakelockStats.clear();
14795 int NKW = in.readInt();
14796 for (int ikw = 0; ikw < NKW; ikw++) {
14797 if (in.readInt() != 0) {
14798 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080014799 SamplingTimer kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -070014800 mKernelWakelockStats.put(wakelockName, kwlt);
14801 }
14802 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014803
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014804 mWakeupReasonStats.clear();
14805 int NWR = in.readInt();
14806 for (int iwr = 0; iwr < NWR; iwr++) {
14807 if (in.readInt() != 0) {
14808 String reasonName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080014809 SamplingTimer timer = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014810 mWakeupReasonStats.put(reasonName, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014811 }
14812 }
14813
James Carr3a226052016-07-01 14:49:52 -070014814 mKernelMemoryStats.clear();
14815 int nmt = in.readInt();
14816 for (int imt = 0; imt < nmt; imt++) {
14817 if (in.readInt() != 0) {
14818 Long bucket = in.readLong();
14819 SamplingTimer kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
14820 mKernelMemoryStats.put(bucket, kmt);
14821 }
14822 }
14823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014824 mPartialTimers.clear();
14825 mFullTimers.clear();
14826 mWindowTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014827 mWifiRunningTimers.clear();
14828 mFullWifiLockTimers.clear();
Nick Pelly6ccaa542012-06-15 15:22:47 -070014829 mWifiScanTimers.clear();
Robert Greenwalta029ea12013-09-25 16:38:12 -070014830 mWifiBatchedScanTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014831 mWifiMulticastTimers.clear();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014832 mAudioTurnedOnTimers.clear();
14833 mVideoTurnedOnTimers.clear();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014834 mFlashlightTurnedOnTimers.clear();
14835 mCameraTurnedOnTimers.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014836
14837 int numUids = in.readInt();
14838 mUidStats.clear();
14839 for (int i = 0; i < numUids; i++) {
14840 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080014841 Uid u = new Uid(this, uid);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014842 u.readFromParcelLocked(mOnBatteryTimeBase, mOnBatteryScreenOffTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014843 mUidStats.append(uid, u);
14844 }
14845 }
14846
14847 public void writeToParcel(Parcel out, int flags) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014848 writeToParcelLocked(out, true, flags);
14849 }
14850
14851 public void writeToParcelWithoutUids(Parcel out, int flags) {
14852 writeToParcelLocked(out, false, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014853 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014854
14855 @SuppressWarnings("unused")
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014856 void writeToParcelLocked(Parcel out, boolean inclUids, int flags) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014857 // Need to update with current kernel wake lock counts.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080014858 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014859
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014860 // Pull the clock time. This may update the time and make a new history entry
14861 // if we had originally pulled a time before the RTC was set.
14862 long startClockTime = getStartClockTime();
14863
Joe Onoratoabded112016-02-08 16:49:39 -080014864 final long uSecUptime = mClocks.uptimeMillis() * 1000;
14865 final long uSecRealtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014866 final long batteryRealtime = mOnBatteryTimeBase.getRealtime(uSecRealtime);
14867 final long batteryScreenOffRealtime = mOnBatteryScreenOffTimeBase.getRealtime(uSecRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014868
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014869 out.writeInt(MAGIC);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014870
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070014871 writeHistory(out, true, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014872
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014873 out.writeInt(mStartCount);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014874 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014875 out.writeString(mStartPlatformVersion);
14876 out.writeString(mEndPlatformVersion);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014877 out.writeLong(mUptime);
14878 out.writeLong(mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014879 out.writeLong(mRealtime);
14880 out.writeLong(mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014881 out.writeInt(mOnBattery ? 1 : 0);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014882 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070014883 out.writeInt(mMinLearnedBatteryCapacity);
14884 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014885 mOnBatteryTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
14886 mOnBatteryScreenOffTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
14887
14888 mScreenOnTimer.writeToParcel(out, uSecRealtime);
Mike Mac2f518a2017-09-19 16:06:03 -070014889 mScreenDozeTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014890 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
14891 mScreenBrightnessTimer[i].writeToParcel(out, uSecRealtime);
14892 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070014893 mInteractiveTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070014894 mPowerSaveModeEnabledTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014895 out.writeLong(mLongestLightIdleTime);
14896 out.writeLong(mLongestFullIdleTime);
14897 mDeviceIdleModeLightTimer.writeToParcel(out, uSecRealtime);
14898 mDeviceIdleModeFullTimer.writeToParcel(out, uSecRealtime);
14899 mDeviceLightIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014900 mDeviceIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014901 mPhoneOnTimer.writeToParcel(out, uSecRealtime);
14902 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
14903 mPhoneSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
14904 }
14905 mPhoneSignalScanningTimer.writeToParcel(out, uSecRealtime);
14906 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
14907 mPhoneDataConnectionsTimer[i].writeToParcel(out, uSecRealtime);
14908 }
14909 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
14910 mNetworkByteActivityCounters[i].writeToParcel(out);
14911 mNetworkPacketActivityCounters[i].writeToParcel(out);
14912 }
14913 mMobileRadioActiveTimer.writeToParcel(out, uSecRealtime);
14914 mMobileRadioActivePerAppTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014915 mMobileRadioActiveAdjustedTime.writeToParcel(out);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014916 mMobileRadioActiveUnknownTime.writeToParcel(out);
14917 mMobileRadioActiveUnknownCount.writeToParcel(out);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014918 mWifiMulticastWakelockTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014919 mWifiOnTimer.writeToParcel(out, uSecRealtime);
14920 mGlobalWifiRunningTimer.writeToParcel(out, uSecRealtime);
14921 for (int i=0; i<NUM_WIFI_STATES; i++) {
14922 mWifiStateTimer[i].writeToParcel(out, uSecRealtime);
14923 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014924 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
14925 mWifiSupplStateTimer[i].writeToParcel(out, uSecRealtime);
14926 }
14927 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
14928 mWifiSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
14929 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014930 mWifiActiveTimer.writeToParcel(out, uSecRealtime);
14931 mWifiActivity.writeToParcel(out, 0);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014932 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14933 mGpsSignalQualityTimer[i].writeToParcel(out, uSecRealtime);
14934 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014935 mBluetoothActivity.writeToParcel(out, 0);
14936 mModemActivity.writeToParcel(out, 0);
14937 out.writeInt(mHasWifiReporting ? 1 : 0);
14938 out.writeInt(mHasBluetoothReporting ? 1 : 0);
14939 out.writeInt(mHasModemReporting ? 1 : 0);
14940
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014941 out.writeInt(mNumConnectivityChange);
14942 out.writeInt(mLoadedNumConnectivityChange);
14943 out.writeInt(mUnpluggedNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070014944 mFlashlightOnTimer.writeToParcel(out, uSecRealtime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014945 mCameraOnTimer.writeToParcel(out, uSecRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014946 mBluetoothScanTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014947 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014948 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070014949 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014950 out.writeInt(mCurrentBatteryLevel);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014951 out.writeInt(mLowDischargeAmountSinceCharge);
14952 out.writeInt(mHighDischargeAmountSinceCharge);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014953 out.writeInt(mDischargeAmountScreenOn);
14954 out.writeInt(mDischargeAmountScreenOnSinceCharge);
14955 out.writeInt(mDischargeAmountScreenOff);
14956 out.writeInt(mDischargeAmountScreenOffSinceCharge);
Mike Mac2f518a2017-09-19 16:06:03 -070014957 out.writeInt(mDischargeAmountScreenDoze);
14958 out.writeInt(mDischargeAmountScreenDozeSinceCharge);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014959 mDischargeStepTracker.writeToParcel(out);
14960 mChargeStepTracker.writeToParcel(out);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070014961 mDischargeCounter.writeToParcel(out);
14962 mDischargeScreenOffCounter.writeToParcel(out);
Mike Mac2f518a2017-09-19 16:06:03 -070014963 mDischargeScreenDozeCounter.writeToParcel(out);
Mike Ma15313c92017-11-15 17:58:21 -080014964 mDischargeLightDozeCounter.writeToParcel(out);
14965 mDischargeDeepDozeCounter.writeToParcel(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014966 out.writeLong(mLastWriteTime);
14967
Bookatz50df7112017-08-04 14:53:26 -070014968 out.writeInt(mRpmStats.size());
14969 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
14970 SamplingTimer rpmt = ent.getValue();
14971 if (rpmt != null) {
14972 out.writeInt(1);
14973 out.writeString(ent.getKey());
14974 rpmt.writeToParcel(out, uSecRealtime);
14975 } else {
14976 out.writeInt(0);
14977 }
14978 }
14979 out.writeInt(mScreenOffRpmStats.size());
14980 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
14981 SamplingTimer rpmt = ent.getValue();
14982 if (rpmt != null) {
14983 out.writeInt(1);
14984 out.writeString(ent.getKey());
14985 rpmt.writeToParcel(out, uSecRealtime);
14986 } else {
14987 out.writeInt(0);
14988 }
14989 }
14990
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014991 if (inclUids) {
14992 out.writeInt(mKernelWakelockStats.size());
14993 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
14994 SamplingTimer kwlt = ent.getValue();
14995 if (kwlt != null) {
14996 out.writeInt(1);
14997 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014998 kwlt.writeToParcel(out, uSecRealtime);
14999 } else {
15000 out.writeInt(0);
15001 }
15002 }
15003 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070015004 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
15005 SamplingTimer timer = ent.getValue();
15006 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070015007 out.writeInt(1);
15008 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070015009 timer.writeToParcel(out, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015010 } else {
15011 out.writeInt(0);
15012 }
Evan Millarc64edde2009-04-18 12:26:32 -070015013 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015014 } else {
Bookatzba78b2b2017-10-10 11:06:33 -070015015 out.writeInt(0);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015016 out.writeInt(0);
Evan Millarc64edde2009-04-18 12:26:32 -070015017 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070015018
James Carr3a226052016-07-01 14:49:52 -070015019 out.writeInt(mKernelMemoryStats.size());
15020 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
15021 SamplingTimer kmt = mKernelMemoryStats.valueAt(i);
15022 if (kmt != null) {
15023 out.writeInt(1);
15024 out.writeLong(mKernelMemoryStats.keyAt(i));
15025 kmt.writeToParcel(out, uSecRealtime);
15026 } else {
15027 out.writeInt(0);
15028 }
15029 }
15030
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015031 if (inclUids) {
15032 int size = mUidStats.size();
15033 out.writeInt(size);
15034 for (int i = 0; i < size; i++) {
15035 out.writeInt(mUidStats.keyAt(i));
15036 Uid uid = mUidStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015037
Bookatz867c0d72017-03-07 18:23:42 -080015038 uid.writeToParcelLocked(out, uSecUptime, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015039 }
15040 } else {
15041 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015042 }
15043 }
15044
15045 public static final Parcelable.Creator<BatteryStatsImpl> CREATOR =
15046 new Parcelable.Creator<BatteryStatsImpl>() {
15047 public BatteryStatsImpl createFromParcel(Parcel in) {
15048 return new BatteryStatsImpl(in);
15049 }
15050
15051 public BatteryStatsImpl[] newArray(int size) {
15052 return new BatteryStatsImpl[size];
15053 }
15054 };
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070015055
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070015056 public void prepareForDumpLocked() {
15057 // Need to retrieve current kernel wake lock stats before printing.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080015058 pullPendingStateUpdatesLocked();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070015059
15060 // Pull the clock time. This may update the time and make a new history entry
15061 // if we had originally pulled a time before the RTC was set.
15062 getStartClockTime();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070015063 }
15064
Dianne Hackbornc51cf032014-03-02 19:08:15 -080015065 public void dumpLocked(Context context, PrintWriter pw, int flags, int reqUid, long histStart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015066 if (DEBUG) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080015067 pw.println("mOnBatteryTimeBase:");
15068 mOnBatteryTimeBase.dump(pw, " ");
15069 pw.println("mOnBatteryScreenOffTimeBase:");
15070 mOnBatteryScreenOffTimeBase.dump(pw, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015071 Printer pr = new PrintWriterPrinter(pw);
Mike Mac2f518a2017-09-19 16:06:03 -070015072 pr.println("*** Screen on timer:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015073 mScreenOnTimer.logState(pr, " ");
Mike Mac2f518a2017-09-19 16:06:03 -070015074 pr.println("*** Screen doze timer:");
15075 mScreenDozeTimer.logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070015076 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015077 pr.println("*** Screen brightness #" + i + ":");
15078 mScreenBrightnessTimer[i].logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070015079 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070015080 pr.println("*** Interactive timer:");
15081 mInteractiveTimer.logState(pr, " ");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070015082 pr.println("*** Power save mode timer:");
15083 mPowerSaveModeEnabledTimer.logState(pr, " ");
Dianne Hackborn08c47a52015-10-15 12:38:14 -070015084 pr.println("*** Device idle mode light timer:");
15085 mDeviceIdleModeLightTimer.logState(pr, " ");
15086 pr.println("*** Device idle mode full timer:");
15087 mDeviceIdleModeFullTimer.logState(pr, " ");
15088 pr.println("*** Device light idling timer:");
15089 mDeviceLightIdlingTimer.logState(pr, " ");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070015090 pr.println("*** Device idling timer:");
15091 mDeviceIdlingTimer.logState(pr, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015092 pr.println("*** Phone timer:");
15093 mPhoneOnTimer.logState(pr, " ");
Wink Saville52840902011-02-18 12:40:47 -080015094 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3251b902014-06-20 14:40:53 -070015095 pr.println("*** Phone signal strength #" + i + ":");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015096 mPhoneSignalStrengthsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070015097 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070015098 pr.println("*** Signal scanning :");
15099 mPhoneSignalScanningTimer.logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070015100 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015101 pr.println("*** Data connection type #" + i + ":");
15102 mPhoneDataConnectionsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070015103 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070015104 pr.println("*** mMobileRadioPowerState=" + mMobileRadioPowerState);
Dianne Hackborne13c4c02014-02-11 17:18:35 -080015105 pr.println("*** Mobile network active timer:");
15106 mMobileRadioActiveTimer.logState(pr, " ");
Dianne Hackborna1bd7922014-03-21 11:07:11 -070015107 pr.println("*** Mobile network active adjusted timer:");
15108 mMobileRadioActiveAdjustedTime.logState(pr, " ");
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080015109 pr.println("*** Wifi Multicast WakeLock Timer:");
15110 mWifiMulticastWakelockTimer.logState(pr, " ");
Dianne Hackborn0c820db2015-04-14 17:47:34 -070015111 pr.println("*** mWifiRadioPowerState=" + mWifiRadioPowerState);
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015112 pr.println("*** Wifi timer:");
15113 mWifiOnTimer.logState(pr, " ");
15114 pr.println("*** WifiRunning timer:");
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070015115 mGlobalWifiRunningTimer.logState(pr, " ");
Dianne Hackbornca1bf212014-02-14 14:18:36 -080015116 for (int i=0; i<NUM_WIFI_STATES; i++) {
15117 pr.println("*** Wifi state #" + i + ":");
15118 mWifiStateTimer[i].logState(pr, " ");
15119 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070015120 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
15121 pr.println("*** Wifi suppl state #" + i + ":");
15122 mWifiSupplStateTimer[i].logState(pr, " ");
15123 }
15124 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
15125 pr.println("*** Wifi signal strength #" + i + ":");
15126 mWifiSignalStrengthsTimer[i].logState(pr, " ");
15127 }
Siddharth Ray78ccaf52017-12-23 16:16:21 -080015128 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
15129 pr.println("*** GPS signal quality #" + i + ":");
15130 mGpsSignalQualityTimer[i].logState(pr, " ");
15131 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -070015132 pr.println("*** Flashlight timer:");
15133 mFlashlightOnTimer.logState(pr, " ");
Ruben Brunk6d2c3632015-05-26 17:32:16 -070015134 pr.println("*** Camera timer:");
15135 mCameraOnTimer.logState(pr, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015136 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -080015137 super.dumpLocked(context, pw, flags, reqUid, histStart);
Sudheer Shankac20379e2018-02-15 00:06:21 -080015138 pw.print("Total cpu time reads: ");
Mike Ma234d1822018-03-13 18:53:21 -070015139 pw.println(mNumSingleUidCpuTimeReads);
Sudheer Shankac20379e2018-02-15 00:06:21 -080015140 pw.print("Batched cpu time reads: ");
Mike Ma234d1822018-03-13 18:53:21 -070015141 pw.println(mNumBatchedSingleUidCpuTimeReads);
Sudheer Shankac20379e2018-02-15 00:06:21 -080015142 pw.print("Batching Duration (min): ");
15143 pw.println((mClocks.uptimeMillis() - mCpuTimeReadsTrackingStartTime) / (60 * 1000));
Mike Ma234d1822018-03-13 18:53:21 -070015144 pw.print("All UID cpu time reads since the later of device start or stats reset: ");
15145 pw.println(mNumAllUidCpuTimeReads);
15146 pw.print("UIDs removed since the later of device start or stats reset: ");
15147 pw.println(mNumUidsRemoved);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015149}