blob: 9993a76ec18ae00020cb77fe9ffdd56e67074b1b [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;
Tej Singh33a412b2018-03-16 18:43:59 -070022import android.app.job.JobProtoEnums;
Adam Lesinski33dac552015-03-09 15:24:48 -070023import android.bluetooth.BluetoothActivityEnergyInfo;
Adam Lesinski50e47602015-12-04 17:04:54 -080024import android.bluetooth.UidTraffic;
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;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080028import android.database.ContentObserver;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070029import android.net.ConnectivityManager;
30import android.net.NetworkStats;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080031import android.net.Uri;
Adam Lesinski33dac552015-03-09 15:24:48 -070032import android.net.wifi.WifiActivityEnergyInfo;
Dianne Hackborn3251b902014-06-20 14:40:53 -070033import android.net.wifi.WifiManager;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070034import android.os.BatteryManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.os.BatteryStats;
Dianne Hackborncd0e3352014-08-07 17:08:09 -070036import android.os.Build;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070037import android.os.FileUtils;
Dianne Hackborn0d903a82010-09-07 23:51:03 -070038import android.os.Handler;
Adam Lesinskie1f480d2017-02-15 18:51:23 -080039import android.os.IBatteryPropertiesRegistrar;
Jeff Brown6f357d32014-01-15 20:40:55 -080040import android.os.Looper;
Dianne Hackborn0d903a82010-09-07 23:51:03 -070041import android.os.Message;
Bookatz1a1b0462018-01-12 11:47:03 -080042import android.os.OsProtoEnums;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.os.Parcel;
44import android.os.ParcelFormatException;
45import android.os.Parcelable;
Bookatz1a1b0462018-01-12 11:47:03 -080046import android.os.PowerManager;
Evan Millarc64edde2009-04-18 12:26:32 -070047import android.os.Process;
Adam Lesinskie1f480d2017-02-15 18:51:23 -080048import android.os.RemoteException;
49import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.os.SystemClock;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070051import android.os.UserHandle;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070052import android.os.WorkSource;
Narayan Kamath81822022017-12-08 11:56:01 +000053import android.os.WorkSource.WorkChain;
Mike Ma234d1822018-03-13 18:53:21 -070054import android.os.connectivity.CellularBatteryStats;
55import android.os.connectivity.GpsBatteryStats;
56import android.os.connectivity.WifiBatteryStats;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080057import android.provider.Settings;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070058import android.telephony.DataConnectionRealTimeInfo;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080059import android.telephony.ModemActivityInfo;
Amith Yamasanif37447b2009-10-08 18:28:01 -070060import android.telephony.ServiceState;
Wink Savillee9b06d72009-05-18 21:47:50 -070061import android.telephony.SignalStrength;
Dianne Hackborn627bba72009-03-24 22:32:56 -070062import android.telephony.TelephonyManager;
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -070063import android.text.TextUtils;
Dianne Hackborn61659e52014-07-09 16:13:01 -070064import android.util.ArrayMap;
Sudheer Shankab2f83c12017-11-13 19:25:01 -080065import android.util.IntArray;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080066import android.util.KeyValueListParser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.util.Log;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070068import android.util.LogWriter;
James Carr3a226052016-07-01 14:49:52 -070069import android.util.LongSparseArray;
70import android.util.LongSparseLongArray;
Dianne Hackbornd953c532014-08-16 18:17:38 -070071import android.util.MutableInt;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070072import android.util.Pools;
Dianne Hackborn1d442e02009-04-20 18:14:05 -070073import android.util.PrintWriterPrinter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074import android.util.Printer;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070075import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.util.SparseArray;
Dianne Hackborn099bc622014-01-22 13:39:16 -080077import android.util.SparseIntArray;
Adam Lesinskie08af192015-03-25 16:42:59 -070078import android.util.SparseLongArray;
Bookatzc1a050a2017-10-10 15:49:28 -070079import android.util.StatsLog;
Dianne Hackbornae384452011-06-28 12:33:48 -070080import android.util.TimeUtils;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080081import android.util.Xml;
Jeff Browne95c3cd2014-05-02 16:59:26 -070082import android.view.Display;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083
Adam Lesinski14ae39a2017-05-26 11:50:40 -070084import com.android.internal.annotations.GuardedBy;
Adam Lesinski98f0d462016-04-19 16:46:20 -070085import com.android.internal.annotations.VisibleForTesting;
Siddharth Ray78ccaf52017-12-23 16:16:21 -080086import com.android.internal.location.gnssmetrics.GnssMetrics;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070087import com.android.internal.net.NetworkStatsFactory;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080088import com.android.internal.util.ArrayUtils;
Dianne Hackborn8c841092013-06-24 13:46:13 -070089import com.android.internal.util.FastPrintWriter;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080090import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070091import com.android.internal.util.JournaledFile;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080092import com.android.internal.util.XmlUtils;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070093
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070094import libcore.util.EmptyArray;
Mike Ma234d1822018-03-13 18:53:21 -070095
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080096import org.xmlpull.v1.XmlPullParser;
97import org.xmlpull.v1.XmlPullParserException;
98import org.xmlpull.v1.XmlSerializer;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070099
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800100import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101import java.io.File;
102import java.io.FileInputStream;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800103import java.io.FileNotFoundException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104import java.io.FileOutputStream;
105import java.io.IOException;
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700106import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100107import java.nio.charset.StandardCharsets;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108import java.util.ArrayList;
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700109import java.util.Arrays;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800110import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111import java.util.HashMap;
Evan Millarc64edde2009-04-18 12:26:32 -0700112import java.util.Iterator;
Mike Ma234d1822018-03-13 18:53:21 -0700113import java.util.LinkedList;
114import java.util.List;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115import java.util.Map;
Mike Ma234d1822018-03-13 18:53:21 -0700116import java.util.Queue;
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700117import java.util.concurrent.Future;
Christopher Tate4cee7252010-03-19 14:50:40 -0700118import java.util.concurrent.atomic.AtomicInteger;
Dianne Hackbornce2ef762010-09-20 11:39:14 -0700119import java.util.concurrent.locks.ReentrantLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120
121/**
122 * All information we are collecting about things that can happen that impact
123 * battery life. All times are represented in microseconds except where indicated
124 * otherwise.
125 */
Joe Onoratoabded112016-02-08 16:49:39 -0800126public class BatteryStatsImpl extends BatteryStats {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127 private static final String TAG = "BatteryStatsImpl";
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800128 private static final boolean DEBUG = false;
Adam Lesinskia7c90c82015-06-18 14:52:24 -0700129 public static final boolean DEBUG_ENERGY = false;
Adam Lesinski50e47602015-12-04 17:04:54 -0800130 private static final boolean DEBUG_ENERGY_CPU = DEBUG_ENERGY;
James Carr3a226052016-07-01 14:49:52 -0700131 private static final boolean DEBUG_MEMORY = false;
Dianne Hackborn32907cf2010-06-10 17:50:20 -0700132 private static final boolean DEBUG_HISTORY = false;
Dianne Hackborne8c88e62011-08-17 19:09:09 -0700133 private static final boolean USE_OLD_HISTORY = false; // for debugging.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700134
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700135 // TODO: remove "tcp" from network methods, since we measure total stats.
136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137 // In-memory Parcel magic number, used to detect attempts to unmarshall bad data
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700138 private static final int MAGIC = 0xBA757475; // 'BATSTATS'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139
140 // Current on-disk Parcel version
Mike Ma561a8d92018-03-20 18:24:05 -0700141 private static final int VERSION = 177 + (USE_OLD_HISTORY ? 1000 : 0);
Amith Yamasanie43530a2009-08-21 13:11:37 -0700142
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700143 // Maximum number of items we will record in the history.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100144 private static final int MAX_HISTORY_ITEMS;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700145
Dianne Hackbornf47d8f22010-10-08 10:46:55 -0700146 // No, really, THIS is the maximum number of items we will record in the history.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100147 private static final int MAX_MAX_HISTORY_ITEMS;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -0700148
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800149 // The maximum number of names wakelocks we will keep track of
150 // per uid; once the limit is reached, we batch the remaining wakelocks
151 // in to one common name.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100152 private static final int MAX_WAKELOCKS_PER_UID;
153
154 static final int MAX_HISTORY_BUFFER; // 256KB
155 static final int MAX_MAX_HISTORY_BUFFER; // 320KB
156
157 static {
158 if (ActivityManager.isLowRamDeviceStatic()) {
159 MAX_HISTORY_ITEMS = 800;
160 MAX_MAX_HISTORY_ITEMS = 1200;
161 MAX_WAKELOCKS_PER_UID = 40;
162 MAX_HISTORY_BUFFER = 96*1024; // 96KB
163 MAX_MAX_HISTORY_BUFFER = 128*1024; // 128KB
164 } else {
Makoto Onuki44d64602018-01-18 08:44:28 -0800165 MAX_HISTORY_ITEMS = 4000;
166 MAX_MAX_HISTORY_ITEMS = 6000;
167 MAX_WAKELOCKS_PER_UID = 200;
168 MAX_HISTORY_BUFFER = 512*1024; // 512KB
169 MAX_MAX_HISTORY_BUFFER = 640*1024; // 640KB
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100170 }
171 }
Dianne Hackbornc24ab862011-10-18 15:55:03 -0700172
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800173 // Number of transmit power states the Wifi controller can be in.
174 private static final int NUM_WIFI_TX_LEVELS = 1;
175
176 // Number of transmit power states the Bluetooth controller can be in.
177 private static final int NUM_BT_TX_LEVELS = 1;
178
Sudheer Shanka38383232017-07-25 09:55:03 -0700179 /**
180 * Holding a wakelock costs more than just using the cpu.
181 * Currently, we assign only half the cpu time to an app that is running but
182 * not holding a wakelock. The apps holding wakelocks get the rest of the blame.
183 * If no app is holding a wakelock, then the distribution is normal.
184 */
185 @VisibleForTesting
186 public static final int WAKE_LOCK_WEIGHT = 50;
187
Joe Onoratoabded112016-02-08 16:49:39 -0800188 protected Clocks mClocks;
189
Dianne Hackborn1afd1c92010-03-18 22:47:17 -0700190 private final JournaledFile mFile;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700191 public final AtomicFile mCheckinFile;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800192 public final AtomicFile mDailyFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193
Sudheer Shankac57729a2018-02-09 15:44:42 -0800194 static final int MSG_REPORT_CPU_UPDATE_NEEDED = 1;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700195 static final int MSG_REPORT_POWER_CHANGE = 2;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700196 static final int MSG_REPORT_CHARGING = 3;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700197 static final long DELAY_UPDATE_WAKELOCKS = 5*1000;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700198
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700199 private final KernelWakelockReader mKernelWakelockReader = new KernelWakelockReader();
200 private final KernelWakelockStats mTmpWakelockStats = new KernelWakelockStats();
201
Sudheer Shanka38383232017-07-25 09:55:03 -0700202 @VisibleForTesting
203 protected KernelUidCpuTimeReader mKernelUidCpuTimeReader = new KernelUidCpuTimeReader();
204 @VisibleForTesting
205 protected KernelCpuSpeedReader[] mKernelCpuSpeedReaders;
206 @VisibleForTesting
207 protected KernelUidCpuFreqTimeReader mKernelUidCpuFreqTimeReader =
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700208 new KernelUidCpuFreqTimeReader();
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800209 @VisibleForTesting
Mike Ma3d422c32017-10-25 11:08:57 -0700210 protected KernelUidCpuActiveTimeReader mKernelUidCpuActiveTimeReader =
211 new KernelUidCpuActiveTimeReader();
212 @VisibleForTesting
213 protected KernelUidCpuClusterTimeReader mKernelUidCpuClusterTimeReader =
214 new KernelUidCpuClusterTimeReader();
215 @VisibleForTesting
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800216 protected KernelSingleUidTimeReader mKernelSingleUidTimeReader;
Adam Lesinski06af1fa2015-05-05 17:35:35 -0700217
James Carr3a226052016-07-01 14:49:52 -0700218 private final KernelMemoryBandwidthStats mKernelMemoryBandwidthStats
219 = new KernelMemoryBandwidthStats();
220 private final LongSparseArray<SamplingTimer> mKernelMemoryStats = new LongSparseArray<>();
221 public LongSparseArray<SamplingTimer> getKernelMemoryStats() {
222 return mKernelMemoryStats;
223 }
224
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800225 @GuardedBy("this")
226 public boolean mPerProcStateCpuTimesAvailable = true;
227
228 /**
229 * Uids for which per-procstate cpu times need to be updated.
230 *
231 * Contains uid -> procState mappings.
232 */
233 @GuardedBy("this")
234 @VisibleForTesting
235 protected final SparseIntArray mPendingUids = new SparseIntArray();
236
Sudheer Shankac20379e2018-02-15 00:06:21 -0800237 @GuardedBy("this")
Mike Ma234d1822018-03-13 18:53:21 -0700238 private long mNumSingleUidCpuTimeReads;
Sudheer Shankac20379e2018-02-15 00:06:21 -0800239 @GuardedBy("this")
Mike Ma234d1822018-03-13 18:53:21 -0700240 private long mNumBatchedSingleUidCpuTimeReads;
Sudheer Shankac20379e2018-02-15 00:06:21 -0800241 @GuardedBy("this")
242 private long mCpuTimeReadsTrackingStartTime = SystemClock.uptimeMillis();
Mike Ma234d1822018-03-13 18:53:21 -0700243 @GuardedBy("this")
244 private int mNumUidsRemoved;
245 @GuardedBy("this")
246 private int mNumAllUidCpuTimeReads;
Sudheer Shankac20379e2018-02-15 00:06:21 -0800247
Bookatz0b8a0502017-09-13 11:51:52 -0700248 /** Container for Resource Power Manager stats. Updated by updateRpmStatsLocked. */
Bookatz50df7112017-08-04 14:53:26 -0700249 private final RpmStats mTmpRpmStats = new RpmStats();
Bookatz0b8a0502017-09-13 11:51:52 -0700250 /** The soonest the RPM stats can be updated after it was last updated. */
251 private static final long RPM_STATS_UPDATE_FREQ_MS = 1000;
252 /** Last time that RPM stats were updated by updateRpmStatsLocked. */
253 private long mLastRpmStatsUpdateTimeMs = -RPM_STATS_UPDATE_FREQ_MS;
Mike Ma234d1822018-03-13 18:53:21 -0700254 /**
255 * Use a queue to delay removing UIDs from {@link KernelUidCpuTimeReader},
256 * {@link KernelUidCpuActiveTimeReader}, {@link KernelUidCpuClusterTimeReader},
257 * {@link KernelUidCpuFreqTimeReader} and from the Kernel.
258 *
259 * Isolated and invalid UID info must be removed to conserve memory. However, STATSD and
260 * Batterystats both need to access UID cpu time. To resolve this race condition, only
261 * Batterystats shall remove UIDs, and a delay {@link Constants#UID_REMOVE_DELAY_MS} is
262 * implemented so that STATSD can capture those UID times before they are deleted.
263 */
264 @GuardedBy("this")
265 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
266 protected Queue<UidToRemove> mPendingRemovedUids = new LinkedList<>();
267
268 @VisibleForTesting
269 public final class UidToRemove {
270 int startUid;
271 int endUid;
272 long timeAddedInQueue;
273
274 /** Remove just one UID */
275 public UidToRemove(int uid, long timestamp) {
276 this(uid, uid, timestamp);
277 }
278
279 /** Remove a range of UIDs, startUid must be smaller than endUid. */
280 public UidToRemove(int startUid, int endUid, long timestamp) {
281 this.startUid = startUid;
282 this.endUid = endUid;
283 timeAddedInQueue = timestamp;
284 }
285
286 void remove() {
287 if (startUid == endUid) {
288 mKernelUidCpuTimeReader.removeUid(startUid);
289 mKernelUidCpuFreqTimeReader.removeUid(startUid);
290 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
291 mKernelUidCpuActiveTimeReader.removeUid(startUid);
292 mKernelUidCpuClusterTimeReader.removeUid(startUid);
293 }
294 if (mKernelSingleUidTimeReader != null) {
295 mKernelSingleUidTimeReader.removeUid(startUid);
296 }
297 mNumUidsRemoved++;
298 } else if (startUid < endUid) {
299 mKernelUidCpuFreqTimeReader.removeUidsInRange(startUid, endUid);
300 mKernelUidCpuTimeReader.removeUidsInRange(startUid, endUid);
301 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
302 mKernelUidCpuActiveTimeReader.removeUidsInRange(startUid, endUid);
303 mKernelUidCpuClusterTimeReader.removeUidsInRange(startUid, endUid);
304 }
305 if (mKernelSingleUidTimeReader != null) {
306 mKernelSingleUidTimeReader.removeUidsInRange(startUid, endUid);
307 }
308 // Treat as one. We don't know how many uids there are in between.
309 mNumUidsRemoved++;
310 } else {
311 Slog.w(TAG, "End UID " + endUid + " is smaller than start UID " + startUid);
312 }
313 }
314 }
Bookatz50df7112017-08-04 14:53:26 -0700315
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700316 public interface BatteryCallback {
317 public void batteryNeedsCpuUpdate();
318 public void batteryPowerChanged(boolean onBattery);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700319 public void batterySendBroadcast(Intent intent);
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700320 }
321
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700322 public interface PlatformIdleStateCallback {
Bookatz50df7112017-08-04 14:53:26 -0700323 public void fillLowPowerStats(RpmStats rpmStats);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700324 public String getPlatformLowPowerStats();
Ahmed ElArabawyd8b44112017-05-23 21:25:02 +0000325 public String getSubsystemLowPowerStats();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700326 }
327
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700328 public static abstract class UserInfoProvider {
329 private int[] userIds;
330 protected abstract @Nullable int[] getUserIds();
Sudheer Shanka38383232017-07-25 09:55:03 -0700331 @VisibleForTesting
332 public final void refreshUserIds() {
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700333 userIds = getUserIds();
334 }
Sudheer Shanka38383232017-07-25 09:55:03 -0700335 @VisibleForTesting
336 public boolean exists(int userId) {
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700337 return userIds != null ? ArrayUtils.contains(userIds, userId) : true;
338 }
339 }
340
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700341 private final PlatformIdleStateCallback mPlatformIdleStateCallback;
342
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700343 final class MyHandler extends Handler {
Jeff Brown6f357d32014-01-15 20:40:55 -0800344 public MyHandler(Looper looper) {
345 super(looper, null, true);
346 }
347
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700348 @Override
349 public void handleMessage(Message msg) {
350 BatteryCallback cb = mCallback;
351 switch (msg.what) {
Sudheer Shankac57729a2018-02-09 15:44:42 -0800352 case MSG_REPORT_CPU_UPDATE_NEEDED:
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700353 if (cb != null) {
354 cb.batteryNeedsCpuUpdate();
355 }
356 break;
357 case MSG_REPORT_POWER_CHANGE:
358 if (cb != null) {
359 cb.batteryPowerChanged(msg.arg1 != 0);
360 }
361 break;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700362 case MSG_REPORT_CHARGING:
363 if (cb != null) {
364 final String action;
365 synchronized (BatteryStatsImpl.this) {
366 action = mCharging ? BatteryManager.ACTION_CHARGING
367 : BatteryManager.ACTION_DISCHARGING;
368 }
369 Intent intent = new Intent(action);
370 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
371 cb.batterySendBroadcast(intent);
372 }
373 break;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700374 }
375 }
376 }
377
Sudheer Shankac57729a2018-02-09 15:44:42 -0800378 public void postBatteryNeedsCpuUpdateMsg() {
379 mHandler.sendEmptyMessage(MSG_REPORT_CPU_UPDATE_NEEDED);
380 }
381
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800382 /**
383 * Update per-freq cpu times for all the uids in {@link #mPendingUids}.
384 */
Sudheer Shankae544d162017-12-28 17:06:20 -0800385 public void updateProcStateCpuTimes(boolean onBattery, boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800386 final SparseIntArray uidStates;
387 synchronized (BatteryStatsImpl.this) {
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800388 if (!mConstants.TRACK_CPU_TIMES_BY_PROC_STATE) {
389 return;
390 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800391 if(!initKernelSingleUidTimeReaderLocked()) {
392 return;
393 }
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800394 // If the KernelSingleUidTimeReader has stale cpu times, then we shouldn't try to
395 // compute deltas since it might result in mis-attributing cpu times to wrong states.
396 if (mKernelSingleUidTimeReader.hasStaleData()) {
397 mPendingUids.clear();
398 return;
399 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800400
401 if (mPendingUids.size() == 0) {
402 return;
403 }
404 uidStates = mPendingUids.clone();
405 mPendingUids.clear();
406 }
407 for (int i = uidStates.size() - 1; i >= 0; --i) {
408 final int uid = uidStates.keyAt(i);
409 final int procState = uidStates.valueAt(i);
410 final int[] isolatedUids;
411 final Uid u;
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800412 synchronized (BatteryStatsImpl.this) {
413 // It's possible that uid no longer exists and any internal references have
414 // already been deleted, so using {@link #getAvailableUidStatsLocked} to avoid
415 // creating an UidStats object if it doesn't already exist.
416 u = getAvailableUidStatsLocked(uid);
417 if (u == null) {
418 continue;
419 }
420 if (u.mChildUids == null) {
421 isolatedUids = null;
422 } else {
423 isolatedUids = u.mChildUids.toArray();
424 for (int j = isolatedUids.length - 1; j >= 0; --j) {
425 isolatedUids[j] = u.mChildUids.get(j);
426 }
427 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800428 }
429 long[] cpuTimesMs = mKernelSingleUidTimeReader.readDeltaMs(uid);
430 if (isolatedUids != null) {
431 for (int j = isolatedUids.length - 1; j >= 0; --j) {
432 cpuTimesMs = addCpuTimes(cpuTimesMs,
433 mKernelSingleUidTimeReader.readDeltaMs(isolatedUids[j]));
434 }
435 }
436 if (onBattery && cpuTimesMs != null) {
437 synchronized (BatteryStatsImpl.this) {
Sudheer Shankae544d162017-12-28 17:06:20 -0800438 u.addProcStateTimesMs(procState, cpuTimesMs, onBattery);
439 u.addProcStateScreenOffTimesMs(procState, cpuTimesMs, onBatteryScreenOff);
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800440 }
441 }
442 }
443 }
444
Mike Ma234d1822018-03-13 18:53:21 -0700445 public void clearPendingRemovedUids() {
446 long cutOffTime = mClocks.elapsedRealtime() - mConstants.UID_REMOVE_DELAY_MS;
447 while (!mPendingRemovedUids.isEmpty()
448 && mPendingRemovedUids.peek().timeAddedInQueue < cutOffTime) {
449 mPendingRemovedUids.poll().remove();
450 }
451 }
452
Sudheer Shankae544d162017-12-28 17:06:20 -0800453 public void copyFromAllUidsCpuTimes() {
454 synchronized (BatteryStatsImpl.this) {
455 copyFromAllUidsCpuTimes(
456 mOnBatteryTimeBase.isRunning(), mOnBatteryScreenOffTimeBase.isRunning());
457 }
458 }
459
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800460 /**
461 * When the battery/screen state changes, we don't attribute the cpu times to any process
462 * but we still need to snapshots of all uids to get correct deltas later on. Since we
463 * already read this data for updating per-freq cpu times, we can use the same data for
464 * per-procstate cpu times.
465 */
Sudheer Shankae544d162017-12-28 17:06:20 -0800466 public void copyFromAllUidsCpuTimes(boolean onBattery, boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800467 synchronized (BatteryStatsImpl.this) {
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800468 if (!mConstants.TRACK_CPU_TIMES_BY_PROC_STATE) {
469 return;
470 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800471 if(!initKernelSingleUidTimeReaderLocked()) {
472 return;
473 }
474
475 final SparseArray<long[]> allUidCpuFreqTimesMs =
476 mKernelUidCpuFreqTimeReader.getAllUidCpuFreqTimeMs();
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800477 // If the KernelSingleUidTimeReader has stale cpu times, then we shouldn't try to
478 // compute deltas since it might result in mis-attributing cpu times to wrong states.
479 if (mKernelSingleUidTimeReader.hasStaleData()) {
480 mKernelSingleUidTimeReader.setAllUidsCpuTimesMs(allUidCpuFreqTimesMs);
481 mKernelSingleUidTimeReader.markDataAsStale(false);
482 mPendingUids.clear();
483 return;
484 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800485 for (int i = allUidCpuFreqTimesMs.size() - 1; i >= 0; --i) {
486 final int uid = allUidCpuFreqTimesMs.keyAt(i);
487 final Uid u = getAvailableUidStatsLocked(mapUid(uid));
488 if (u == null) {
489 continue;
490 }
491 final long[] cpuTimesMs = allUidCpuFreqTimesMs.valueAt(i);
492 if (cpuTimesMs == null) {
493 continue;
494 }
495 final long[] deltaTimesMs = mKernelSingleUidTimeReader.computeDelta(
496 uid, cpuTimesMs.clone());
Sudheer Shankae544d162017-12-28 17:06:20 -0800497 if (onBattery && deltaTimesMs != null) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800498 final int procState;
499 final int idx = mPendingUids.indexOfKey(uid);
500 if (idx >= 0) {
501 procState = mPendingUids.valueAt(idx);
502 mPendingUids.removeAt(idx);
503 } else {
504 procState = u.mProcessState;
505 }
506 if (procState >= 0 && procState < Uid.NUM_PROCESS_STATE) {
Sudheer Shankae544d162017-12-28 17:06:20 -0800507 u.addProcStateTimesMs(procState, deltaTimesMs, onBattery);
508 u.addProcStateScreenOffTimesMs(procState, deltaTimesMs, onBatteryScreenOff);
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800509 }
510 }
511 }
512 }
513 }
514
515 @VisibleForTesting
516 public long[] addCpuTimes(long[] timesA, long[] timesB) {
517 if (timesA != null && timesB != null) {
518 for (int i = timesA.length - 1; i >= 0; --i) {
519 timesA[i] += timesB[i];
520 }
521 return timesA;
522 }
523 return timesA == null ? (timesB == null ? null : timesB) : timesA;
524 }
525
526 @GuardedBy("this")
527 private boolean initKernelSingleUidTimeReaderLocked() {
528 if (mKernelSingleUidTimeReader == null) {
529 if (mPowerProfile == null) {
530 return false;
531 }
532 if (mCpuFreqs == null) {
533 mCpuFreqs = mKernelUidCpuFreqTimeReader.readFreqs(mPowerProfile);
534 }
535 if (mCpuFreqs != null) {
536 mKernelSingleUidTimeReader = new KernelSingleUidTimeReader(mCpuFreqs.length);
537 } else {
538 mPerProcStateCpuTimesAvailable = mKernelUidCpuFreqTimeReader.allUidTimesAvailable();
539 return false;
540 }
541 }
542 mPerProcStateCpuTimesAvailable = mKernelUidCpuFreqTimeReader.allUidTimesAvailable()
543 && mKernelSingleUidTimeReader.singleUidCpuTimesAvailable();
544 return true;
545 }
546
Joe Onoratoabded112016-02-08 16:49:39 -0800547 public interface Clocks {
548 public long elapsedRealtime();
549 public long uptimeMillis();
550 }
551
552 public static class SystemClocks implements Clocks {
553 public long elapsedRealtime() {
554 return SystemClock.elapsedRealtime();
555 }
556
557 public long uptimeMillis() {
558 return SystemClock.uptimeMillis();
559 }
560 }
561
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700562 public interface ExternalStatsSync {
Adam Lesinski14ae39a2017-05-26 11:50:40 -0700563 int UPDATE_CPU = 0x01;
564 int UPDATE_WIFI = 0x02;
565 int UPDATE_RADIO = 0x04;
566 int UPDATE_BT = 0x08;
Bookatz50df7112017-08-04 14:53:26 -0700567 int UPDATE_RPM = 0x10; // 16
568 int UPDATE_ALL = UPDATE_CPU | UPDATE_WIFI | UPDATE_RADIO | UPDATE_BT | UPDATE_RPM;
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800569
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700570 Future<?> scheduleSync(String reason, int flags);
571 Future<?> scheduleCpuSyncDueToRemovedUid(int uid);
Sudheer Shankac20379e2018-02-15 00:06:21 -0800572 Future<?> scheduleReadProcStateCpuTimes(boolean onBattery, boolean onBatteryScreenOff,
573 long delayMillis);
Sudheer Shankae544d162017-12-28 17:06:20 -0800574 Future<?> scheduleCopyFromAllUidsCpuTimes(boolean onBattery, boolean onBatteryScreenOff);
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800575 Future<?> scheduleCpuSyncDueToSettingChange();
Sudheer Shankac57729a2018-02-09 15:44:42 -0800576 Future<?> scheduleCpuSyncDueToScreenStateChange(boolean onBattery,
577 boolean onBatteryScreenOff);
578 Future<?> scheduleCpuSyncDueToWakelockChange(long delayMillis);
579 void cancelCpuSyncDueToWakelockChange();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700580 }
581
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800582 public Handler mHandler;
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700583 private ExternalStatsSync mExternalSync = null;
Sudheer Shanka38383232017-07-25 09:55:03 -0700584 @VisibleForTesting
585 protected UserInfoProvider mUserInfoProvider = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700586
587 private BatteryCallback mCallback;
588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800589 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -0800590 * Mapping isolated uids to the actual owning app uid.
591 */
592 final SparseIntArray mIsolatedUids = new SparseIntArray();
593
594 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 * The statistics we have collected organized by uids.
596 */
Adam Lesinski50e47602015-12-04 17:04:54 -0800597 final SparseArray<BatteryStatsImpl.Uid> mUidStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800598
599 // A set of pools of currently active timers. When a timer is queried, we will divide the
600 // elapsed time by the number of active timers to arrive at that timer's share of the time.
601 // In order to do this, we must refresh each timer whenever the number of active timers
602 // changes.
Sudheer Shanka38383232017-07-25 09:55:03 -0700603 @VisibleForTesting
604 protected ArrayList<StopwatchTimer> mPartialTimers = new ArrayList<>();
Adam Lesinskie08af192015-03-25 16:42:59 -0700605 final ArrayList<StopwatchTimer> mFullTimers = new ArrayList<>();
606 final ArrayList<StopwatchTimer> mWindowTimers = new ArrayList<>();
Jeff Brown6a8bd7b2015-06-19 15:07:51 -0700607 final ArrayList<StopwatchTimer> mDrawTimers = new ArrayList<>();
Adam Lesinskie08af192015-03-25 16:42:59 -0700608 final SparseArray<ArrayList<StopwatchTimer>> mSensorTimers = new SparseArray<>();
609 final ArrayList<StopwatchTimer> mWifiRunningTimers = new ArrayList<>();
610 final ArrayList<StopwatchTimer> mFullWifiLockTimers = new ArrayList<>();
611 final ArrayList<StopwatchTimer> mWifiMulticastTimers = new ArrayList<>();
612 final ArrayList<StopwatchTimer> mWifiScanTimers = new ArrayList<>();
613 final SparseArray<ArrayList<StopwatchTimer>> mWifiBatchedScanTimers = new SparseArray<>();
614 final ArrayList<StopwatchTimer> mAudioTurnedOnTimers = new ArrayList<>();
615 final ArrayList<StopwatchTimer> mVideoTurnedOnTimers = new ArrayList<>();
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700616 final ArrayList<StopwatchTimer> mFlashlightTurnedOnTimers = new ArrayList<>();
617 final ArrayList<StopwatchTimer> mCameraTurnedOnTimers = new ArrayList<>();
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800618 final ArrayList<StopwatchTimer> mBluetoothScanOnTimers = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700620 // Last partial timers we use for distributing CPU usage.
Sudheer Shanka38383232017-07-25 09:55:03 -0700621 @VisibleForTesting
622 protected ArrayList<StopwatchTimer> mLastPartialTimers = new ArrayList<>();
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624 // These are the objects that will want to do something when the device
625 // is unplugged from power.
Joe Onoratoabded112016-02-08 16:49:39 -0800626 protected final TimeBase mOnBatteryTimeBase = new TimeBase();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800627
628 // These are the objects that will want to do something when the device
Mike Mac2f518a2017-09-19 16:06:03 -0700629 // is unplugged from power *and* the screen is off or doze.
630 protected final TimeBase mOnBatteryScreenOffTimeBase = new TimeBase();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800631
632 // Set to true when we want to distribute CPU across wakelocks for the next
633 // CPU update, even if we aren't currently running wake locks.
634 boolean mDistributeWakelockCpu;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700635
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700636 boolean mShuttingDown;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700637
Dianne Hackborn37de0982014-05-09 09:32:18 -0700638 final HistoryEventTracker mActiveEvents = new HistoryEventTracker();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800639
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700640 long mHistoryBaseTime;
Narayan Kamath695cf722017-12-21 18:32:47 +0000641 protected boolean mHaveBatteryLevel = false;
642 protected boolean mRecordingHistory = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700643 int mNumHistoryItems;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700644
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700645 final Parcel mHistoryBuffer = Parcel.obtain();
646 final HistoryItem mHistoryLastWritten = new HistoryItem();
647 final HistoryItem mHistoryLastLastWritten = new HistoryItem();
Dianne Hackborn1fadab52011-04-14 17:57:33 -0700648 final HistoryItem mHistoryReadTmp = new HistoryItem();
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700649 final HistoryItem mHistoryAddTmp = new HistoryItem();
Adam Lesinskie08af192015-03-25 16:42:59 -0700650 final HashMap<HistoryTag, Integer> mHistoryTagPool = new HashMap<>();
Dianne Hackborn099bc622014-01-22 13:39:16 -0800651 String[] mReadHistoryStrings;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -0800652 int[] mReadHistoryUids;
653 int mReadHistoryChars;
654 int mNextHistoryTagIdx = 0;
655 int mNumHistoryTagChars = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700656 int mHistoryBufferLastPos = -1;
657 boolean mHistoryOverflow = false;
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700658 int mActiveHistoryStates = 0xffffffff;
659 int mActiveHistoryStates2 = 0xffffffff;
Dianne Hackborn40c87252014-03-19 16:55:40 -0700660 long mLastHistoryElapsedRealtime = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700661 long mTrackRunningHistoryElapsedRealtime = 0;
662 long mTrackRunningHistoryUptime = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700663
664 final HistoryItem mHistoryCur = new HistoryItem();
665
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700666 HistoryItem mHistory;
667 HistoryItem mHistoryEnd;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700668 HistoryItem mHistoryLastEnd;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700669 HistoryItem mHistoryCache;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700670
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800671 // Used by computeHistoryStepDetails
672 HistoryStepDetails mLastHistoryStepDetails = null;
673 byte mLastHistoryStepLevel = 0;
674 final HistoryStepDetails mCurHistoryStepDetails = new HistoryStepDetails();
675 final HistoryStepDetails mReadHistoryStepDetails = new HistoryStepDetails();
676 final HistoryStepDetails mTmpHistoryStepDetails = new HistoryStepDetails();
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700677
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800678 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700679 * Total time (in milliseconds) spent executing in user code.
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800680 */
681 long mLastStepCpuUserTime;
682 long mCurStepCpuUserTime;
683 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700684 * Total time (in milliseconds) spent executing in kernel code.
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800685 */
686 long mLastStepCpuSystemTime;
687 long mCurStepCpuSystemTime;
688 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700689 * Times from /proc/stat (but measured in milliseconds).
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800690 */
691 long mLastStepStatUserTime;
692 long mLastStepStatSystemTime;
693 long mLastStepStatIOWaitTime;
694 long mLastStepStatIrqTime;
695 long mLastStepStatSoftIrqTime;
696 long mLastStepStatIdleTime;
697 long mCurStepStatUserTime;
698 long mCurStepStatSystemTime;
699 long mCurStepStatIOWaitTime;
700 long mCurStepStatIrqTime;
701 long mCurStepStatSoftIrqTime;
702 long mCurStepStatIdleTime;
703
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700704 private HistoryItem mHistoryIterator;
705 private boolean mReadOverflow;
706 private boolean mIteratingHistory;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700707
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708 int mStartCount;
709
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -0800710 long mStartClockTime;
Dianne Hackborncd0e3352014-08-07 17:08:09 -0700711 String mStartPlatformVersion;
712 String mEndPlatformVersion;
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -0800713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800714 long mUptime;
715 long mUptimeStart;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 long mRealtime;
717 long mRealtimeStart;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700718
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800719 int mWakeLockNesting;
720 boolean mWakeLockImportant;
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700721 public boolean mRecordAllHistory;
Dianne Hackborn9a755432014-05-15 17:05:22 -0700722 boolean mNoAutoReset;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800723
Mike Mac2f518a2017-09-19 16:06:03 -0700724 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
725 protected int mScreenState = Display.STATE_UNKNOWN;
726 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
727 protected StopwatchTimer mScreenOnTimer;
728 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
729 protected StopwatchTimer mScreenDozeTimer;
Amith Yamasani3718aaa2009-06-09 06:32:35 -0700730
Dianne Hackborn617f8772009-03-31 15:04:46 -0700731 int mScreenBrightnessBin = -1;
Evan Millarc64edde2009-04-18 12:26:32 -0700732 final StopwatchTimer[] mScreenBrightnessTimer = new StopwatchTimer[NUM_SCREEN_BRIGHTNESS_BINS];
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700733
Amith Yamasani674c9bb2017-02-01 09:45:17 -0800734 boolean mPretendScreenOff;
735
Jeff Browne95c3cd2014-05-02 16:59:26 -0700736 boolean mInteractive;
737 StopwatchTimer mInteractiveTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700738
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700739 boolean mPowerSaveModeEnabled;
740 StopwatchTimer mPowerSaveModeEnabledTimer;
741
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700742 boolean mDeviceIdling;
743 StopwatchTimer mDeviceIdlingTimer;
744
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700745 boolean mDeviceLightIdling;
746 StopwatchTimer mDeviceLightIdlingTimer;
747
748 int mDeviceIdleMode;
749 long mLastIdleTimeStart;
750 long mLongestLightIdleTime;
751 long mLongestFullIdleTime;
752 StopwatchTimer mDeviceIdleModeLightTimer;
753 StopwatchTimer mDeviceIdleModeFullTimer;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 boolean mPhoneOn;
Evan Millarc64edde2009-04-18 12:26:32 -0700756 StopwatchTimer mPhoneOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700757
Dianne Hackborn10eaa852014-07-22 22:54:55 -0700758 int mAudioOnNesting;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700759 StopwatchTimer mAudioOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700760
Dianne Hackborn10eaa852014-07-22 22:54:55 -0700761 int mVideoOnNesting;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700762 StopwatchTimer mVideoOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700763
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700764 int mFlashlightOnNesting;
Dianne Hackbornabc7c492014-06-30 16:57:46 -0700765 StopwatchTimer mFlashlightOnTimer;
766
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700767 int mCameraOnNesting;
768 StopwatchTimer mCameraOnTimer;
769
Mike Ma926a97c2018-03-25 02:32:35 -0700770 int mUsbDataState; // 0: unknown, 1: disconnected, 2: connected
771
Siddharth Ray78ccaf52017-12-23 16:16:21 -0800772 int mGpsSignalQualityBin = -1;
Narayan Kamathefa0fe62018-02-05 16:04:43 +0000773 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
774 protected final StopwatchTimer[] mGpsSignalQualityTimer =
Siddharth Ray78ccaf52017-12-23 16:16:21 -0800775 new StopwatchTimer[GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS];
776
Dianne Hackborn627bba72009-03-24 22:32:56 -0700777 int mPhoneSignalStrengthBin = -1;
Dianne Hackborne4a59512010-12-07 11:08:07 -0800778 int mPhoneSignalStrengthBinRaw = -1;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700779 final StopwatchTimer[] mPhoneSignalStrengthsTimer =
Wink Saville52840902011-02-18 12:40:47 -0800780 new StopwatchTimer[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
Amith Yamasanif37447b2009-10-08 18:28:01 -0700781
782 StopwatchTimer mPhoneSignalScanningTimer;
783
Dianne Hackborn627bba72009-03-24 22:32:56 -0700784 int mPhoneDataConnectionType = -1;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700785 final StopwatchTimer[] mPhoneDataConnectionsTimer =
Evan Millarc64edde2009-04-18 12:26:32 -0700786 new StopwatchTimer[NUM_DATA_CONNECTION_TYPES];
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700787
Dianne Hackborn57ed6a62013-12-09 18:15:56 -0800788 final LongSamplingCounter[] mNetworkByteActivityCounters =
789 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
790 final LongSamplingCounter[] mNetworkPacketActivityCounters =
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700791 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
792
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800793 /**
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -0800794 * The WiFi Overall wakelock timer
795 * This timer tracks the actual aggregate time for which MC wakelocks are enabled
796 * since addition of per UID timers would not result in an accurate value due to overlapp of
797 * per uid wakelock timers
798 */
799 StopwatchTimer mWifiMulticastWakelockTimer;
800
801 /**
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800802 * The WiFi controller activity (time in tx, rx, idle, and power consumed) for the device.
803 */
804 ControllerActivityCounterImpl mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -0700805
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800806 /**
807 * The Bluetooth controller activity (time in tx, rx, idle, and power consumed) for the device.
808 */
809 ControllerActivityCounterImpl mBluetoothActivity;
810
811 /**
812 * The Modem controller activity (time in tx, rx, idle, and power consumed) for the device.
813 */
814 ControllerActivityCounterImpl mModemActivity;
815
816 /**
817 * Whether the device supports WiFi controller energy reporting. This is set to true on
818 * the first WiFi energy report. See {@link #mWifiActivity}.
819 */
820 boolean mHasWifiReporting = false;
821
822 /**
823 * Whether the device supports Bluetooth controller energy reporting. This is set to true on
824 * the first Bluetooth energy report. See {@link #mBluetoothActivity}.
825 */
826 boolean mHasBluetoothReporting = false;
827
828 /**
829 * Whether the device supports Modem controller energy reporting. This is set to true on
830 * the first Modem energy report. See {@link #mModemActivity}.
831 */
832 boolean mHasModemReporting = false;
Adam Lesinski33dac552015-03-09 15:24:48 -0700833
The Android Open Source Project10592532009-03-18 17:39:46 -0700834 boolean mWifiOn;
Evan Millarc64edde2009-04-18 12:26:32 -0700835 StopwatchTimer mWifiOnTimer;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -0700836
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700837 boolean mGlobalWifiRunning;
838 StopwatchTimer mGlobalWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700839
Dianne Hackbornca1bf212014-02-14 14:18:36 -0800840 int mWifiState = -1;
841 final StopwatchTimer[] mWifiStateTimer = new StopwatchTimer[NUM_WIFI_STATES];
842
Dianne Hackborn3251b902014-06-20 14:40:53 -0700843 int mWifiSupplState = -1;
844 final StopwatchTimer[] mWifiSupplStateTimer = new StopwatchTimer[NUM_WIFI_SUPPL_STATES];
845
846 int mWifiSignalStrengthBin = -1;
847 final StopwatchTimer[] mWifiSignalStrengthsTimer =
848 new StopwatchTimer[NUM_WIFI_SIGNAL_STRENGTH_BINS];
849
Siddharth Rayb50a6842017-12-14 15:15:28 -0800850 StopwatchTimer mWifiActiveTimer;
851
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800852 int mBluetoothScanNesting;
Bookatz867c0d72017-03-07 18:23:42 -0800853 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
854 protected StopwatchTimer mBluetoothScanTimer;
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800855
Siddharth Rayf5e796a2018-01-22 18:18:17 -0800856 boolean mIsCellularTxPowerHigh = false;
857
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700858 int mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackbornf7097a52014-05-13 09:56:14 -0700859 long mMobileRadioActiveStartTime;
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800860 StopwatchTimer mMobileRadioActiveTimer;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800861 StopwatchTimer mMobileRadioActivePerAppTimer;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700862 LongSamplingCounter mMobileRadioActiveAdjustedTime;
Dianne Hackbornd45665b2014-02-26 12:35:32 -0800863 LongSamplingCounter mMobileRadioActiveUnknownTime;
864 LongSamplingCounter mMobileRadioActiveUnknownCount;
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800865
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700866 int mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 /**
869 * These provide time bases that discount the time the device is plugged
870 * in to power.
871 */
872 boolean mOnBattery;
Sudheer Shanka38383232017-07-25 09:55:03 -0700873 @VisibleForTesting
874 protected boolean mOnBatteryInternal;
Amith Yamasani3718aaa2009-06-09 06:32:35 -0700875
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700876 /**
877 * External reporting of whether the device is actually charging.
878 */
879 boolean mCharging = true;
880 int mLastChargingStateLevel;
881
The Android Open Source Project10592532009-03-18 17:39:46 -0700882 /*
883 * These keep track of battery levels (1-100) at the last plug event and the last unplug event.
884 */
Evan Millar633a1742009-04-02 16:36:33 -0700885 int mDischargeStartLevel;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700886 int mDischargeUnplugLevel;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700887 int mDischargePlugLevel;
Evan Millar633a1742009-04-02 16:36:33 -0700888 int mDischargeCurrentLevel;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700889 int mCurrentBatteryLevel;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -0700890 int mLowDischargeAmountSinceCharge;
891 int mHighDischargeAmountSinceCharge;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -0800892 int mDischargeScreenOnUnplugLevel;
893 int mDischargeScreenOffUnplugLevel;
Mike Mac2f518a2017-09-19 16:06:03 -0700894 int mDischargeScreenDozeUnplugLevel;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -0800895 int mDischargeAmountScreenOn;
896 int mDischargeAmountScreenOnSinceCharge;
897 int mDischargeAmountScreenOff;
898 int mDischargeAmountScreenOffSinceCharge;
Mike Mac2f518a2017-09-19 16:06:03 -0700899 int mDischargeAmountScreenDoze;
900 int mDischargeAmountScreenDozeSinceCharge;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700901
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700902 private LongSamplingCounter mDischargeScreenOffCounter;
Mike Mac2f518a2017-09-19 16:06:03 -0700903 private LongSamplingCounter mDischargeScreenDozeCounter;
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700904 private LongSamplingCounter mDischargeCounter;
Mike Ma15313c92017-11-15 17:58:21 -0800905 private LongSamplingCounter mDischargeLightDozeCounter;
906 private LongSamplingCounter mDischargeDeepDozeCounter;
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700907
Dianne Hackborncd0e3352014-08-07 17:08:09 -0700908 static final int MAX_LEVEL_STEPS = 200;
Dianne Hackborn260c5022014-04-29 11:23:16 -0700909
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700910 int mInitStepMode = 0;
911 int mCurStepMode = 0;
912 int mModStepMode = 0;
913
Dianne Hackborn260c5022014-04-29 11:23:16 -0700914 int mLastDischargeStepLevel;
Dianne Hackborn29325132014-05-21 15:01:03 -0700915 int mMinDischargeStepLevel;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800916 final LevelStepTracker mDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS);
917 final LevelStepTracker mDailyDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700918 ArrayList<PackageChange> mDailyPackageChanges;
Dianne Hackborn260c5022014-04-29 11:23:16 -0700919
920 int mLastChargeStepLevel;
Dianne Hackborn29325132014-05-21 15:01:03 -0700921 int mMaxChargeStepLevel;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800922 final LevelStepTracker mChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS);
923 final LevelStepTracker mDailyChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2);
924
925 static final int MAX_DAILY_ITEMS = 10;
926
927 long mDailyStartTime = 0;
928 long mNextMinDailyDeadline = 0;
929 long mNextMaxDailyDeadline = 0;
930
931 final ArrayList<DailyItem> mDailyItems = new ArrayList<>();
Dianne Hackborn260c5022014-04-29 11:23:16 -0700932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 long mLastWriteTime = 0; // Milliseconds
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700934
Amith Yamasanif37447b2009-10-08 18:28:01 -0700935 private int mPhoneServiceState = -1;
Dianne Hackborne4a59512010-12-07 11:08:07 -0800936 private int mPhoneServiceStateRaw = -1;
937 private int mPhoneSimStateRaw = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -0700938
Dianne Hackborn1e01d162014-12-04 17:46:42 -0800939 private int mNumConnectivityChange;
940 private int mLoadedNumConnectivityChange;
941 private int mUnpluggedNumConnectivityChange;
942
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700943 private int mEstimatedBatteryCapacity = -1;
944
Jocelyn Dangc627d102017-04-14 13:15:14 -0700945 private int mMinLearnedBatteryCapacity = -1;
946 private int mMaxLearnedBatteryCapacity = -1;
Adam Lesinski041d9172016-12-12 12:03:56 -0800947
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700948 private long[] mCpuFreqs;
949
Sudheer Shanka38383232017-07-25 09:55:03 -0700950 @VisibleForTesting
951 protected PowerProfile mPowerProfile;
Adam Lesinskie08af192015-03-25 16:42:59 -0700952
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800953 @GuardedBy("this")
954 private final Constants mConstants;
955
Evan Millarc64edde2009-04-18 12:26:32 -0700956 /*
Bookatz50df7112017-08-04 14:53:26 -0700957 * Holds a SamplingTimer associated with each Resource Power Manager state and voter,
958 * recording their times when on-battery (regardless of screen state).
959 */
960 private final HashMap<String, SamplingTimer> mRpmStats = new HashMap<>();
961 /** Times for each Resource Power Manager state and voter when screen-off and on-battery. */
962 private final HashMap<String, SamplingTimer> mScreenOffRpmStats = new HashMap<>();
963
964 @Override
965 public Map<String, ? extends Timer> getRpmStats() {
966 return mRpmStats;
967 }
968
Bookatz82b341172017-09-07 19:06:08 -0700969 // TODO: Note: screenOffRpmStats has been disabled via SCREEN_OFF_RPM_STATS_ENABLED.
Bookatz50df7112017-08-04 14:53:26 -0700970 @Override
971 public Map<String, ? extends Timer> getScreenOffRpmStats() {
972 return mScreenOffRpmStats;
973 }
974
975 /*
Evan Millarc64edde2009-04-18 12:26:32 -0700976 * Holds a SamplingTimer associated with each kernel wakelock name being tracked.
977 */
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700978 private final HashMap<String, SamplingTimer> mKernelWakelockStats = new HashMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700979
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700980 public Map<String, ? extends Timer> getKernelWakelockStats() {
Evan Millarc64edde2009-04-18 12:26:32 -0700981 return mKernelWakelockStats;
982 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700983
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700984 String mLastWakeupReason = null;
985 long mLastWakeupUptimeMs = 0;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -0700986 private final HashMap<String, SamplingTimer> mWakeupReasonStats = new HashMap<>();
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700987
Dianne Hackbornc3940bc2014-09-05 15:50:25 -0700988 public Map<String, ? extends Timer> getWakeupReasonStats() {
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700989 return mWakeupReasonStats;
990 }
991
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700992 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -0700993 public long getUahDischarge(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -0700994 return mDischargeCounter.getCountLocked(which);
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700995 }
996
997 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -0700998 public long getUahDischargeScreenOff(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -0700999 return mDischargeScreenOffCounter.getCountLocked(which);
1000 }
1001
1002 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -07001003 public long getUahDischargeScreenDoze(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -07001004 return mDischargeScreenDozeCounter.getCountLocked(which);
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001005 }
1006
Adam Lesinskif9b20a92016-06-17 17:30:01 -07001007 @Override
Mike Ma15313c92017-11-15 17:58:21 -08001008 public long getUahDischargeLightDoze(int which) {
1009 return mDischargeLightDozeCounter.getCountLocked(which);
1010 }
1011
1012 @Override
1013 public long getUahDischargeDeepDoze(int which) {
1014 return mDischargeDeepDozeCounter.getCountLocked(which);
1015 }
1016
1017 @Override
Adam Lesinskif9b20a92016-06-17 17:30:01 -07001018 public int getEstimatedBatteryCapacity() {
1019 return mEstimatedBatteryCapacity;
1020 }
1021
Jocelyn Dangc627d102017-04-14 13:15:14 -07001022 @Override
1023 public int getMinLearnedBatteryCapacity() {
1024 return mMinLearnedBatteryCapacity;
1025 }
1026
1027 @Override
1028 public int getMaxLearnedBatteryCapacity() {
1029 return mMaxLearnedBatteryCapacity;
1030 }
1031
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032 public BatteryStatsImpl() {
Joe Onoratoabded112016-02-08 16:49:39 -08001033 this(new SystemClocks());
1034 }
1035
1036 public BatteryStatsImpl(Clocks clocks) {
1037 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07001038 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07001039 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08001040 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001041 mHandler = null;
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07001042 mPlatformIdleStateCallback = null;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -07001043 mUserInfoProvider = null;
Sudheer Shanka5c19b892018-01-05 17:25:46 -08001044 mConstants = new Constants(mHandler);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07001045 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 }
1047
Joe Onoratoabded112016-02-08 16:49:39 -08001048 private void init(Clocks clocks) {
1049 mClocks = clocks;
Joe Onoratoabded112016-02-08 16:49:39 -08001050 }
1051
Adam Lesinski14ae39a2017-05-26 11:50:40 -07001052 public interface TimeBaseObs {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001053 void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime);
1054 void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime);
1055 }
1056
Joe Onoratoabded112016-02-08 16:49:39 -08001057 // methods are protected not private to be VisibleForTesting
1058 public static class TimeBase {
1059 protected final ArrayList<TimeBaseObs> mObservers = new ArrayList<>();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001060
Joe Onoratoabded112016-02-08 16:49:39 -08001061 protected long mUptime;
1062 protected long mRealtime;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001063
Joe Onoratoabded112016-02-08 16:49:39 -08001064 protected boolean mRunning;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001065
Joe Onoratoabded112016-02-08 16:49:39 -08001066 protected long mPastUptime;
1067 protected long mUptimeStart;
1068 protected long mPastRealtime;
1069 protected long mRealtimeStart;
1070 protected long mUnpluggedUptime;
1071 protected long mUnpluggedRealtime;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001072
1073 public void dump(PrintWriter pw, String prefix) {
1074 StringBuilder sb = new StringBuilder(128);
1075 pw.print(prefix); pw.print("mRunning="); pw.println(mRunning);
1076 sb.setLength(0);
1077 sb.append(prefix);
1078 sb.append("mUptime=");
Dianne Hackborn4590e522014-03-24 13:36:46 -07001079 formatTimeMs(sb, mUptime / 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001080 pw.println(sb.toString());
1081 sb.setLength(0);
1082 sb.append(prefix);
1083 sb.append("mRealtime=");
Dianne Hackborn4590e522014-03-24 13:36:46 -07001084 formatTimeMs(sb, mRealtime / 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001085 pw.println(sb.toString());
1086 sb.setLength(0);
1087 sb.append(prefix);
1088 sb.append("mPastUptime=");
1089 formatTimeMs(sb, mPastUptime / 1000); sb.append("mUptimeStart=");
1090 formatTimeMs(sb, mUptimeStart / 1000);
1091 sb.append("mUnpluggedUptime="); formatTimeMs(sb, mUnpluggedUptime / 1000);
1092 pw.println(sb.toString());
1093 sb.setLength(0);
1094 sb.append(prefix);
1095 sb.append("mPastRealtime=");
1096 formatTimeMs(sb, mPastRealtime / 1000); sb.append("mRealtimeStart=");
1097 formatTimeMs(sb, mRealtimeStart / 1000);
1098 sb.append("mUnpluggedRealtime="); formatTimeMs(sb, mUnpluggedRealtime / 1000);
1099 pw.println(sb.toString());
1100 }
1101
1102 public void add(TimeBaseObs observer) {
1103 mObservers.add(observer);
1104 }
1105
1106 public void remove(TimeBaseObs observer) {
1107 if (!mObservers.remove(observer)) {
1108 Slog.wtf(TAG, "Removed unknown observer: " + observer);
1109 }
1110 }
1111
Joe Onoratoabded112016-02-08 16:49:39 -08001112 public boolean hasObserver(TimeBaseObs observer) {
1113 return mObservers.contains(observer);
1114 }
1115
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001116 public void init(long uptime, long realtime) {
1117 mRealtime = 0;
1118 mUptime = 0;
1119 mPastUptime = 0;
1120 mPastRealtime = 0;
1121 mUptimeStart = uptime;
1122 mRealtimeStart = realtime;
1123 mUnpluggedUptime = getUptime(mUptimeStart);
1124 mUnpluggedRealtime = getRealtime(mRealtimeStart);
1125 }
1126
1127 public void reset(long uptime, long realtime) {
1128 if (!mRunning) {
1129 mPastUptime = 0;
1130 mPastRealtime = 0;
1131 } else {
1132 mUptimeStart = uptime;
1133 mRealtimeStart = realtime;
Joe Onoratoabded112016-02-08 16:49:39 -08001134 // TODO: Since mUptimeStart was just reset and we are running, getUptime will
1135 // just return mPastUptime. Also, are we sure we don't want to reset that?
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001136 mUnpluggedUptime = getUptime(uptime);
Joe Onoratoabded112016-02-08 16:49:39 -08001137 // TODO: likewise.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001138 mUnpluggedRealtime = getRealtime(realtime);
1139 }
1140 }
1141
1142 public long computeUptime(long curTime, int which) {
1143 switch (which) {
1144 case STATS_SINCE_CHARGED:
1145 return mUptime + getUptime(curTime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001146 case STATS_CURRENT:
1147 return getUptime(curTime);
1148 case STATS_SINCE_UNPLUGGED:
1149 return getUptime(curTime) - mUnpluggedUptime;
1150 }
1151 return 0;
1152 }
1153
1154 public long computeRealtime(long curTime, int which) {
1155 switch (which) {
1156 case STATS_SINCE_CHARGED:
1157 return mRealtime + getRealtime(curTime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001158 case STATS_CURRENT:
1159 return getRealtime(curTime);
1160 case STATS_SINCE_UNPLUGGED:
1161 return getRealtime(curTime) - mUnpluggedRealtime;
1162 }
1163 return 0;
1164 }
1165
1166 public long getUptime(long curTime) {
1167 long time = mPastUptime;
1168 if (mRunning) {
1169 time += curTime - mUptimeStart;
1170 }
1171 return time;
1172 }
1173
1174 public long getRealtime(long curTime) {
1175 long time = mPastRealtime;
1176 if (mRunning) {
1177 time += curTime - mRealtimeStart;
1178 }
1179 return time;
1180 }
1181
1182 public long getUptimeStart() {
1183 return mUptimeStart;
1184 }
1185
1186 public long getRealtimeStart() {
1187 return mRealtimeStart;
1188 }
1189
1190 public boolean isRunning() {
1191 return mRunning;
1192 }
1193
1194 public boolean setRunning(boolean running, long uptime, long realtime) {
1195 if (mRunning != running) {
1196 mRunning = running;
1197 if (running) {
1198 mUptimeStart = uptime;
1199 mRealtimeStart = realtime;
1200 long batteryUptime = mUnpluggedUptime = getUptime(uptime);
1201 long batteryRealtime = mUnpluggedRealtime = getRealtime(realtime);
1202
1203 for (int i = mObservers.size() - 1; i >= 0; i--) {
1204 mObservers.get(i).onTimeStarted(realtime, batteryUptime, batteryRealtime);
1205 }
1206 } else {
1207 mPastUptime += uptime - mUptimeStart;
1208 mPastRealtime += realtime - mRealtimeStart;
1209
1210 long batteryUptime = getUptime(uptime);
1211 long batteryRealtime = getRealtime(realtime);
1212
1213 for (int i = mObservers.size() - 1; i >= 0; i--) {
1214 mObservers.get(i).onTimeStopped(realtime, batteryUptime, batteryRealtime);
1215 }
1216 }
1217 return true;
1218 }
1219 return false;
1220 }
1221
1222 public void readSummaryFromParcel(Parcel in) {
1223 mUptime = in.readLong();
1224 mRealtime = in.readLong();
1225 }
1226
1227 public void writeSummaryToParcel(Parcel out, long uptime, long realtime) {
1228 out.writeLong(computeUptime(uptime, STATS_SINCE_CHARGED));
1229 out.writeLong(computeRealtime(realtime, STATS_SINCE_CHARGED));
1230 }
1231
1232 public void readFromParcel(Parcel in) {
1233 mRunning = false;
1234 mUptime = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001235 mPastUptime = in.readLong();
1236 mUptimeStart = in.readLong();
Dianne Hackbornef640cd2014-03-25 14:41:05 -07001237 mRealtime = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001238 mPastRealtime = in.readLong();
1239 mRealtimeStart = in.readLong();
1240 mUnpluggedUptime = in.readLong();
1241 mUnpluggedRealtime = in.readLong();
1242 }
1243
1244 public void writeToParcel(Parcel out, long uptime, long realtime) {
1245 final long runningUptime = getUptime(uptime);
1246 final long runningRealtime = getRealtime(realtime);
1247 out.writeLong(mUptime);
1248 out.writeLong(runningUptime);
1249 out.writeLong(mUptimeStart);
Dianne Hackbornef640cd2014-03-25 14:41:05 -07001250 out.writeLong(mRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001251 out.writeLong(runningRealtime);
1252 out.writeLong(mRealtimeStart);
1253 out.writeLong(mUnpluggedUptime);
1254 out.writeLong(mUnpluggedRealtime);
1255 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001257
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001258 /**
Dianne Hackborn617f8772009-03-31 15:04:46 -07001259 * State for keeping track of counting information.
1260 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001261 public static class Counter extends BatteryStats.Counter implements TimeBaseObs {
Christopher Tate4cee7252010-03-19 14:50:40 -07001262 final AtomicInteger mCount = new AtomicInteger();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001263 final TimeBase mTimeBase;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001264 int mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001265 int mUnpluggedCount;
1266 int mPluggedCount;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001267
Bookatz8c6f3c52017-05-24 12:00:17 -07001268 public Counter(TimeBase timeBase, Parcel in) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001269 mTimeBase = timeBase;
Christopher Tate4cee7252010-03-19 14:50:40 -07001270 mPluggedCount = in.readInt();
1271 mCount.set(mPluggedCount);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001272 mLoadedCount = in.readInt();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001273 mUnpluggedCount = in.readInt();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001274 timeBase.add(this);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001275 }
1276
Bookatz8c6f3c52017-05-24 12:00:17 -07001277 public Counter(TimeBase timeBase) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001278 mTimeBase = timeBase;
1279 timeBase.add(this);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001280 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001281
Dianne Hackborn617f8772009-03-31 15:04:46 -07001282 public void writeToParcel(Parcel out) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001283 out.writeInt(mCount.get());
Dianne Hackborn617f8772009-03-31 15:04:46 -07001284 out.writeInt(mLoadedCount);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001285 out.writeInt(mUnpluggedCount);
1286 }
1287
Bookatz8c6f3c52017-05-24 12:00:17 -07001288 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001289 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001290 mUnpluggedCount = mPluggedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001291 }
1292
Bookatz8c6f3c52017-05-24 12:00:17 -07001293 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001294 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001295 mPluggedCount = mCount.get();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001296 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001297
Dianne Hackborn617f8772009-03-31 15:04:46 -07001298 /**
1299 * Writes a possibly null Counter to a Parcel.
1300 *
1301 * @param out the Parcel to be written to.
1302 * @param counter a Counter, or null.
1303 */
Amith Yamasani977e11f2018-02-16 11:29:54 -08001304 public static void writeCounterToParcel(Parcel out, @Nullable Counter counter) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07001305 if (counter == null) {
1306 out.writeInt(0); // indicates null
1307 return;
1308 }
1309 out.writeInt(1); // indicates non-null
1310
1311 counter.writeToParcel(out);
1312 }
1313
Amith Yamasani977e11f2018-02-16 11:29:54 -08001314 /**
1315 * Reads a Counter that was written using {@link #writeCounterToParcel(Parcel, Counter)}.
1316 * @param timeBase the timebase to assign to the Counter
1317 * @param in the parcel to read from
1318 * @return the Counter or null.
1319 */
1320 public static @Nullable Counter readCounterFromParcel(TimeBase timeBase, Parcel in) {
1321 if (in.readInt() == 0) {
1322 return null;
1323 }
1324 return new Counter(timeBase, in);
1325 }
1326
Dianne Hackborn617f8772009-03-31 15:04:46 -07001327 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001328 public int getCountLocked(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001329 int val = mCount.get();
1330 if (which == STATS_SINCE_UNPLUGGED) {
1331 val -= mUnpluggedCount;
1332 } else if (which != STATS_SINCE_CHARGED) {
1333 val -= mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001334 }
1335
1336 return val;
1337 }
1338
1339 public void logState(Printer pw, String prefix) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001340 pw.println(prefix + "mCount=" + mCount.get()
Bookatz8c6f3c52017-05-24 12:00:17 -07001341 + " mLoadedCount=" + mLoadedCount
Dianne Hackborn617f8772009-03-31 15:04:46 -07001342 + " mUnpluggedCount=" + mUnpluggedCount
1343 + " mPluggedCount=" + mPluggedCount);
1344 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001345
Bookatz8c6f3c52017-05-24 12:00:17 -07001346 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1347 public void stepAtomic() {
1348 if (mTimeBase.isRunning()) {
1349 mCount.incrementAndGet();
1350 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001351 }
1352
Bookatz4ebc0642017-05-11 12:21:19 -07001353 void addAtomic(int delta) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001354 if (mTimeBase.isRunning()) {
1355 mCount.addAndGet(delta);
1356 }
Bookatz4ebc0642017-05-11 12:21:19 -07001357 }
1358
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001359 /**
1360 * Clear state of this counter.
1361 */
1362 void reset(boolean detachIfReset) {
1363 mCount.set(0);
Bookatz8c6f3c52017-05-24 12:00:17 -07001364 mLoadedCount = mPluggedCount = mUnpluggedCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001365 if (detachIfReset) {
1366 detach();
1367 }
1368 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001369
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001370 void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001371 mTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001372 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001373
Bookatz8c6f3c52017-05-24 12:00:17 -07001374 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1375 public void writeSummaryFromParcelLocked(Parcel out) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001376 int count = mCount.get();
1377 out.writeInt(count);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001378 }
1379
Bookatz8c6f3c52017-05-24 12:00:17 -07001380 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1381 public void readSummaryFromParcelLocked(Parcel in) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001382 mLoadedCount = in.readInt();
1383 mCount.set(mLoadedCount);
Christopher Tate4cee7252010-03-19 14:50:40 -07001384 mUnpluggedCount = mPluggedCount = mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001385 }
1386 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07001387
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001388 @VisibleForTesting
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001389 public static class LongSamplingCounterArray extends LongCounterArray implements TimeBaseObs {
1390 final TimeBase mTimeBase;
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001391 public long[] mCounts;
1392 public long[] mLoadedCounts;
1393 public long[] mUnpluggedCounts;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001394
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001395 private LongSamplingCounterArray(TimeBase timeBase, Parcel in) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001396 mTimeBase = timeBase;
Sudheer Shankae544d162017-12-28 17:06:20 -08001397 mCounts = in.createLongArray();
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001398 mLoadedCounts = in.createLongArray();
1399 mUnpluggedCounts = in.createLongArray();
1400 timeBase.add(this);
1401 }
1402
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001403 public LongSamplingCounterArray(TimeBase timeBase) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001404 mTimeBase = timeBase;
1405 timeBase.add(this);
1406 }
1407
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001408 private void writeToParcel(Parcel out) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001409 out.writeLongArray(mCounts);
1410 out.writeLongArray(mLoadedCounts);
1411 out.writeLongArray(mUnpluggedCounts);
1412 }
1413
1414 @Override
1415 public void onTimeStarted(long elapsedRealTime, long baseUptime, long baseRealtime) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001416 mUnpluggedCounts = copyArray(mCounts, mUnpluggedCounts);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001417 }
1418
1419 @Override
1420 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001421 }
1422
1423 @Override
1424 public long[] getCountsLocked(int which) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001425 long[] val = copyArray(mCounts, null);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001426 if (which == STATS_SINCE_UNPLUGGED) {
1427 subtract(val, mUnpluggedCounts);
1428 } else if (which != STATS_SINCE_CHARGED) {
1429 subtract(val, mLoadedCounts);
1430 }
1431 return val;
1432 }
1433
1434 @Override
1435 public void logState(Printer pw, String prefix) {
1436 pw.println(prefix + "mCounts=" + Arrays.toString(mCounts)
1437 + " mLoadedCounts=" + Arrays.toString(mLoadedCounts)
Sudheer Shankae544d162017-12-28 17:06:20 -08001438 + " mUnpluggedCounts=" + Arrays.toString(mUnpluggedCounts));
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001439 }
1440
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001441 public void addCountLocked(long[] counts) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001442 addCountLocked(counts, mTimeBase.isRunning());
1443 }
1444
1445 public void addCountLocked(long[] counts, boolean isRunning) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001446 if (counts == null) {
1447 return;
1448 }
Sudheer Shankae544d162017-12-28 17:06:20 -08001449 if (isRunning) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001450 if (mCounts == null) {
1451 mCounts = new long[counts.length];
1452 }
1453 for (int i = 0; i < counts.length; ++i) {
1454 mCounts[i] += counts[i];
1455 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001456 }
1457 }
1458
Sudheer Shankab8ad5942017-08-08 12:16:09 -07001459 public int getSize() {
1460 return mCounts == null ? 0 : mCounts.length;
1461 }
1462
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001463 /**
1464 * Clear state of this counter.
1465 */
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001466 public void reset(boolean detachIfReset) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001467 fillArray(mCounts, 0);
1468 fillArray(mLoadedCounts, 0);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001469 fillArray(mUnpluggedCounts, 0);
1470 if (detachIfReset) {
1471 detach();
1472 }
1473 }
1474
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001475 public void detach() {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001476 mTimeBase.remove(this);
1477 }
1478
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001479 private void writeSummaryToParcelLocked(Parcel out) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001480 out.writeLongArray(mCounts);
1481 }
1482
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001483 private void readSummaryFromParcelLocked(Parcel in) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001484 mCounts = in.createLongArray();
1485 mLoadedCounts = copyArray(mCounts, mLoadedCounts);
1486 mUnpluggedCounts = copyArray(mCounts, mUnpluggedCounts);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001487 }
1488
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001489 public static void writeToParcel(Parcel out, LongSamplingCounterArray counterArray) {
1490 if (counterArray != null) {
1491 out.writeInt(1);
1492 counterArray.writeToParcel(out);
1493 } else {
1494 out.writeInt(0);
1495 }
1496 }
1497
1498 public static LongSamplingCounterArray readFromParcel(Parcel in, TimeBase timeBase) {
1499 if (in.readInt() != 0) {
1500 return new LongSamplingCounterArray(timeBase, in);
1501 } else {
1502 return null;
1503 }
1504 }
1505
1506 public static void writeSummaryToParcelLocked(Parcel out,
1507 LongSamplingCounterArray counterArray) {
1508 if (counterArray != null) {
1509 out.writeInt(1);
1510 counterArray.writeSummaryToParcelLocked(out);
1511 } else {
1512 out.writeInt(0);
1513 }
1514 }
1515
1516 public static LongSamplingCounterArray readSummaryFromParcelLocked(Parcel in,
1517 TimeBase timeBase) {
1518 if (in.readInt() != 0) {
1519 final LongSamplingCounterArray counterArray
1520 = new LongSamplingCounterArray(timeBase);
1521 counterArray.readSummaryFromParcelLocked(in);
1522 return counterArray;
1523 } else {
1524 return null;
1525 }
1526 }
1527
Bookatz8c6f3c52017-05-24 12:00:17 -07001528 private static void fillArray(long[] a, long val) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001529 if (a != null) {
1530 Arrays.fill(a, val);
1531 }
1532 }
1533
Bookatz8c6f3c52017-05-24 12:00:17 -07001534 private static void subtract(@NonNull long[] val, long[] toSubtract) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001535 if (toSubtract == null) {
1536 return;
1537 }
1538 for (int i = 0; i < val.length; i++) {
1539 val[i] -= toSubtract[i];
1540 }
1541 }
1542
Bookatz8c6f3c52017-05-24 12:00:17 -07001543 private static long[] copyArray(long[] src, long[] dest) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001544 if (src == null) {
1545 return null;
1546 } else {
1547 if (dest == null) {
1548 dest = new long[src.length];
1549 }
1550 System.arraycopy(src, 0, dest, 0, src.length);
1551 return dest;
1552 }
1553 }
1554 }
1555
Mike Ma561a8d92018-03-20 18:24:05 -07001556 @VisibleForTesting
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001557 public static class LongSamplingCounter extends LongCounter implements TimeBaseObs {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001558 final TimeBase mTimeBase;
Mike Ma561a8d92018-03-20 18:24:05 -07001559 public long mCount;
1560 public long mCurrentCount;
1561 public long mLoadedCount;
1562 public long mUnpluggedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001563
Mike Ma561a8d92018-03-20 18:24:05 -07001564 public LongSamplingCounter(TimeBase timeBase, Parcel in) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001565 mTimeBase = timeBase;
Sudheer Shankac57729a2018-02-09 15:44:42 -08001566 mCount = in.readLong();
Mike Ma561a8d92018-03-20 18:24:05 -07001567 mCurrentCount = in.readLong();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001568 mLoadedCount = in.readLong();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001569 mUnpluggedCount = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001570 timeBase.add(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001571 }
1572
Mike Ma561a8d92018-03-20 18:24:05 -07001573 public LongSamplingCounter(TimeBase timeBase) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001574 mTimeBase = timeBase;
1575 timeBase.add(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001576 }
1577
1578 public void writeToParcel(Parcel out) {
1579 out.writeLong(mCount);
Mike Ma561a8d92018-03-20 18:24:05 -07001580 out.writeLong(mCurrentCount);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001581 out.writeLong(mLoadedCount);
1582 out.writeLong(mUnpluggedCount);
1583 }
1584
1585 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001586 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Sudheer Shankac57729a2018-02-09 15:44:42 -08001587 mUnpluggedCount = mCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001588 }
1589
1590 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001591 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001592 }
1593
1594 public long getCountLocked(int which) {
Sudheer Shankac57729a2018-02-09 15:44:42 -08001595 long val = mCount;
Dianne Hackborn4590e522014-03-24 13:36:46 -07001596 if (which == STATS_SINCE_UNPLUGGED) {
1597 val -= mUnpluggedCount;
1598 } else if (which != STATS_SINCE_CHARGED) {
1599 val -= mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001600 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001601 return val;
1602 }
1603
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001604 @Override
1605 public void logState(Printer pw, String prefix) {
1606 pw.println(prefix + "mCount=" + mCount
Mike Ma561a8d92018-03-20 18:24:05 -07001607 + " mCurrentCount=" + mCurrentCount
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001608 + " mLoadedCount=" + mLoadedCount
Sudheer Shankac57729a2018-02-09 15:44:42 -08001609 + " mUnpluggedCount=" + mUnpluggedCount);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001610 }
1611
Mike Ma561a8d92018-03-20 18:24:05 -07001612 public void addCountLocked(long count) {
1613 update(mCurrentCount + count, mTimeBase.isRunning());
Sudheer Shankac57729a2018-02-09 15:44:42 -08001614 }
1615
Mike Ma561a8d92018-03-20 18:24:05 -07001616 public void addCountLocked(long count, boolean isRunning) {
1617 update(mCurrentCount + count, isRunning);
1618 }
1619
1620 public void update(long count) {
1621 update(count, mTimeBase.isRunning());
1622 }
1623
1624 public void update(long count, boolean isRunning) {
1625 if (count < mCurrentCount) {
1626 mCurrentCount = 0;
Bookatz8c6f3c52017-05-24 12:00:17 -07001627 }
Mike Ma561a8d92018-03-20 18:24:05 -07001628 if (isRunning) {
1629 mCount += count - mCurrentCount;
1630 }
1631 mCurrentCount = count;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001632 }
1633
1634 /**
1635 * Clear state of this counter.
1636 */
Mike Ma561a8d92018-03-20 18:24:05 -07001637 public void reset(boolean detachIfReset) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001638 mCount = 0;
Sudheer Shankac57729a2018-02-09 15:44:42 -08001639 mLoadedCount = mUnpluggedCount = 0;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001640 if (detachIfReset) {
1641 detach();
1642 }
1643 }
1644
Mike Ma561a8d92018-03-20 18:24:05 -07001645 public void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001646 mTimeBase.remove(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001647 }
1648
Mike Ma561a8d92018-03-20 18:24:05 -07001649 public void writeSummaryFromParcelLocked(Parcel out) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001650 out.writeLong(mCount);
1651 }
1652
Mike Ma561a8d92018-03-20 18:24:05 -07001653 public void readSummaryFromParcelLocked(Parcel in) {
1654 mCount = mUnpluggedCount= mLoadedCount = in.readLong();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001655 }
1656 }
1657
Dianne Hackborn617f8772009-03-31 15:04:46 -07001658 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 * State for keeping track of timing information.
1660 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001661 public static abstract class Timer extends BatteryStats.Timer implements TimeBaseObs {
Joe Onoratoabded112016-02-08 16:49:39 -08001662 protected final Clocks mClocks;
1663 protected final int mType;
1664 protected final TimeBase mTimeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001665
Joe Onoratoabded112016-02-08 16:49:39 -08001666 protected int mCount;
1667 protected int mLoadedCount;
1668 protected int mLastCount;
1669 protected int mUnpluggedCount;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 // Times are in microseconds for better accuracy when dividing by the
1672 // lock count, and are in "battery realtime" units.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001673
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674 /**
1675 * The total time we have accumulated since the start of the original
1676 * boot, to the last time something interesting happened in the
1677 * current run.
1678 */
Joe Onoratoabded112016-02-08 16:49:39 -08001679 protected long mTotalTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 /**
1682 * The total time we loaded for the previous runs. Subtract this from
1683 * mTotalTime to find the time for the current run of the system.
1684 */
Joe Onoratoabded112016-02-08 16:49:39 -08001685 protected long mLoadedTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001686
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 /**
1688 * The run time of the last run of the system, as loaded from the
1689 * saved data.
1690 */
Joe Onoratoabded112016-02-08 16:49:39 -08001691 protected long mLastTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 /**
1694 * The value of mTotalTime when unplug() was last called. Subtract
1695 * this from mTotalTime to find the time since the last unplug from
1696 * power.
1697 */
Joe Onoratoabded112016-02-08 16:49:39 -08001698 protected long mUnpluggedTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001699
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001700 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07001701 * The total time this timer has been running until the latest mark has been set.
1702 * Subtract this from mTotalTime to get the time spent running since the mark was set.
1703 */
Joe Onoratoabded112016-02-08 16:49:39 -08001704 protected long mTimeBeforeMark;
Adam Lesinskie08af192015-03-25 16:42:59 -07001705
1706 /**
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001707 * Constructs from a parcel.
1708 * @param type
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001709 * @param timeBase
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001710 * @param in
1711 */
Joe Onoratoabded112016-02-08 16:49:39 -08001712 public Timer(Clocks clocks, int type, TimeBase timeBase, Parcel in) {
1713 mClocks = clocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 mType = type;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001715 mTimeBase = timeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 mCount = in.readInt();
1718 mLoadedCount = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001719 mLastCount = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720 mUnpluggedCount = in.readInt();
1721 mTotalTime = in.readLong();
1722 mLoadedTime = in.readLong();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001723 mLastTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 mUnpluggedTime = in.readLong();
Adam Lesinskie08af192015-03-25 16:42:59 -07001725 mTimeBeforeMark = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001726 timeBase.add(this);
Dianne Hackborn29325132014-05-21 15:01:03 -07001727 if (DEBUG) Log.i(TAG, "**** READ TIMER #" + mType + ": mTotalTime=" + mTotalTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001728 }
1729
Joe Onoratoabded112016-02-08 16:49:39 -08001730 public Timer(Clocks clocks, int type, TimeBase timeBase) {
1731 mClocks = clocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 mType = type;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001733 mTimeBase = timeBase;
1734 timeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 }
Evan Millarc64edde2009-04-18 12:26:32 -07001736
1737 protected abstract long computeRunTimeLocked(long curBatteryRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001738
Evan Millarc64edde2009-04-18 12:26:32 -07001739 protected abstract int computeCurrentCountLocked();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001740
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001741 /**
1742 * Clear state of this timer. Returns true if the timer is inactive
1743 * so can be completely dropped.
1744 */
Joe Onoratoabded112016-02-08 16:49:39 -08001745 public boolean reset(boolean detachIfReset) {
Adam Lesinskie08af192015-03-25 16:42:59 -07001746 mTotalTime = mLoadedTime = mLastTime = mTimeBeforeMark = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001747 mCount = mLoadedCount = mLastCount = 0;
1748 if (detachIfReset) {
1749 detach();
1750 }
1751 return true;
1752 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001753
Joe Onoratoabded112016-02-08 16:49:39 -08001754 public void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001755 mTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001756 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001757
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001758 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
Dianne Hackborn29325132014-05-21 15:01:03 -07001759 if (DEBUG) Log.i(TAG, "**** WRITING TIMER #" + mType + ": mTotalTime="
1760 + computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)));
Adam Lesinski98f0d462016-04-19 16:46:20 -07001761 out.writeInt(computeCurrentCountLocked());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 out.writeInt(mLoadedCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001763 out.writeInt(mUnpluggedCount);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001764 out.writeLong(computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001765 out.writeLong(mLoadedTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 out.writeLong(mUnpluggedTime);
Adam Lesinskie08af192015-03-25 16:42:59 -07001767 out.writeLong(mTimeBeforeMark);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 }
1769
Adam Lesinskie08af192015-03-25 16:42:59 -07001770 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001771 public void onTimeStarted(long elapsedRealtime, long timeBaseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001772 if (DEBUG && mType < 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001773 Log.v(TAG, "unplug #" + mType + ": realtime=" + baseRealtime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 + " old mUnpluggedTime=" + mUnpluggedTime
1775 + " old mUnpluggedCount=" + mUnpluggedCount);
1776 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001777 mUnpluggedTime = computeRunTimeLocked(baseRealtime);
Adam Lesinski98f0d462016-04-19 16:46:20 -07001778 mUnpluggedCount = computeCurrentCountLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001779 if (DEBUG && mType < 0) {
1780 Log.v(TAG, "unplug #" + mType
1781 + ": new mUnpluggedTime=" + mUnpluggedTime
1782 + " new mUnpluggedCount=" + mUnpluggedCount);
1783 }
1784 }
1785
Adam Lesinskie08af192015-03-25 16:42:59 -07001786 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001787 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Evan Millarc64edde2009-04-18 12:26:32 -07001788 if (DEBUG && mType < 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001789 Log.v(TAG, "plug #" + mType + ": realtime=" + baseRealtime
Evan Millarc64edde2009-04-18 12:26:32 -07001790 + " old mTotalTime=" + mTotalTime);
1791 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001792 mTotalTime = computeRunTimeLocked(baseRealtime);
Evan Millarc64edde2009-04-18 12:26:32 -07001793 mCount = computeCurrentCountLocked();
1794 if (DEBUG && mType < 0) {
1795 Log.v(TAG, "plug #" + mType
1796 + ": new mTotalTime=" + mTotalTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797 }
1798 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001799
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 /**
1801 * Writes a possibly null Timer to a Parcel.
1802 *
1803 * @param out the Parcel to be written to.
1804 * @param timer a Timer, or null.
1805 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001806 public static void writeTimerToParcel(Parcel out, Timer timer, long elapsedRealtimeUs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 if (timer == null) {
1808 out.writeInt(0); // indicates null
1809 return;
1810 }
1811 out.writeInt(1); // indicates non-null
1812
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001813 timer.writeToParcel(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001814 }
1815
1816 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001817 public long getTotalTimeLocked(long elapsedRealtimeUs, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001818 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1819 if (which == STATS_SINCE_UNPLUGGED) {
1820 val -= mUnpluggedTime;
1821 } else if (which != STATS_SINCE_CHARGED) {
1822 val -= mLoadedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001823 }
1824
1825 return val;
1826 }
1827
1828 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001829 public int getCountLocked(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001830 int val = computeCurrentCountLocked();
1831 if (which == STATS_SINCE_UNPLUGGED) {
1832 val -= mUnpluggedCount;
1833 } else if (which != STATS_SINCE_CHARGED) {
1834 val -= mLoadedCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001835 }
1836
1837 return val;
1838 }
1839
Adam Lesinskie08af192015-03-25 16:42:59 -07001840 @Override
1841 public long getTimeSinceMarkLocked(long elapsedRealtimeUs) {
1842 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1843 return val - mTimeBeforeMark;
1844 }
1845
1846 @Override
Dianne Hackborn627bba72009-03-24 22:32:56 -07001847 public void logState(Printer pw, String prefix) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07001848 pw.println(prefix + "mCount=" + mCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001849 + " mLoadedCount=" + mLoadedCount + " mLastCount=" + mLastCount
1850 + " mUnpluggedCount=" + mUnpluggedCount);
Dianne Hackborn627bba72009-03-24 22:32:56 -07001851 pw.println(prefix + "mTotalTime=" + mTotalTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 + " mLoadedTime=" + mLoadedTime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07001853 pw.println(prefix + "mLastTime=" + mLastTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 + " mUnpluggedTime=" + mUnpluggedTime);
Evan Millarc64edde2009-04-18 12:26:32 -07001855 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001856
1857
Joe Onoratoabded112016-02-08 16:49:39 -08001858 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001859 long runTime = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1860 out.writeLong(runTime);
Adam Lesinski98f0d462016-04-19 16:46:20 -07001861 out.writeInt(computeCurrentCountLocked());
Evan Millarc64edde2009-04-18 12:26:32 -07001862 }
1863
Joe Onoratoabded112016-02-08 16:49:39 -08001864 public void readSummaryFromParcelLocked(Parcel in) {
Evan Millarc64edde2009-04-18 12:26:32 -07001865 // Multiply by 1000 for backwards compatibility
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001866 mTotalTime = mLoadedTime = in.readLong();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001867 mLastTime = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001868 mUnpluggedTime = mTotalTime;
1869 mCount = mLoadedCount = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001870 mLastCount = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001871 mUnpluggedCount = mCount;
Adam Lesinskie08af192015-03-25 16:42:59 -07001872
1873 // When reading the summary, we set the mark to be the latest information.
1874 mTimeBeforeMark = mTotalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001875 }
1876 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001877
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001878 /**
1879 * A counter meant to accept monotonically increasing values to its {@link #update(long, int)}
1880 * method. The state of the timer according to its {@link TimeBase} will determine how much
1881 * of the value is recorded.
1882 *
1883 * If the value being recorded resets, {@link #endSample()} can be called in order to
1884 * account for the change. If the value passed in to {@link #update(long, int)} decreased
1885 * between calls, the {@link #endSample()} is automatically called and the new value is
1886 * expected to increase monotonically from that point on.
1887 */
Joe Onoratoabded112016-02-08 16:49:39 -08001888 public static class SamplingTimer extends Timer {
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001889
Evan Millarc64edde2009-04-18 12:26:32 -07001890 /**
1891 * The most recent reported count from /proc/wakelocks.
1892 */
1893 int mCurrentReportedCount;
1894
1895 /**
1896 * The reported count from /proc/wakelocks when unplug() was last
1897 * called.
1898 */
1899 int mUnpluggedReportedCount;
1900
1901 /**
1902 * The most recent reported total_time from /proc/wakelocks.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001903 */
Evan Millarc64edde2009-04-18 12:26:32 -07001904 long mCurrentReportedTotalTime;
1905
1906
1907 /**
1908 * The reported total_time from /proc/wakelocks when unplug() was last
1909 * called.
1910 */
1911 long mUnpluggedReportedTotalTime;
1912
1913 /**
1914 * Whether we are currently in a discharge cycle.
1915 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001916 boolean mTimeBaseRunning;
Evan Millarc64edde2009-04-18 12:26:32 -07001917
1918 /**
1919 * Whether we are currently recording reported values.
1920 */
1921 boolean mTrackingReportedValues;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001922
Evan Millarc64edde2009-04-18 12:26:32 -07001923 /*
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001924 * A sequence counter, incremented once for each update of the stats.
Evan Millarc64edde2009-04-18 12:26:32 -07001925 */
1926 int mUpdateVersion;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001927
Adam Lesinski98f0d462016-04-19 16:46:20 -07001928 @VisibleForTesting
1929 public SamplingTimer(Clocks clocks, TimeBase timeBase, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08001930 super(clocks, 0, timeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -07001931 mCurrentReportedCount = in.readInt();
1932 mUnpluggedReportedCount = in.readInt();
1933 mCurrentReportedTotalTime = in.readLong();
1934 mUnpluggedReportedTotalTime = in.readLong();
1935 mTrackingReportedValues = in.readInt() == 1;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001936 mTimeBaseRunning = timeBase.isRunning();
Evan Millarc64edde2009-04-18 12:26:32 -07001937 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001938
Adam Lesinski98f0d462016-04-19 16:46:20 -07001939 @VisibleForTesting
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001940 public SamplingTimer(Clocks clocks, TimeBase timeBase) {
Joe Onoratoabded112016-02-08 16:49:39 -08001941 super(clocks, 0, timeBase);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001942 mTrackingReportedValues = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001943 mTimeBaseRunning = timeBase.isRunning();
Evan Millarc64edde2009-04-18 12:26:32 -07001944 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001945
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001946 /**
1947 * Ends the current sample, allowing subsequent values to {@link #update(long, int)} to
1948 * be less than the values used for a previous invocation.
1949 */
1950 public void endSample() {
1951 mTotalTime = computeRunTimeLocked(0 /* unused by us */);
1952 mCount = computeCurrentCountLocked();
1953 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime = 0;
1954 mUnpluggedReportedCount = mCurrentReportedCount = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001955 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001956
Evan Millarc64edde2009-04-18 12:26:32 -07001957 public void setUpdateVersion(int version) {
1958 mUpdateVersion = version;
1959 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001960
Evan Millarc64edde2009-04-18 12:26:32 -07001961 public int getUpdateVersion() {
1962 return mUpdateVersion;
1963 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001964
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001965 /**
1966 * Updates the current recorded values. These are meant to be monotonically increasing
1967 * and cumulative. If you are dealing with deltas, use {@link #add(long, int)}.
1968 *
1969 * If the values being recorded have been reset, the monotonically increasing requirement
1970 * will be broken. In this case, {@link #endSample()} is automatically called and
1971 * the total value of totalTime and count are recorded, starting a new monotonically
1972 * increasing sample.
1973 *
1974 * @param totalTime total time of sample in microseconds.
1975 * @param count total number of times the event being sampled occurred.
1976 */
1977 public void update(long totalTime, int count) {
1978 if (mTimeBaseRunning && !mTrackingReportedValues) {
Evan Millarc64edde2009-04-18 12:26:32 -07001979 // Updating the reported value for the first time.
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001980 mUnpluggedReportedTotalTime = totalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001981 mUnpluggedReportedCount = count;
Evan Millarc64edde2009-04-18 12:26:32 -07001982 }
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001983
1984 mTrackingReportedValues = true;
1985
1986 if (totalTime < mCurrentReportedTotalTime || count < mCurrentReportedCount) {
1987 endSample();
1988 }
1989
1990 mCurrentReportedTotalTime = totalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001991 mCurrentReportedCount = count;
1992 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001993
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001994 /**
1995 * Adds deltaTime and deltaCount to the current sample.
1996 *
1997 * @param deltaTime additional time recorded since the last sampled event, in microseconds.
1998 * @param deltaCount additional number of times the event being sampled occurred.
1999 */
2000 public void add(long deltaTime, int deltaCount) {
2001 update(mCurrentReportedTotalTime + deltaTime, mCurrentReportedCount + deltaCount);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002002 }
2003
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002004 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002005 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
2006 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime);
Evan Millarc64edde2009-04-18 12:26:32 -07002007 if (mTrackingReportedValues) {
2008 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime;
2009 mUnpluggedReportedCount = mCurrentReportedCount;
2010 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002011 mTimeBaseRunning = true;
Evan Millarc64edde2009-04-18 12:26:32 -07002012 }
2013
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002014 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002015 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
2016 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
2017 mTimeBaseRunning = false;
Evan Millarc64edde2009-04-18 12:26:32 -07002018 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002019
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002020 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07002021 public void logState(Printer pw, String prefix) {
2022 super.logState(pw, prefix);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002023 pw.println(prefix + "mCurrentReportedCount=" + mCurrentReportedCount
Evan Millarc64edde2009-04-18 12:26:32 -07002024 + " mUnpluggedReportedCount=" + mUnpluggedReportedCount
2025 + " mCurrentReportedTotalTime=" + mCurrentReportedTotalTime
2026 + " mUnpluggedReportedTotalTime=" + mUnpluggedReportedTotalTime);
2027 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002028
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002029 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07002030 protected long computeRunTimeLocked(long curBatteryRealtime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002031 return mTotalTime + (mTimeBaseRunning && mTrackingReportedValues
Evan Millarc64edde2009-04-18 12:26:32 -07002032 ? mCurrentReportedTotalTime - mUnpluggedReportedTotalTime : 0);
2033 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002034
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002035 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07002036 protected int computeCurrentCountLocked() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002037 return mCount + (mTimeBaseRunning && mTrackingReportedValues
Evan Millarc64edde2009-04-18 12:26:32 -07002038 ? mCurrentReportedCount - mUnpluggedReportedCount : 0);
2039 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002040
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002041 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002042 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2043 super.writeToParcel(out, elapsedRealtimeUs);
Evan Millarc64edde2009-04-18 12:26:32 -07002044 out.writeInt(mCurrentReportedCount);
2045 out.writeInt(mUnpluggedReportedCount);
2046 out.writeLong(mCurrentReportedTotalTime);
2047 out.writeLong(mUnpluggedReportedTotalTime);
2048 out.writeInt(mTrackingReportedValues ? 1 : 0);
2049 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002050
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002051 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002052 public boolean reset(boolean detachIfReset) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002053 super.reset(detachIfReset);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002054 mTrackingReportedValues = false;
2055 mUnpluggedReportedTotalTime = 0;
2056 mUnpluggedReportedCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002057 return true;
2058 }
Evan Millarc64edde2009-04-18 12:26:32 -07002059 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002060
Evan Millarc64edde2009-04-18 12:26:32 -07002061 /**
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002062 * A timer that increments in batches. It does not run for durations, but just jumps
2063 * for a pre-determined amount.
2064 */
Joe Onoratoabded112016-02-08 16:49:39 -08002065 public static class BatchTimer extends Timer {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002066 final Uid mUid;
2067
2068 /**
2069 * The last time at which we updated the timer. This is in elapsed realtime microseconds.
2070 */
2071 long mLastAddedTime;
2072
2073 /**
2074 * The last duration that we added to the timer. This is in microseconds.
2075 */
2076 long mLastAddedDuration;
2077
2078 /**
2079 * Whether we are currently in a discharge cycle.
2080 */
2081 boolean mInDischarge;
2082
Joe Onoratoabded112016-02-08 16:49:39 -08002083 BatchTimer(Clocks clocks, Uid uid, int type, TimeBase timeBase, Parcel in) {
2084 super(clocks, type, timeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002085 mUid = uid;
2086 mLastAddedTime = in.readLong();
2087 mLastAddedDuration = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002088 mInDischarge = timeBase.isRunning();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002089 }
2090
Joe Onoratoabded112016-02-08 16:49:39 -08002091 BatchTimer(Clocks clocks, Uid uid, int type, TimeBase timeBase) {
2092 super(clocks, type, timeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002093 mUid = uid;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002094 mInDischarge = timeBase.isRunning();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002095 }
2096
2097 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002098 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2099 super.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002100 out.writeLong(mLastAddedTime);
2101 out.writeLong(mLastAddedDuration);
2102 }
2103
2104 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002105 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Joe Onoratoabded112016-02-08 16:49:39 -08002106 recomputeLastDuration(mClocks.elapsedRealtime() * 1000, false);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002107 mInDischarge = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002108 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002109 }
2110
2111 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002112 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002113 recomputeLastDuration(elapsedRealtime, false);
2114 mInDischarge = true;
2115 // If we are still within the last added duration, then re-added whatever remains.
2116 if (mLastAddedTime == elapsedRealtime) {
2117 mTotalTime += mLastAddedDuration;
2118 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002119 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002120 }
2121
2122 @Override
2123 public void logState(Printer pw, String prefix) {
2124 super.logState(pw, prefix);
2125 pw.println(prefix + "mLastAddedTime=" + mLastAddedTime
2126 + " mLastAddedDuration=" + mLastAddedDuration);
2127 }
2128
2129 private long computeOverage(long curTime) {
2130 if (mLastAddedTime > 0) {
2131 return mLastTime + mLastAddedDuration - curTime;
2132 }
2133 return 0;
2134 }
2135
2136 private void recomputeLastDuration(long curTime, boolean abort) {
2137 final long overage = computeOverage(curTime);
2138 if (overage > 0) {
2139 // Aborting before the duration ran out -- roll back the remaining
2140 // duration. Only do this if currently discharging; otherwise we didn't
2141 // actually add the time.
2142 if (mInDischarge) {
2143 mTotalTime -= overage;
2144 }
2145 if (abort) {
2146 mLastAddedTime = 0;
2147 } else {
2148 mLastAddedTime = curTime;
2149 mLastAddedDuration -= overage;
2150 }
2151 }
2152 }
2153
2154 public void addDuration(BatteryStatsImpl stats, long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08002155 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002156 recomputeLastDuration(now, true);
2157 mLastAddedTime = now;
2158 mLastAddedDuration = durationMillis * 1000;
2159 if (mInDischarge) {
2160 mTotalTime += mLastAddedDuration;
2161 mCount++;
2162 }
2163 }
2164
2165 public void abortLastDuration(BatteryStatsImpl stats) {
Joe Onoratoabded112016-02-08 16:49:39 -08002166 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002167 recomputeLastDuration(now, true);
2168 }
2169
2170 @Override
2171 protected int computeCurrentCountLocked() {
2172 return mCount;
2173 }
2174
2175 @Override
2176 protected long computeRunTimeLocked(long curBatteryRealtime) {
Joe Onoratoabded112016-02-08 16:49:39 -08002177 final long overage = computeOverage(mClocks.elapsedRealtime() * 1000);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002178 if (overage > 0) {
2179 return mTotalTime = overage;
2180 }
2181 return mTotalTime;
2182 }
2183
2184 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002185 public boolean reset(boolean detachIfReset) {
2186 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002187 recomputeLastDuration(now, true);
2188 boolean stillActive = mLastAddedTime == now;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002189 super.reset(!stillActive && detachIfReset);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002190 return !stillActive;
2191 }
2192 }
2193
Joe Onorato92fd23f2016-07-25 11:18:42 -07002194
2195 /**
2196 * A StopwatchTimer that also tracks the total and max individual
2197 * time spent active according to the given timebase. Whereas
2198 * StopwatchTimer apportions the time amongst all in the pool,
2199 * the total and max durations are not apportioned.
2200 */
2201 public static class DurationTimer extends StopwatchTimer {
2202 /**
2203 * The time (in ms) that the timer was last acquired or the time base
2204 * last (re-)started. Increasing the nesting depth does not reset this time.
2205 *
2206 * -1 if the timer is currently not running or the time base is not running.
2207 *
2208 * If written to a parcel, the start time is reset, as is mNesting in the base class
2209 * StopwatchTimer.
2210 */
2211 long mStartTimeMs = -1;
2212
2213 /**
Bookatz867c0d72017-03-07 18:23:42 -08002214 * The longest time period (in ms) that the timer has been active. Not pooled.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002215 */
2216 long mMaxDurationMs;
2217
2218 /**
Bookatz867c0d72017-03-07 18:23:42 -08002219 * The time (in ms) that that the timer has been active since most recent
2220 * stopRunningLocked() or reset(). Not pooled.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002221 */
2222 long mCurrentDurationMs;
2223
Bookatz867c0d72017-03-07 18:23:42 -08002224 /**
2225 * The total time (in ms) that that the timer has been active since most recent reset()
2226 * prior to the current startRunningLocked. This is the sum of all past currentDurations
2227 * (but not including the present currentDuration) since reset. Not pooled.
2228 */
2229 long mTotalDurationMs;
2230
Joe Onorato92fd23f2016-07-25 11:18:42 -07002231 public DurationTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2232 TimeBase timeBase, Parcel in) {
2233 super(clocks, uid, type, timerPool, timeBase, in);
2234 mMaxDurationMs = in.readLong();
Bookatz867c0d72017-03-07 18:23:42 -08002235 mTotalDurationMs = in.readLong();
jackqdyulei610a0a02017-08-09 14:02:01 -07002236 mCurrentDurationMs = in.readLong();
Joe Onorato92fd23f2016-07-25 11:18:42 -07002237 }
2238
2239 public DurationTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2240 TimeBase timeBase) {
2241 super(clocks, uid, type, timerPool, timeBase);
2242 }
2243
2244 @Override
2245 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2246 super.writeToParcel(out, elapsedRealtimeUs);
Kweku Adams47db5a82016-12-09 19:04:50 -08002247 out.writeLong(getMaxDurationMsLocked(elapsedRealtimeUs / 1000));
jackqdyulei610a0a02017-08-09 14:02:01 -07002248 out.writeLong(mTotalDurationMs);
2249 out.writeLong(getCurrentDurationMsLocked(elapsedRealtimeUs / 1000));
Joe Onorato92fd23f2016-07-25 11:18:42 -07002250 }
2251
2252 /**
2253 * Write the summary to the parcel.
2254 *
2255 * Since the time base is probably meaningless after we come back, reading
2256 * from this will have the effect of stopping the timer. So here all we write
Bookatz867c0d72017-03-07 18:23:42 -08002257 * is the max and total durations.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002258 */
2259 @Override
2260 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
2261 super.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
Kweku Adams47db5a82016-12-09 19:04:50 -08002262 out.writeLong(getMaxDurationMsLocked(elapsedRealtimeUs / 1000));
Bookatz867c0d72017-03-07 18:23:42 -08002263 out.writeLong(getTotalDurationMsLocked(elapsedRealtimeUs / 1000));
Joe Onorato92fd23f2016-07-25 11:18:42 -07002264 }
2265
2266 /**
2267 * Read the summary parcel.
2268 *
2269 * Has the side effect of stopping the timer.
2270 */
2271 @Override
2272 public void readSummaryFromParcelLocked(Parcel in) {
2273 super.readSummaryFromParcelLocked(in);
2274 mMaxDurationMs = in.readLong();
Bookatz867c0d72017-03-07 18:23:42 -08002275 mTotalDurationMs = in.readLong();
Joe Onorato92fd23f2016-07-25 11:18:42 -07002276 mStartTimeMs = -1;
2277 mCurrentDurationMs = 0;
2278 }
2279
2280 /**
2281 * The TimeBase time started (again).
2282 *
2283 * If the timer is also running, store the start time.
2284 */
2285 public void onTimeStarted(long elapsedRealtimeUs, long baseUptime, long baseRealtime) {
2286 super.onTimeStarted(elapsedRealtimeUs, baseUptime, baseRealtime);
2287 if (mNesting > 0) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002288 mStartTimeMs = baseRealtime / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002289 }
2290 }
2291
2292 /**
2293 * The TimeBase stopped running.
2294 *
2295 * If the timer is running, add the duration into mCurrentDurationMs.
2296 */
2297 @Override
Kweku Adams47db5a82016-12-09 19:04:50 -08002298 public void onTimeStopped(long elapsedRealtimeUs, long baseUptime, long baseRealtimeUs) {
2299 super.onTimeStopped(elapsedRealtimeUs, baseUptime, baseRealtimeUs);
Joe Onorato92fd23f2016-07-25 11:18:42 -07002300 if (mNesting > 0) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002301 // baseRealtimeUs has already been converted to the timebase's realtime.
2302 mCurrentDurationMs += (baseRealtimeUs / 1000) - mStartTimeMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002303 }
2304 mStartTimeMs = -1;
2305 }
2306
2307 @Override
2308 public void logState(Printer pw, String prefix) {
2309 super.logState(pw, prefix);
2310 }
2311
2312 @Override
2313 public void startRunningLocked(long elapsedRealtimeMs) {
2314 super.startRunningLocked(elapsedRealtimeMs);
2315 if (mNesting == 1 && mTimeBase.isRunning()) {
2316 // Just started
Kweku Adams47db5a82016-12-09 19:04:50 -08002317 mStartTimeMs = mTimeBase.getRealtime(elapsedRealtimeMs * 1000) / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002318 }
2319 }
2320
2321 /**
2322 * Decrements the mNesting ref-count on this timer.
2323 *
2324 * If it actually stopped (mNesting went to 0), then possibly update
2325 * mMaxDuration if the current duration was the longest ever.
2326 */
2327 @Override
2328 public void stopRunningLocked(long elapsedRealtimeMs) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002329 if (mNesting == 1) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07002330 final long durationMs = getCurrentDurationMsLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002331 mTotalDurationMs += durationMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002332 if (durationMs > mMaxDurationMs) {
2333 mMaxDurationMs = durationMs;
2334 }
2335 mStartTimeMs = -1;
2336 mCurrentDurationMs = 0;
2337 }
Kweku Adams47db5a82016-12-09 19:04:50 -08002338 // super method decrements mNesting, which getCurrentDurationMsLocked relies on,
2339 // so call super.stopRunningLocked after calling getCurrentDurationMsLocked.
2340 super.stopRunningLocked(elapsedRealtimeMs);
Joe Onorato92fd23f2016-07-25 11:18:42 -07002341 }
2342
2343 @Override
2344 public boolean reset(boolean detachIfReset) {
2345 boolean result = super.reset(detachIfReset);
2346 mMaxDurationMs = 0;
Bookatz867c0d72017-03-07 18:23:42 -08002347 mTotalDurationMs = 0;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002348 mCurrentDurationMs = 0;
2349 if (mNesting > 0) {
2350 mStartTimeMs = mTimeBase.getRealtime(mClocks.elapsedRealtime()*1000) / 1000;
2351 } else {
2352 mStartTimeMs = -1;
2353 }
2354 return result;
2355 }
2356
2357 /**
2358 * Returns the max duration that this timer has ever seen.
2359 *
2360 * Note that this time is NOT split between the timers in the timer group that
2361 * this timer is attached to. It is the TOTAL time.
2362 */
2363 @Override
2364 public long getMaxDurationMsLocked(long elapsedRealtimeMs) {
2365 if (mNesting > 0) {
2366 final long durationMs = getCurrentDurationMsLocked(elapsedRealtimeMs);
2367 if (durationMs > mMaxDurationMs) {
2368 return durationMs;
2369 }
2370 }
2371 return mMaxDurationMs;
2372 }
2373
2374 /**
2375 * Returns the time since the timer was started.
Bookatz867c0d72017-03-07 18:23:42 -08002376 * Returns 0 if the timer is not currently running.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002377 *
2378 * Note that this time is NOT split between the timers in the timer group that
2379 * this timer is attached to. It is the TOTAL time.
jackqdyulei610a0a02017-08-09 14:02:01 -07002380 *
2381 * Note that if running timer is parceled and unparceled, this method will return
2382 * current duration value at the time of parceling even though timer may not be
2383 * currently running.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002384 */
2385 @Override
2386 public long getCurrentDurationMsLocked(long elapsedRealtimeMs) {
2387 long durationMs = mCurrentDurationMs;
Kweku Adams47db5a82016-12-09 19:04:50 -08002388 if (mNesting > 0 && mTimeBase.isRunning()) {
2389 durationMs += (mTimeBase.getRealtime(elapsedRealtimeMs*1000)/1000)
2390 - mStartTimeMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002391 }
2392 return durationMs;
2393 }
Bookatz867c0d72017-03-07 18:23:42 -08002394
2395 /**
2396 * Returns the total cumulative duration that this timer has been on since reset().
2397 * If mTimerPool == null, this should be the same
2398 * as getTotalTimeLocked(elapsedRealtimeMs*1000, STATS_SINCE_CHARGED)/1000.
2399 *
2400 * Note that this time is NOT split between the timers in the timer group that
2401 * this timer is attached to. It is the TOTAL time. For this reason, if mTimerPool != null,
2402 * the result will not be equivalent to getTotalTimeLocked.
2403 */
2404 @Override
2405 public long getTotalDurationMsLocked(long elapsedRealtimeMs) {
2406 return mTotalDurationMs + getCurrentDurationMsLocked(elapsedRealtimeMs);
2407 }
Joe Onorato92fd23f2016-07-25 11:18:42 -07002408 }
2409
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002410 /**
Evan Millarc64edde2009-04-18 12:26:32 -07002411 * State for keeping track of timing information.
2412 */
Joe Onoratoabded112016-02-08 16:49:39 -08002413 public static class StopwatchTimer extends Timer {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002414 final Uid mUid;
Evan Millarc64edde2009-04-18 12:26:32 -07002415 final ArrayList<StopwatchTimer> mTimerPool;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002416
Evan Millarc64edde2009-04-18 12:26:32 -07002417 int mNesting;
2418
Evan Millarc64edde2009-04-18 12:26:32 -07002419 /**
2420 * The last time at which we updated the timer. If mNesting is > 0,
2421 * subtract this from the current battery time to find the amount of
2422 * time we have been running since we last computed an update.
2423 */
2424 long mUpdateTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002425
Evan Millarc64edde2009-04-18 12:26:32 -07002426 /**
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002427 * The total time at which the timer was acquired, to determine if it
Bookatzceebafe2017-04-06 11:59:13 -07002428 * was actually held for an interesting duration. If time base was not running when timer
2429 * was acquired, will be -1.
Evan Millarc64edde2009-04-18 12:26:32 -07002430 */
Bookatzceebafe2017-04-06 11:59:13 -07002431 long mAcquireTime = -1;
Evan Millarc64edde2009-04-18 12:26:32 -07002432
Amith Yamasanif37447b2009-10-08 18:28:01 -07002433 long mTimeout;
2434
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002435 /**
2436 * For partial wake locks, keep track of whether we are in the list
2437 * to consume CPU cycles.
2438 */
Sudheer Shanka38383232017-07-25 09:55:03 -07002439 @VisibleForTesting
2440 public boolean mInList;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002441
Joe Onoratoabded112016-02-08 16:49:39 -08002442 public StopwatchTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002443 TimeBase timeBase, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08002444 super(clocks, type, timeBase, in);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002445 mUid = uid;
Evan Millarc64edde2009-04-18 12:26:32 -07002446 mTimerPool = timerPool;
2447 mUpdateTime = in.readLong();
2448 }
2449
Joe Onoratoabded112016-02-08 16:49:39 -08002450 public StopwatchTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002451 TimeBase timeBase) {
Joe Onoratoabded112016-02-08 16:49:39 -08002452 super(clocks, type, timeBase);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002453 mUid = uid;
Evan Millarc64edde2009-04-18 12:26:32 -07002454 mTimerPool = timerPool;
2455 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002456
Joe Onoratoabded112016-02-08 16:49:39 -08002457 public void setTimeout(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07002458 mTimeout = timeout;
2459 }
2460
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002461 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2462 super.writeToParcel(out, elapsedRealtimeUs);
Evan Millarc64edde2009-04-18 12:26:32 -07002463 out.writeLong(mUpdateTime);
2464 }
2465
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002466 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Evan Millarc64edde2009-04-18 12:26:32 -07002467 if (mNesting > 0) {
2468 if (DEBUG && mType < 0) {
2469 Log.v(TAG, "old mUpdateTime=" + mUpdateTime);
2470 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002471 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
2472 mUpdateTime = baseRealtime;
Evan Millarc64edde2009-04-18 12:26:32 -07002473 if (DEBUG && mType < 0) {
2474 Log.v(TAG, "new mUpdateTime=" + mUpdateTime);
2475 }
2476 }
2477 }
2478
2479 public void logState(Printer pw, String prefix) {
2480 super.logState(pw, prefix);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07002481 pw.println(prefix + "mNesting=" + mNesting + " mUpdateTime=" + mUpdateTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002482 + " mAcquireTime=" + mAcquireTime);
2483 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002484
Joe Onoratoabded112016-02-08 16:49:39 -08002485 public void startRunningLocked(long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002486 if (mNesting++ == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002487 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002488 mUpdateTime = batteryRealtime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002489 if (mTimerPool != null) {
2490 // Accumulate time to all currently active timers before adding
2491 // this new one to the pool.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002492 refreshTimersLocked(batteryRealtime, mTimerPool, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002493 // Add this timer to the active pool
2494 mTimerPool.add(this);
2495 }
Bookatzceebafe2017-04-06 11:59:13 -07002496 if (mTimeBase.isRunning()) {
2497 // Increment the count
2498 mCount++;
2499 mAcquireTime = mTotalTime;
2500 } else {
2501 mAcquireTime = -1;
2502 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002503 if (DEBUG && mType < 0) {
2504 Log.v(TAG, "start #" + mType + ": mUpdateTime=" + mUpdateTime
2505 + " mTotalTime=" + mTotalTime + " mCount=" + mCount
2506 + " mAcquireTime=" + mAcquireTime);
2507 }
2508 }
2509 }
2510
Joe Onoratoabded112016-02-08 16:49:39 -08002511 public boolean isRunningLocked() {
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002512 return mNesting > 0;
2513 }
2514
Joe Onoratoabded112016-02-08 16:49:39 -08002515 public void stopRunningLocked(long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 // Ignore attempt to stop a timer that isn't running
2517 if (mNesting == 0) {
2518 return;
2519 }
2520 if (--mNesting == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002521 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002522 if (mTimerPool != null) {
2523 // Accumulate time to all active counters, scaled by the total
2524 // active in the pool, before taking this one out of the pool.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002525 refreshTimersLocked(batteryRealtime, mTimerPool, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002526 // Remove this timer from the active pool
2527 mTimerPool.remove(this);
2528 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529 mNesting = 1;
2530 mTotalTime = computeRunTimeLocked(batteryRealtime);
2531 mNesting = 0;
2532 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 if (DEBUG && mType < 0) {
2535 Log.v(TAG, "stop #" + mType + ": mUpdateTime=" + mUpdateTime
2536 + " mTotalTime=" + mTotalTime + " mCount=" + mCount
2537 + " mAcquireTime=" + mAcquireTime);
2538 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002539
Bookatzceebafe2017-04-06 11:59:13 -07002540 if (mAcquireTime >= 0 && mTotalTime == mAcquireTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002541 // If there was no change in the time, then discard this
2542 // count. A somewhat cheezy strategy, but hey.
2543 mCount--;
2544 }
2545 }
2546 }
2547
Joe Onoratoabded112016-02-08 16:49:39 -08002548 public void stopAllRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07002549 if (mNesting > 0) {
2550 mNesting = 1;
2551 stopRunningLocked(elapsedRealtimeMs);
2552 }
2553 }
2554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002555 // Update the total time for all other running Timers with the same type as this Timer
2556 // due to a change in timer count
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002557 private static long refreshTimersLocked(long batteryRealtime,
2558 final ArrayList<StopwatchTimer> pool, StopwatchTimer self) {
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002559 long selfTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002560 final int N = pool.size();
2561 for (int i=N-1; i>= 0; i--) {
Evan Millarc64edde2009-04-18 12:26:32 -07002562 final StopwatchTimer t = pool.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002563 long heldTime = batteryRealtime - t.mUpdateTime;
2564 if (heldTime > 0) {
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002565 final long myTime = heldTime / N;
2566 if (t == self) {
2567 selfTime = myTime;
2568 }
2569 t.mTotalTime += myTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002570 }
2571 t.mUpdateTime = batteryRealtime;
2572 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002573 return selfTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 }
2575
Evan Millarc64edde2009-04-18 12:26:32 -07002576 @Override
2577 protected long computeRunTimeLocked(long curBatteryRealtime) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07002578 if (mTimeout > 0 && curBatteryRealtime > mUpdateTime + mTimeout) {
2579 curBatteryRealtime = mUpdateTime + mTimeout;
2580 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002581 return mTotalTime + (mNesting > 0
2582 ? (curBatteryRealtime - mUpdateTime)
2583 / (mTimerPool != null ? mTimerPool.size() : 1)
2584 : 0);
2585 }
2586
Evan Millarc64edde2009-04-18 12:26:32 -07002587 @Override
2588 protected int computeCurrentCountLocked() {
2589 return mCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002590 }
2591
Adam Lesinskie08af192015-03-25 16:42:59 -07002592 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002593 public boolean reset(boolean detachIfReset) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002594 boolean canDetach = mNesting <= 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002595 super.reset(canDetach && detachIfReset);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002596 if (mNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08002597 mUpdateTime = mTimeBase.getRealtime(mClocks.elapsedRealtime() * 1000);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002598 }
Bookatzceebafe2017-04-06 11:59:13 -07002599 mAcquireTime = -1; // to ensure mCount isn't decreased to -1 if timer is stopped later.
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002600 return canDetach;
2601 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002602
Adam Lesinskie08af192015-03-25 16:42:59 -07002603 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002604 public void detach() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002605 super.detach();
2606 if (mTimerPool != null) {
2607 mTimerPool.remove(this);
2608 }
2609 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002610
Adam Lesinskie08af192015-03-25 16:42:59 -07002611 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002612 public void readSummaryFromParcelLocked(Parcel in) {
Evan Millarc64edde2009-04-18 12:26:32 -07002613 super.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002614 mNesting = 0;
2615 }
Adam Lesinskie08af192015-03-25 16:42:59 -07002616
2617 /**
2618 * Set the mark so that we can query later for the total time the timer has
2619 * accumulated since this point. The timer can be running or not.
2620 *
2621 * @param elapsedRealtimeMs the current elapsed realtime in milliseconds.
2622 */
2623 public void setMark(long elapsedRealtimeMs) {
2624 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
2625 if (mNesting > 0) {
2626 // We are running.
2627 if (mTimerPool != null) {
2628 refreshTimersLocked(batteryRealtime, mTimerPool, this);
2629 } else {
2630 mTotalTime += batteryRealtime - mUpdateTime;
2631 mUpdateTime = batteryRealtime;
2632 }
2633 }
2634 mTimeBeforeMark = mTotalTime;
2635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002636 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002637
Bookatz867c0d72017-03-07 18:23:42 -08002638 /**
2639 * State for keeping track of two DurationTimers with different TimeBases, presumably where one
2640 * TimeBase is effectively a subset of the other.
2641 */
Bookatzaa4594a2017-03-24 12:39:56 -07002642 public static class DualTimer extends DurationTimer {
2643 // This class both is a DurationTimer and also holds a second DurationTimer.
2644 // The main timer (this) typically tracks the total time. It may be pooled (but since it's a
2645 // durationTimer, it also has the unpooled getTotalDurationMsLocked() for
2646 // STATS_SINCE_CHARGED).
Bookatz867c0d72017-03-07 18:23:42 -08002647 // mSubTimer typically tracks only part of the total time, such as background time, as
2648 // determined by a subTimeBase. It is NOT pooled.
2649 private final DurationTimer mSubTimer;
2650
2651 /**
Bookatzaa4594a2017-03-24 12:39:56 -07002652 * Creates a DualTimer to hold a main timer (this) and a mSubTimer.
2653 * The main timer (this) is based on the given timeBase and timerPool.
Bookatz867c0d72017-03-07 18:23:42 -08002654 * The mSubTimer is based on the given subTimeBase. The mSubTimer is not pooled, even if
Bookatzaa4594a2017-03-24 12:39:56 -07002655 * the main timer is.
Bookatz867c0d72017-03-07 18:23:42 -08002656 */
2657 public DualTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2658 TimeBase timeBase, TimeBase subTimeBase, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07002659 super(clocks, uid, type, timerPool, timeBase, in);
Bookatz867c0d72017-03-07 18:23:42 -08002660 mSubTimer = new DurationTimer(clocks, uid, type, null, subTimeBase, in);
2661 }
2662
2663 /**
Bookatzaa4594a2017-03-24 12:39:56 -07002664 * Creates a DualTimer to hold a main timer (this) and a mSubTimer.
2665 * The main timer (this) is based on the given timeBase and timerPool.
Bookatz867c0d72017-03-07 18:23:42 -08002666 * The mSubTimer is based on the given subTimeBase. The mSubTimer is not pooled, even if
Bookatzaa4594a2017-03-24 12:39:56 -07002667 * the main timer is.
Bookatz867c0d72017-03-07 18:23:42 -08002668 */
2669 public DualTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2670 TimeBase timeBase, TimeBase subTimeBase) {
Bookatzaa4594a2017-03-24 12:39:56 -07002671 super(clocks, uid, type, timerPool, timeBase);
Bookatz867c0d72017-03-07 18:23:42 -08002672 mSubTimer = new DurationTimer(clocks, uid, type, null, subTimeBase);
2673 }
2674
Bookatz867c0d72017-03-07 18:23:42 -08002675 /** Get the secondary timer. */
Bookatzaa4594a2017-03-24 12:39:56 -07002676 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002677 public DurationTimer getSubTimer() {
2678 return mSubTimer;
2679 }
2680
Bookatzaa4594a2017-03-24 12:39:56 -07002681 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002682 public void startRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002683 super.startRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002684 mSubTimer.startRunningLocked(elapsedRealtimeMs);
2685 }
2686
Bookatzaa4594a2017-03-24 12:39:56 -07002687 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002688 public void stopRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002689 super.stopRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002690 mSubTimer.stopRunningLocked(elapsedRealtimeMs);
2691 }
2692
Bookatzaa4594a2017-03-24 12:39:56 -07002693 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002694 public void stopAllRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002695 super.stopAllRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002696 mSubTimer.stopAllRunningLocked(elapsedRealtimeMs);
2697 }
2698
Bookatzaa4594a2017-03-24 12:39:56 -07002699 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002700 public boolean reset(boolean detachIfReset) {
2701 boolean active = false;
Bookatz4a3eda92017-04-10 13:10:46 -07002702 // Do not detach the subTimer explicitly since that'll be done by DualTimer.detach().
2703 active |= !mSubTimer.reset(false);
Bookatzaa4594a2017-03-24 12:39:56 -07002704 active |= !super.reset(detachIfReset);
Bookatz867c0d72017-03-07 18:23:42 -08002705 return !active;
2706 }
2707
Bookatzaa4594a2017-03-24 12:39:56 -07002708 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002709 public void detach() {
Bookatz867c0d72017-03-07 18:23:42 -08002710 mSubTimer.detach();
Bookatz4a3eda92017-04-10 13:10:46 -07002711 super.detach();
Bookatz867c0d72017-03-07 18:23:42 -08002712 }
2713
Bookatzaa4594a2017-03-24 12:39:56 -07002714 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002715 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002716 super.writeToParcel(out, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08002717 mSubTimer.writeToParcel(out, elapsedRealtimeUs);
2718 }
2719
Bookatzaa4594a2017-03-24 12:39:56 -07002720 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002721 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002722 super.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08002723 mSubTimer.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
2724 }
2725
Bookatzaa4594a2017-03-24 12:39:56 -07002726 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002727 public void readSummaryFromParcelLocked(Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07002728 super.readSummaryFromParcelLocked(in);
Bookatz867c0d72017-03-07 18:23:42 -08002729 mSubTimer.readSummaryFromParcelLocked(in);
2730 }
2731 }
2732
2733
Dianne Hackbornd953c532014-08-16 18:17:38 -07002734 public abstract class OverflowArrayMap<T> {
2735 private static final String OVERFLOW_NAME = "*overflow*";
2736
Dianne Hackborn657153b2016-07-29 14:54:14 -07002737 final int mUid;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002738 final ArrayMap<String, T> mMap = new ArrayMap<>();
2739 T mCurOverflow;
2740 ArrayMap<String, MutableInt> mActiveOverflow;
Dianne Hackborn657153b2016-07-29 14:54:14 -07002741 long mLastOverflowTime;
2742 long mLastOverflowFinishTime;
2743 long mLastClearTime;
2744 long mLastCleanupTime;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002745
Dianne Hackborn657153b2016-07-29 14:54:14 -07002746 public OverflowArrayMap(int uid) {
2747 mUid = uid;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002748 }
2749
2750 public ArrayMap<String, T> getMap() {
2751 return mMap;
2752 }
2753
2754 public void clear() {
Dianne Hackborn657153b2016-07-29 14:54:14 -07002755 mLastClearTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002756 mMap.clear();
2757 mCurOverflow = null;
2758 mActiveOverflow = null;
2759 }
2760
2761 public void add(String name, T obj) {
Joe Onorato388fc332016-04-12 17:06:47 -07002762 if (name == null) {
2763 name = "";
2764 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002765 mMap.put(name, obj);
2766 if (OVERFLOW_NAME.equals(name)) {
2767 mCurOverflow = obj;
2768 }
2769 }
2770
2771 public void cleanup() {
Dianne Hackborn657153b2016-07-29 14:54:14 -07002772 mLastCleanupTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002773 if (mActiveOverflow != null) {
2774 if (mActiveOverflow.size() == 0) {
2775 mActiveOverflow = null;
2776 }
2777 }
2778 if (mActiveOverflow == null) {
2779 // There is no currently active overflow, so we should no longer have
2780 // an overflow entry.
2781 if (mMap.containsKey(OVERFLOW_NAME)) {
2782 Slog.wtf(TAG, "Cleaning up with no active overflow, but have overflow entry "
2783 + mMap.get(OVERFLOW_NAME));
2784 mMap.remove(OVERFLOW_NAME);
2785 }
2786 mCurOverflow = null;
2787 } else {
2788 // There is currently active overflow, so we should still have an overflow entry.
2789 if (mCurOverflow == null || !mMap.containsKey(OVERFLOW_NAME)) {
2790 Slog.wtf(TAG, "Cleaning up with active overflow, but no overflow entry: cur="
2791 + mCurOverflow + " map=" + mMap.get(OVERFLOW_NAME));
2792 }
2793 }
2794 }
2795
2796 public T startObject(String name) {
Joe Onorato388fc332016-04-12 17:06:47 -07002797 if (name == null) {
2798 name = "";
2799 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002800 T obj = mMap.get(name);
2801 if (obj != null) {
2802 return obj;
2803 }
2804
2805 // No object exists for the given name, but do we currently have it
2806 // running as part of the overflow?
2807 if (mActiveOverflow != null) {
2808 MutableInt over = mActiveOverflow.get(name);
2809 if (over != null) {
2810 // We are already actively counting this name in the overflow object.
2811 obj = mCurOverflow;
2812 if (obj == null) {
2813 // Shouldn't be here, but we'll try to recover.
2814 Slog.wtf(TAG, "Have active overflow " + name + " but null overflow");
2815 obj = mCurOverflow = instantiateObject();
2816 mMap.put(OVERFLOW_NAME, obj);
2817 }
2818 over.value++;
2819 return obj;
2820 }
2821 }
2822
2823 // No object exists for given name nor in the overflow; we need to make
2824 // a new one.
2825 final int N = mMap.size();
2826 if (N >= MAX_WAKELOCKS_PER_UID) {
2827 // Went over the limit on number of objects to track; this one goes
2828 // in to the overflow.
2829 obj = mCurOverflow;
2830 if (obj == null) {
2831 // Need to start overflow now...
2832 obj = mCurOverflow = instantiateObject();
2833 mMap.put(OVERFLOW_NAME, obj);
2834 }
2835 if (mActiveOverflow == null) {
2836 mActiveOverflow = new ArrayMap<>();
2837 }
2838 mActiveOverflow.put(name, new MutableInt(1));
Dianne Hackborn657153b2016-07-29 14:54:14 -07002839 mLastOverflowTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002840 return obj;
2841 }
2842
2843 // Normal case where we just need to make a new object.
2844 obj = instantiateObject();
2845 mMap.put(name, obj);
2846 return obj;
2847 }
2848
2849 public T stopObject(String name) {
Joe Onorato388fc332016-04-12 17:06:47 -07002850 if (name == null) {
2851 name = "";
2852 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002853 T obj = mMap.get(name);
2854 if (obj != null) {
2855 return obj;
2856 }
2857
2858 // No object exists for the given name, but do we currently have it
2859 // running as part of the overflow?
2860 if (mActiveOverflow != null) {
2861 MutableInt over = mActiveOverflow.get(name);
2862 if (over != null) {
2863 // We are already actively counting this name in the overflow object.
2864 obj = mCurOverflow;
2865 if (obj != null) {
2866 over.value--;
2867 if (over.value <= 0) {
2868 mActiveOverflow.remove(name);
Dianne Hackborn657153b2016-07-29 14:54:14 -07002869 mLastOverflowFinishTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002870 }
2871 return obj;
2872 }
2873 }
2874 }
2875
2876 // Huh, they are stopping an active operation but we can't find one!
2877 // That's not good.
Dianne Hackborn657153b2016-07-29 14:54:14 -07002878 StringBuilder sb = new StringBuilder();
2879 sb.append("Unable to find object for ");
2880 sb.append(name);
2881 sb.append(" in uid ");
2882 sb.append(mUid);
2883 sb.append(" mapsize=");
2884 sb.append(mMap.size());
2885 sb.append(" activeoverflow=");
2886 sb.append(mActiveOverflow);
2887 sb.append(" curoverflow=");
2888 sb.append(mCurOverflow);
2889 long now = SystemClock.elapsedRealtime();
2890 if (mLastOverflowTime != 0) {
2891 sb.append(" lastOverflowTime=");
2892 TimeUtils.formatDuration(mLastOverflowTime-now, sb);
2893 }
2894 if (mLastOverflowFinishTime != 0) {
2895 sb.append(" lastOverflowFinishTime=");
2896 TimeUtils.formatDuration(mLastOverflowFinishTime-now, sb);
2897 }
2898 if (mLastClearTime != 0) {
2899 sb.append(" lastClearTime=");
2900 TimeUtils.formatDuration(mLastClearTime-now, sb);
2901 }
2902 if (mLastCleanupTime != 0) {
2903 sb.append(" lastCleanupTime=");
2904 TimeUtils.formatDuration(mLastCleanupTime-now, sb);
2905 }
2906 Slog.wtf(TAG, sb.toString());
Dianne Hackbornd953c532014-08-16 18:17:38 -07002907 return null;
2908 }
2909
2910 public abstract T instantiateObject();
2911 }
2912
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002913 public static class ControllerActivityCounterImpl extends ControllerActivityCounter
2914 implements Parcelable {
2915 private final LongSamplingCounter mIdleTimeMillis;
Siddharth Rayb50a6842017-12-14 15:15:28 -08002916 private final LongSamplingCounter mScanTimeMillis;
Siddharth Rayed754702018-02-15 12:44:37 -08002917 private final LongSamplingCounter mSleepTimeMillis;
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002918 private final LongSamplingCounter mRxTimeMillis;
2919 private final LongSamplingCounter[] mTxTimeMillis;
2920 private final LongSamplingCounter mPowerDrainMaMs;
2921
2922 public ControllerActivityCounterImpl(TimeBase timeBase, int numTxStates) {
2923 mIdleTimeMillis = new LongSamplingCounter(timeBase);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002924 mScanTimeMillis = new LongSamplingCounter(timeBase);
Siddharth Rayed754702018-02-15 12:44:37 -08002925 mSleepTimeMillis = new LongSamplingCounter(timeBase);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002926 mRxTimeMillis = new LongSamplingCounter(timeBase);
2927 mTxTimeMillis = new LongSamplingCounter[numTxStates];
2928 for (int i = 0; i < numTxStates; i++) {
2929 mTxTimeMillis[i] = new LongSamplingCounter(timeBase);
2930 }
2931 mPowerDrainMaMs = new LongSamplingCounter(timeBase);
2932 }
2933
2934 public ControllerActivityCounterImpl(TimeBase timeBase, int numTxStates, Parcel in) {
2935 mIdleTimeMillis = new LongSamplingCounter(timeBase, in);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002936 mScanTimeMillis = new LongSamplingCounter(timeBase, in);
Siddharth Rayed754702018-02-15 12:44:37 -08002937 mSleepTimeMillis = new LongSamplingCounter(timeBase, in);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002938 mRxTimeMillis = new LongSamplingCounter(timeBase, in);
2939 final int recordedTxStates = in.readInt();
2940 if (recordedTxStates != numTxStates) {
2941 throw new ParcelFormatException("inconsistent tx state lengths");
2942 }
2943
2944 mTxTimeMillis = new LongSamplingCounter[numTxStates];
2945 for (int i = 0; i < numTxStates; i++) {
2946 mTxTimeMillis[i] = new LongSamplingCounter(timeBase, in);
2947 }
2948 mPowerDrainMaMs = new LongSamplingCounter(timeBase, in);
2949 }
2950
2951 public void readSummaryFromParcel(Parcel in) {
2952 mIdleTimeMillis.readSummaryFromParcelLocked(in);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002953 mScanTimeMillis.readSummaryFromParcelLocked(in);
Siddharth Rayed754702018-02-15 12:44:37 -08002954 mSleepTimeMillis.readSummaryFromParcelLocked(in);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002955 mRxTimeMillis.readSummaryFromParcelLocked(in);
2956 final int recordedTxStates = in.readInt();
2957 if (recordedTxStates != mTxTimeMillis.length) {
2958 throw new ParcelFormatException("inconsistent tx state lengths");
2959 }
2960 for (LongSamplingCounter counter : mTxTimeMillis) {
2961 counter.readSummaryFromParcelLocked(in);
2962 }
2963 mPowerDrainMaMs.readSummaryFromParcelLocked(in);
2964 }
2965
2966 @Override
2967 public int describeContents() {
2968 return 0;
2969 }
2970
2971 public void writeSummaryToParcel(Parcel dest) {
2972 mIdleTimeMillis.writeSummaryFromParcelLocked(dest);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002973 mScanTimeMillis.writeSummaryFromParcelLocked(dest);
Siddharth Rayed754702018-02-15 12:44:37 -08002974 mSleepTimeMillis.writeSummaryFromParcelLocked(dest);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002975 mRxTimeMillis.writeSummaryFromParcelLocked(dest);
2976 dest.writeInt(mTxTimeMillis.length);
2977 for (LongSamplingCounter counter : mTxTimeMillis) {
2978 counter.writeSummaryFromParcelLocked(dest);
2979 }
2980 mPowerDrainMaMs.writeSummaryFromParcelLocked(dest);
2981 }
2982
2983 @Override
2984 public void writeToParcel(Parcel dest, int flags) {
2985 mIdleTimeMillis.writeToParcel(dest);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002986 mScanTimeMillis.writeToParcel(dest);
Siddharth Rayed754702018-02-15 12:44:37 -08002987 mSleepTimeMillis.writeToParcel(dest);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002988 mRxTimeMillis.writeToParcel(dest);
2989 dest.writeInt(mTxTimeMillis.length);
2990 for (LongSamplingCounter counter : mTxTimeMillis) {
2991 counter.writeToParcel(dest);
2992 }
2993 mPowerDrainMaMs.writeToParcel(dest);
2994 }
2995
2996 public void reset(boolean detachIfReset) {
2997 mIdleTimeMillis.reset(detachIfReset);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002998 mScanTimeMillis.reset(detachIfReset);
Siddharth Rayed754702018-02-15 12:44:37 -08002999 mSleepTimeMillis.reset(detachIfReset);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08003000 mRxTimeMillis.reset(detachIfReset);
3001 for (LongSamplingCounter counter : mTxTimeMillis) {
3002 counter.reset(detachIfReset);
3003 }
3004 mPowerDrainMaMs.reset(detachIfReset);
3005 }
3006
3007 public void detach() {
3008 mIdleTimeMillis.detach();
Siddharth Rayb50a6842017-12-14 15:15:28 -08003009 mScanTimeMillis.detach();
Siddharth Rayed754702018-02-15 12:44:37 -08003010 mSleepTimeMillis.detach();
Adam Lesinski21f76aa2016-01-25 12:27:06 -08003011 mRxTimeMillis.detach();
3012 for (LongSamplingCounter counter : mTxTimeMillis) {
3013 counter.detach();
3014 }
3015 mPowerDrainMaMs.detach();
3016 }
3017
3018 /**
3019 * @return a LongSamplingCounter, measuring time spent in the idle state in
3020 * milliseconds.
3021 */
3022 @Override
3023 public LongSamplingCounter getIdleTimeCounter() {
Roshan Pius81643302016-03-14 16:45:55 -07003024 return mIdleTimeMillis;
Adam Lesinski21f76aa2016-01-25 12:27:06 -08003025 }
3026
3027 /**
Siddharth Rayb50a6842017-12-14 15:15:28 -08003028 * @return a LongSamplingCounter, measuring time spent in the scan state in
3029 * milliseconds.
3030 */
3031 @Override
3032 public LongSamplingCounter getScanTimeCounter() {
3033 return mScanTimeMillis;
3034 }
3035
3036 /**
Siddharth Rayed754702018-02-15 12:44:37 -08003037 * @return a LongSamplingCounter, measuring time spent in the sleep state in
3038 * milliseconds.
3039 */
3040 @Override
3041 public LongSamplingCounter getSleepTimeCounter() {
3042 return mSleepTimeMillis;
3043 }
3044
3045 /**
Adam Lesinski21f76aa2016-01-25 12:27:06 -08003046 * @return a LongSamplingCounter, measuring time spent in the receive state in
3047 * milliseconds.
3048 */
3049 @Override
3050 public LongSamplingCounter getRxTimeCounter() {
3051 return mRxTimeMillis;
3052 }
3053
3054 /**
3055 * @return a LongSamplingCounter[], measuring time spent in various transmit states in
3056 * milliseconds.
3057 */
3058 @Override
3059 public LongSamplingCounter[] getTxTimeCounters() {
3060 return mTxTimeMillis;
3061 }
3062
3063 /**
3064 * @return a LongSamplingCounter, measuring power use in milli-ampere milliseconds (mAmS).
3065 */
3066 @Override
3067 public LongSamplingCounter getPowerCounter() {
3068 return mPowerDrainMaMs;
3069 }
3070 }
3071
Bookatz50df7112017-08-04 14:53:26 -07003072 /** Get Resource Power Manager stats. Create a new one if it doesn't already exist. */
3073 public SamplingTimer getRpmTimerLocked(String name) {
3074 SamplingTimer rpmt = mRpmStats.get(name);
3075 if (rpmt == null) {
3076 rpmt = new SamplingTimer(mClocks, mOnBatteryTimeBase);
3077 mRpmStats.put(name, rpmt);
3078 }
3079 return rpmt;
3080 }
3081
3082 /** Get Screen-off Resource Power Manager stats. Create new one if it doesn't already exist. */
3083 public SamplingTimer getScreenOffRpmTimerLocked(String name) {
3084 SamplingTimer rpmt = mScreenOffRpmStats.get(name);
3085 if (rpmt == null) {
3086 rpmt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
3087 mScreenOffRpmStats.put(name, rpmt);
3088 }
3089 return rpmt;
3090 }
3091
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003092 /*
3093 * Get the wakeup reason counter, and create a new one if one
3094 * doesn't already exist.
3095 */
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07003096 public SamplingTimer getWakeupReasonTimerLocked(String name) {
3097 SamplingTimer timer = mWakeupReasonStats.get(name);
3098 if (timer == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07003099 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07003100 mWakeupReasonStats.put(name, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003101 }
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07003102 return timer;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003103 }
3104
Evan Millarc64edde2009-04-18 12:26:32 -07003105 /*
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003106 * Get the KernelWakelockTimer associated with name, and create a new one if one
Evan Millarc64edde2009-04-18 12:26:32 -07003107 * doesn't already exist.
3108 */
3109 public SamplingTimer getKernelWakelockTimerLocked(String name) {
3110 SamplingTimer kwlt = mKernelWakelockStats.get(name);
3111 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07003112 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Evan Millarc64edde2009-04-18 12:26:32 -07003113 mKernelWakelockStats.put(name, kwlt);
3114 }
3115 return kwlt;
3116 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07003117
James Carr3a226052016-07-01 14:49:52 -07003118 public SamplingTimer getKernelMemoryTimerLocked(long bucket) {
3119 SamplingTimer kmt = mKernelMemoryStats.get(bucket);
3120 if (kmt == null) {
3121 kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase);
3122 mKernelMemoryStats.put(bucket, kmt);
3123 }
3124 return kmt;
3125 }
3126
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003127 private int writeHistoryTag(HistoryTag tag) {
3128 Integer idxObj = mHistoryTagPool.get(tag);
3129 int idx;
3130 if (idxObj != null) {
3131 idx = idxObj;
3132 } else {
3133 idx = mNextHistoryTagIdx;
3134 HistoryTag key = new HistoryTag();
3135 key.setTo(tag);
3136 tag.poolIdx = idx;
3137 mHistoryTagPool.put(key, idx);
3138 mNextHistoryTagIdx++;
3139 mNumHistoryTagChars += key.string.length() + 1;
3140 }
3141 return idx;
3142 }
3143
3144 private void readHistoryTag(int index, HistoryTag tag) {
3145 tag.string = mReadHistoryStrings[index];
3146 tag.uid = mReadHistoryUids[index];
3147 tag.poolIdx = index;
3148 }
3149
Adam Lesinski926969b2016-04-28 17:31:12 -07003150 /*
3151 The history delta format uses flags to denote further data in subsequent ints in the parcel.
3152
3153 There is always the first token, which may contain the delta time, or an indicator of
3154 the length of the time (int or long) following this token.
3155
3156 First token: always present,
3157 31 23 15 7 0
3158 â–ˆ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â–ˆ
3159
3160 T: the delta time if it is <= 0x7fffd. Otherwise 0x7fffe indicates an int immediately
3161 follows containing the time, and 0x7ffff indicates a long immediately follows with the
3162 delta time.
3163 A: battery level changed and an int follows with battery data.
3164 B: state changed and an int follows with state change data.
3165 C: state2 has changed and an int follows with state2 change data.
3166 D: wakelock/wakereason has changed and an wakelock/wakereason struct follows.
3167 E: event data has changed and an event struct follows.
3168 F: battery charge in coulombs has changed and an int with the charge follows.
3169 G: state flag denoting that the mobile radio was active.
3170 H: state flag denoting that the wifi radio was active.
3171 I: state flag denoting that a wifi scan occurred.
3172 J: state flag denoting that a wifi full lock was held.
3173 K: state flag denoting that the gps was on.
3174 L: state flag denoting that a wakelock was held.
3175 M: state flag denoting that the cpu was running.
3176
3177 Time int/long: if T in the first token is 0x7ffff or 0x7fffe, then an int or long follows
3178 with the time delta.
3179
3180 Battery level int: if A in the first token is set,
3181 31 23 15 7 0
3182 â–ˆ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â–ˆ
3183
3184 D: indicates that extra history details follow.
3185 V: the battery voltage.
3186 T: the battery temperature.
3187 L: the battery level (out of 100).
3188
3189 State change int: if B in the first token is set,
3190 31 23 15 7 0
3191 â–ˆS|S|S|H|H|H|P|Pâ–ˆF|E|D|C|B| | |Aâ–ˆ | | | | | | | â–ˆ | | | | | | | â–ˆ
3192
3193 A: wifi multicast was on.
3194 B: battery was plugged in.
3195 C: screen was on.
3196 D: phone was scanning for signal.
3197 E: audio was on.
3198 F: a sensor was active.
3199
3200 State2 change int: if C in the first token is set,
3201 31 23 15 7 0
3202 â–ˆM|L|K|J|I|H|H|Gâ–ˆF|E|D|C| | | | â–ˆ | | | | | | | â–ˆ |B|B|B|A|A|A|Aâ–ˆ
3203
3204 A: 4 bits indicating the wifi supplicant state: {@link BatteryStats#WIFI_SUPPL_STATE_NAMES}.
3205 B: 3 bits indicating the wifi signal strength: 0, 1, 2, 3, 4.
3206 C: a bluetooth scan was active.
3207 D: the camera was active.
3208 E: bluetooth was on.
3209 F: a phone call was active.
3210 G: the device was charging.
3211 H: 2 bits indicating the device-idle (doze) state: off, light, full
3212 I: the flashlight was on.
3213 J: wifi was on.
3214 K: wifi was running.
3215 L: video was playing.
3216 M: power save mode was on.
3217
3218 Wakelock/wakereason struct: if D in the first token is set,
3219 TODO(adamlesinski): describe wakelock/wakereason struct.
3220
3221 Event struct: if E in the first token is set,
3222 TODO(adamlesinski): describe the event struct.
3223
3224 History step details struct: if D in the battery level int is set,
3225 TODO(adamlesinski): describe the history step details struct.
3226
3227 Battery charge int: if F in the first token is set, an int representing the battery charge
3228 in coulombs follows.
3229 */
3230
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003231 // Part of initial delta int that specifies the time delta.
Dianne Hackborne13c4c02014-02-11 17:18:35 -08003232 static final int DELTA_TIME_MASK = 0x7ffff;
3233 static final int DELTA_TIME_LONG = 0x7ffff; // The delta is a following long
3234 static final int DELTA_TIME_INT = 0x7fffe; // The delta is a following int
3235 static final int DELTA_TIME_ABS = 0x7fffd; // Following is an entire abs update.
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003236 // Flag in delta int: a new battery level int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003237 static final int DELTA_BATTERY_LEVEL_FLAG = 0x00080000;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003238 // Flag in delta int: a new full state and battery status int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003239 static final int DELTA_STATE_FLAG = 0x00100000;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08003240 // Flag in delta int: a new full state2 int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003241 static final int DELTA_STATE2_FLAG = 0x00200000;
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003242 // Flag in delta int: contains a wakelock or wakeReason tag.
Adam Lesinski926969b2016-04-28 17:31:12 -07003243 static final int DELTA_WAKELOCK_FLAG = 0x00400000;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003244 // Flag in delta int: contains an event description.
Adam Lesinski926969b2016-04-28 17:31:12 -07003245 static final int DELTA_EVENT_FLAG = 0x00800000;
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003246 // Flag in delta int: contains the battery charge count in uAh.
3247 static final int DELTA_BATTERY_CHARGE_FLAG = 0x01000000;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003248 // These upper bits are the frequently changing state bits.
Adam Lesinski926969b2016-04-28 17:31:12 -07003249 static final int DELTA_STATE_MASK = 0xfe000000;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003250
3251 // These are the pieces of battery state that are packed in to the upper bits of
3252 // the state int that have been packed in to the first delta int. They must fit
Adam Lesinski926969b2016-04-28 17:31:12 -07003253 // in STATE_BATTERY_MASK.
3254 static final int STATE_BATTERY_MASK = 0xff000000;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003255 static final int STATE_BATTERY_STATUS_MASK = 0x00000007;
3256 static final int STATE_BATTERY_STATUS_SHIFT = 29;
3257 static final int STATE_BATTERY_HEALTH_MASK = 0x00000007;
3258 static final int STATE_BATTERY_HEALTH_SHIFT = 26;
3259 static final int STATE_BATTERY_PLUG_MASK = 0x00000003;
3260 static final int STATE_BATTERY_PLUG_SHIFT = 24;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003261
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003262 // We use the low bit of the battery state int to indicate that we have full details
3263 // from a battery level change.
3264 static final int BATTERY_DELTA_LEVEL_FLAG = 0x00000001;
3265
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003266 public void writeHistoryDelta(Parcel dest, HistoryItem cur, HistoryItem last) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003267 if (last == null || cur.cmd != HistoryItem.CMD_UPDATE) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003268 dest.writeInt(DELTA_TIME_ABS);
3269 cur.writeToParcel(dest, 0);
3270 return;
3271 }
3272
3273 final long deltaTime = cur.time - last.time;
3274 final int lastBatteryLevelInt = buildBatteryLevelInt(last);
3275 final int lastStateInt = buildStateInt(last);
3276
3277 int deltaTimeToken;
3278 if (deltaTime < 0 || deltaTime > Integer.MAX_VALUE) {
3279 deltaTimeToken = DELTA_TIME_LONG;
3280 } else if (deltaTime >= DELTA_TIME_ABS) {
3281 deltaTimeToken = DELTA_TIME_INT;
3282 } else {
3283 deltaTimeToken = (int)deltaTime;
3284 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003285 int firstToken = deltaTimeToken | (cur.states&DELTA_STATE_MASK);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003286 final int includeStepDetails = mLastHistoryStepLevel > cur.batteryLevel
3287 ? BATTERY_DELTA_LEVEL_FLAG : 0;
3288 final boolean computeStepDetails = includeStepDetails != 0
3289 || mLastHistoryStepDetails == null;
3290 final int batteryLevelInt = buildBatteryLevelInt(cur) | includeStepDetails;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003291 final boolean batteryLevelIntChanged = batteryLevelInt != lastBatteryLevelInt;
3292 if (batteryLevelIntChanged) {
3293 firstToken |= DELTA_BATTERY_LEVEL_FLAG;
3294 }
3295 final int stateInt = buildStateInt(cur);
3296 final boolean stateIntChanged = stateInt != lastStateInt;
3297 if (stateIntChanged) {
3298 firstToken |= DELTA_STATE_FLAG;
3299 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003300 final boolean state2IntChanged = cur.states2 != last.states2;
3301 if (state2IntChanged) {
3302 firstToken |= DELTA_STATE2_FLAG;
3303 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003304 if (cur.wakelockTag != null || cur.wakeReasonTag != null) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003305 firstToken |= DELTA_WAKELOCK_FLAG;
3306 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003307 if (cur.eventCode != HistoryItem.EVENT_NONE) {
3308 firstToken |= DELTA_EVENT_FLAG;
3309 }
Adam Lesinski926969b2016-04-28 17:31:12 -07003310
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003311 final boolean batteryChargeChanged = cur.batteryChargeUAh != last.batteryChargeUAh;
3312 if (batteryChargeChanged) {
3313 firstToken |= DELTA_BATTERY_CHARGE_FLAG;
Adam Lesinski926969b2016-04-28 17:31:12 -07003314 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003315 dest.writeInt(firstToken);
3316 if (DEBUG) Slog.i(TAG, "WRITE DELTA: firstToken=0x" + Integer.toHexString(firstToken)
3317 + " deltaTime=" + deltaTime);
3318
3319 if (deltaTimeToken >= DELTA_TIME_INT) {
3320 if (deltaTimeToken == DELTA_TIME_INT) {
3321 if (DEBUG) Slog.i(TAG, "WRITE DELTA: int deltaTime=" + (int)deltaTime);
3322 dest.writeInt((int)deltaTime);
3323 } else {
3324 if (DEBUG) Slog.i(TAG, "WRITE DELTA: long deltaTime=" + deltaTime);
3325 dest.writeLong(deltaTime);
3326 }
3327 }
3328 if (batteryLevelIntChanged) {
3329 dest.writeInt(batteryLevelInt);
3330 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryToken=0x"
3331 + Integer.toHexString(batteryLevelInt)
3332 + " batteryLevel=" + cur.batteryLevel
3333 + " batteryTemp=" + cur.batteryTemperature
3334 + " batteryVolt=" + (int)cur.batteryVoltage);
3335 }
3336 if (stateIntChanged) {
3337 dest.writeInt(stateInt);
3338 if (DEBUG) Slog.i(TAG, "WRITE DELTA: stateToken=0x"
3339 + Integer.toHexString(stateInt)
3340 + " batteryStatus=" + cur.batteryStatus
3341 + " batteryHealth=" + cur.batteryHealth
3342 + " batteryPlugType=" + cur.batteryPlugType
3343 + " states=0x" + Integer.toHexString(cur.states));
3344 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003345 if (state2IntChanged) {
3346 dest.writeInt(cur.states2);
3347 if (DEBUG) Slog.i(TAG, "WRITE DELTA: states2=0x"
3348 + Integer.toHexString(cur.states2));
3349 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003350 if (cur.wakelockTag != null || cur.wakeReasonTag != null) {
3351 int wakeLockIndex;
3352 int wakeReasonIndex;
3353 if (cur.wakelockTag != null) {
3354 wakeLockIndex = writeHistoryTag(cur.wakelockTag);
3355 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx
3356 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string);
3357 } else {
3358 wakeLockIndex = 0xffff;
3359 }
3360 if (cur.wakeReasonTag != null) {
3361 wakeReasonIndex = writeHistoryTag(cur.wakeReasonTag);
3362 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx
3363 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string);
3364 } else {
3365 wakeReasonIndex = 0xffff;
3366 }
3367 dest.writeInt((wakeReasonIndex<<16) | wakeLockIndex);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003368 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003369 if (cur.eventCode != HistoryItem.EVENT_NONE) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003370 int index = writeHistoryTag(cur.eventTag);
3371 int codeAndIndex = (cur.eventCode&0xffff) | (index<<16);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003372 dest.writeInt(codeAndIndex);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003373 if (DEBUG) Slog.i(TAG, "WRITE DELTA: event=" + cur.eventCode + " tag=#"
3374 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":"
3375 + cur.eventTag.string);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003376 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003377 if (computeStepDetails) {
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07003378 if (mPlatformIdleStateCallback != null) {
3379 mCurHistoryStepDetails.statPlatformIdleState =
3380 mPlatformIdleStateCallback.getPlatformLowPowerStats();
3381 if (DEBUG) Slog.i(TAG, "WRITE PlatformIdleState:" +
3382 mCurHistoryStepDetails.statPlatformIdleState);
Ahmed ElArabawyd8b44112017-05-23 21:25:02 +00003383
3384 mCurHistoryStepDetails.statSubsystemPowerState =
3385 mPlatformIdleStateCallback.getSubsystemLowPowerStats();
3386 if (DEBUG) Slog.i(TAG, "WRITE SubsystemPowerState:" +
3387 mCurHistoryStepDetails.statSubsystemPowerState);
3388
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07003389 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003390 computeHistoryStepDetails(mCurHistoryStepDetails, mLastHistoryStepDetails);
3391 if (includeStepDetails != 0) {
3392 mCurHistoryStepDetails.writeToParcel(dest);
3393 }
3394 cur.stepDetails = mCurHistoryStepDetails;
3395 mLastHistoryStepDetails = mCurHistoryStepDetails;
3396 } else {
3397 cur.stepDetails = null;
3398 }
3399 if (mLastHistoryStepLevel < cur.batteryLevel) {
3400 mLastHistoryStepDetails = null;
3401 }
3402 mLastHistoryStepLevel = cur.batteryLevel;
Adam Lesinski926969b2016-04-28 17:31:12 -07003403
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003404 if (batteryChargeChanged) {
3405 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryChargeUAh=" + cur.batteryChargeUAh);
3406 dest.writeInt(cur.batteryChargeUAh);
Adam Lesinski926969b2016-04-28 17:31:12 -07003407 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003408 }
3409
3410 private int buildBatteryLevelInt(HistoryItem h) {
3411 return ((((int)h.batteryLevel)<<25)&0xfe000000)
Adam Lesinski3944c812015-11-13 15:54:59 -08003412 | ((((int)h.batteryTemperature)<<15)&0x01ff8000)
3413 | ((((int)h.batteryVoltage)<<1)&0x00007ffe);
3414 }
3415
3416 private void readBatteryLevelInt(int batteryLevelInt, HistoryItem out) {
3417 out.batteryLevel = (byte)((batteryLevelInt & 0xfe000000) >>> 25);
3418 out.batteryTemperature = (short)((batteryLevelInt & 0x01ff8000) >>> 15);
3419 out.batteryVoltage = (char)((batteryLevelInt & 0x00007ffe) >>> 1);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003420 }
3421
3422 private int buildStateInt(HistoryItem h) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003423 int plugType = 0;
3424 if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_AC) != 0) {
3425 plugType = 1;
3426 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_USB) != 0) {
3427 plugType = 2;
3428 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_WIRELESS) != 0) {
3429 plugType = 3;
3430 }
3431 return ((h.batteryStatus&STATE_BATTERY_STATUS_MASK)<<STATE_BATTERY_STATUS_SHIFT)
3432 | ((h.batteryHealth&STATE_BATTERY_HEALTH_MASK)<<STATE_BATTERY_HEALTH_SHIFT)
3433 | ((plugType&STATE_BATTERY_PLUG_MASK)<<STATE_BATTERY_PLUG_SHIFT)
Adam Lesinski926969b2016-04-28 17:31:12 -07003434 | (h.states&(~STATE_BATTERY_MASK));
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003435 }
3436
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003437 private void computeHistoryStepDetails(final HistoryStepDetails out,
3438 final HistoryStepDetails last) {
3439 final HistoryStepDetails tmp = last != null ? mTmpHistoryStepDetails : out;
3440
3441 // Perform a CPU update right after we do this collection, so we have started
3442 // collecting good data for the next step.
3443 requestImmediateCpuUpdate();
3444
3445 if (last == null) {
3446 // We are not generating a delta, so all we need to do is reset the stats
3447 // we will later be doing a delta from.
3448 final int NU = mUidStats.size();
3449 for (int i=0; i<NU; i++) {
3450 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
3451 uid.mLastStepUserTime = uid.mCurStepUserTime;
3452 uid.mLastStepSystemTime = uid.mCurStepSystemTime;
3453 }
3454 mLastStepCpuUserTime = mCurStepCpuUserTime;
3455 mLastStepCpuSystemTime = mCurStepCpuSystemTime;
3456 mLastStepStatUserTime = mCurStepStatUserTime;
3457 mLastStepStatSystemTime = mCurStepStatSystemTime;
3458 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime;
3459 mLastStepStatIrqTime = mCurStepStatIrqTime;
3460 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime;
3461 mLastStepStatIdleTime = mCurStepStatIdleTime;
3462 tmp.clear();
3463 return;
3464 }
3465 if (DEBUG) {
3466 Slog.d(TAG, "Step stats last: user=" + mLastStepCpuUserTime + " sys="
3467 + mLastStepStatSystemTime + " io=" + mLastStepStatIOWaitTime
3468 + " irq=" + mLastStepStatIrqTime + " sirq="
3469 + mLastStepStatSoftIrqTime + " idle=" + mLastStepStatIdleTime);
3470 Slog.d(TAG, "Step stats cur: user=" + mCurStepCpuUserTime + " sys="
3471 + mCurStepStatSystemTime + " io=" + mCurStepStatIOWaitTime
3472 + " irq=" + mCurStepStatIrqTime + " sirq="
3473 + mCurStepStatSoftIrqTime + " idle=" + mCurStepStatIdleTime);
3474 }
3475 out.userTime = (int)(mCurStepCpuUserTime - mLastStepCpuUserTime);
3476 out.systemTime = (int)(mCurStepCpuSystemTime - mLastStepCpuSystemTime);
3477 out.statUserTime = (int)(mCurStepStatUserTime - mLastStepStatUserTime);
3478 out.statSystemTime = (int)(mCurStepStatSystemTime - mLastStepStatSystemTime);
3479 out.statIOWaitTime = (int)(mCurStepStatIOWaitTime - mLastStepStatIOWaitTime);
3480 out.statIrqTime = (int)(mCurStepStatIrqTime - mLastStepStatIrqTime);
3481 out.statSoftIrqTime = (int)(mCurStepStatSoftIrqTime - mLastStepStatSoftIrqTime);
3482 out.statIdlTime = (int)(mCurStepStatIdleTime - mLastStepStatIdleTime);
3483 out.appCpuUid1 = out.appCpuUid2 = out.appCpuUid3 = -1;
3484 out.appCpuUTime1 = out.appCpuUTime2 = out.appCpuUTime3 = 0;
3485 out.appCpuSTime1 = out.appCpuSTime2 = out.appCpuSTime3 = 0;
3486 final int NU = mUidStats.size();
3487 for (int i=0; i<NU; i++) {
3488 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
3489 final int totalUTime = (int)(uid.mCurStepUserTime - uid.mLastStepUserTime);
3490 final int totalSTime = (int)(uid.mCurStepSystemTime - uid.mLastStepSystemTime);
3491 final int totalTime = totalUTime + totalSTime;
3492 uid.mLastStepUserTime = uid.mCurStepUserTime;
3493 uid.mLastStepSystemTime = uid.mCurStepSystemTime;
3494 if (totalTime <= (out.appCpuUTime3+out.appCpuSTime3)) {
3495 continue;
3496 }
3497 if (totalTime <= (out.appCpuUTime2+out.appCpuSTime2)) {
3498 out.appCpuUid3 = uid.mUid;
3499 out.appCpuUTime3 = totalUTime;
3500 out.appCpuSTime3 = totalSTime;
3501 } else {
3502 out.appCpuUid3 = out.appCpuUid2;
3503 out.appCpuUTime3 = out.appCpuUTime2;
3504 out.appCpuSTime3 = out.appCpuSTime2;
3505 if (totalTime <= (out.appCpuUTime1+out.appCpuSTime1)) {
3506 out.appCpuUid2 = uid.mUid;
3507 out.appCpuUTime2 = totalUTime;
3508 out.appCpuSTime2 = totalSTime;
3509 } else {
3510 out.appCpuUid2 = out.appCpuUid1;
3511 out.appCpuUTime2 = out.appCpuUTime1;
3512 out.appCpuSTime2 = out.appCpuSTime1;
3513 out.appCpuUid1 = uid.mUid;
3514 out.appCpuUTime1 = totalUTime;
3515 out.appCpuSTime1 = totalSTime;
3516 }
3517 }
3518 }
3519 mLastStepCpuUserTime = mCurStepCpuUserTime;
3520 mLastStepCpuSystemTime = mCurStepCpuSystemTime;
3521 mLastStepStatUserTime = mCurStepStatUserTime;
3522 mLastStepStatSystemTime = mCurStepStatSystemTime;
3523 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime;
3524 mLastStepStatIrqTime = mCurStepStatIrqTime;
3525 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime;
3526 mLastStepStatIdleTime = mCurStepStatIdleTime;
3527 }
3528
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003529 public void readHistoryDelta(Parcel src, HistoryItem cur) {
3530 int firstToken = src.readInt();
3531 int deltaTimeToken = firstToken&DELTA_TIME_MASK;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003532 cur.cmd = HistoryItem.CMD_UPDATE;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003533 cur.numReadInts = 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003534 if (DEBUG) Slog.i(TAG, "READ DELTA: firstToken=0x" + Integer.toHexString(firstToken)
3535 + " deltaTimeToken=" + deltaTimeToken);
3536
3537 if (deltaTimeToken < DELTA_TIME_ABS) {
3538 cur.time += deltaTimeToken;
3539 } else if (deltaTimeToken == DELTA_TIME_ABS) {
3540 cur.time = src.readLong();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003541 cur.numReadInts += 2;
3542 if (DEBUG) Slog.i(TAG, "READ DELTA: ABS time=" + cur.time);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003543 cur.readFromParcel(src);
3544 return;
3545 } else if (deltaTimeToken == DELTA_TIME_INT) {
3546 int delta = src.readInt();
3547 cur.time += delta;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003548 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003549 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time);
3550 } else {
3551 long delta = src.readLong();
3552 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time);
3553 cur.time += delta;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003554 cur.numReadInts += 2;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003555 }
3556
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003557 final int batteryLevelInt;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003558 if ((firstToken&DELTA_BATTERY_LEVEL_FLAG) != 0) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003559 batteryLevelInt = src.readInt();
Adam Lesinski3944c812015-11-13 15:54:59 -08003560 readBatteryLevelInt(batteryLevelInt, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003561 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003562 if (DEBUG) Slog.i(TAG, "READ DELTA: batteryToken=0x"
3563 + Integer.toHexString(batteryLevelInt)
3564 + " batteryLevel=" + cur.batteryLevel
3565 + " batteryTemp=" + cur.batteryTemperature
3566 + " batteryVolt=" + (int)cur.batteryVoltage);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003567 } else {
3568 batteryLevelInt = 0;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003569 }
3570
3571 if ((firstToken&DELTA_STATE_FLAG) != 0) {
3572 int stateInt = src.readInt();
Adam Lesinski926969b2016-04-28 17:31:12 -07003573 cur.states = (firstToken&DELTA_STATE_MASK) | (stateInt&(~STATE_BATTERY_MASK));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003574 cur.batteryStatus = (byte)((stateInt>>STATE_BATTERY_STATUS_SHIFT)
3575 & STATE_BATTERY_STATUS_MASK);
3576 cur.batteryHealth = (byte)((stateInt>>STATE_BATTERY_HEALTH_SHIFT)
3577 & STATE_BATTERY_HEALTH_MASK);
3578 cur.batteryPlugType = (byte)((stateInt>>STATE_BATTERY_PLUG_SHIFT)
3579 & STATE_BATTERY_PLUG_MASK);
3580 switch (cur.batteryPlugType) {
3581 case 1:
3582 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_AC;
3583 break;
3584 case 2:
3585 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_USB;
3586 break;
3587 case 3:
3588 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_WIRELESS;
3589 break;
3590 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003591 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003592 if (DEBUG) Slog.i(TAG, "READ DELTA: stateToken=0x"
3593 + Integer.toHexString(stateInt)
3594 + " batteryStatus=" + cur.batteryStatus
3595 + " batteryHealth=" + cur.batteryHealth
3596 + " batteryPlugType=" + cur.batteryPlugType
3597 + " states=0x" + Integer.toHexString(cur.states));
3598 } else {
Adam Lesinski926969b2016-04-28 17:31:12 -07003599 cur.states = (firstToken&DELTA_STATE_MASK) | (cur.states&(~STATE_BATTERY_MASK));
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003600 }
3601
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003602 if ((firstToken&DELTA_STATE2_FLAG) != 0) {
3603 cur.states2 = src.readInt();
3604 if (DEBUG) Slog.i(TAG, "READ DELTA: states2=0x"
3605 + Integer.toHexString(cur.states2));
3606 }
3607
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003608 if ((firstToken&DELTA_WAKELOCK_FLAG) != 0) {
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003609 int indexes = src.readInt();
3610 int wakeLockIndex = indexes&0xffff;
3611 int wakeReasonIndex = (indexes>>16)&0xffff;
3612 if (wakeLockIndex != 0xffff) {
3613 cur.wakelockTag = cur.localWakelockTag;
3614 readHistoryTag(wakeLockIndex, cur.wakelockTag);
3615 if (DEBUG) Slog.i(TAG, "READ DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx
3616 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string);
3617 } else {
3618 cur.wakelockTag = null;
3619 }
3620 if (wakeReasonIndex != 0xffff) {
3621 cur.wakeReasonTag = cur.localWakeReasonTag;
3622 readHistoryTag(wakeReasonIndex, cur.wakeReasonTag);
3623 if (DEBUG) Slog.i(TAG, "READ DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx
3624 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string);
3625 } else {
3626 cur.wakeReasonTag = null;
3627 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003628 cur.numReadInts += 1;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003629 } else {
3630 cur.wakelockTag = null;
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003631 cur.wakeReasonTag = null;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003632 }
3633
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003634 if ((firstToken&DELTA_EVENT_FLAG) != 0) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003635 cur.eventTag = cur.localEventTag;
3636 final int codeAndIndex = src.readInt();
Dianne Hackborn099bc622014-01-22 13:39:16 -08003637 cur.eventCode = (codeAndIndex&0xffff);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003638 final int index = ((codeAndIndex>>16)&0xffff);
3639 readHistoryTag(index, cur.eventTag);
3640 cur.numReadInts += 1;
3641 if (DEBUG) Slog.i(TAG, "READ DELTA: event=" + cur.eventCode + " tag=#"
3642 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":"
3643 + cur.eventTag.string);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003644 } else {
3645 cur.eventCode = HistoryItem.EVENT_NONE;
3646 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003647
3648 if ((batteryLevelInt&BATTERY_DELTA_LEVEL_FLAG) != 0) {
3649 cur.stepDetails = mReadHistoryStepDetails;
3650 cur.stepDetails.readFromParcel(src);
3651 } else {
3652 cur.stepDetails = null;
3653 }
Adam Lesinski926969b2016-04-28 17:31:12 -07003654
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003655 if ((firstToken&DELTA_BATTERY_CHARGE_FLAG) != 0) {
3656 cur.batteryChargeUAh = src.readInt();
Adam Lesinski926969b2016-04-28 17:31:12 -07003657 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003658 }
3659
Dianne Hackbornfc064132014-06-02 12:42:12 -07003660 @Override
3661 public void commitCurrentHistoryBatchLocked() {
3662 mHistoryLastWritten.cmd = HistoryItem.CMD_NULL;
3663 }
3664
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003665 void addHistoryBufferLocked(long elapsedRealtimeMs, HistoryItem cur) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003666 if (!mHaveBatteryLevel || !mRecordingHistory) {
3667 return;
3668 }
3669
Dianne Hackborn40c87252014-03-19 16:55:40 -07003670 final long timeDiff = (mHistoryBaseTime+elapsedRealtimeMs) - mHistoryLastWritten.time;
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003671 final int diffStates = mHistoryLastWritten.states^(cur.states&mActiveHistoryStates);
3672 final int diffStates2 = mHistoryLastWritten.states2^(cur.states2&mActiveHistoryStates2);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003673 final int lastDiffStates = mHistoryLastWritten.states^mHistoryLastLastWritten.states;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003674 final int lastDiffStates2 = mHistoryLastWritten.states2^mHistoryLastLastWritten.states2;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003675 if (DEBUG) Slog.i(TAG, "ADD: tdelta=" + timeDiff + " diff="
3676 + Integer.toHexString(diffStates) + " lastDiff="
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003677 + Integer.toHexString(lastDiffStates) + " diff2="
3678 + Integer.toHexString(diffStates2) + " lastDiff2="
3679 + Integer.toHexString(lastDiffStates2));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003680 if (mHistoryBufferLastPos >= 0 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003681 && timeDiff < 1000 && (diffStates&lastDiffStates) == 0
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003682 && (diffStates2&lastDiffStates2) == 0
3683 && (mHistoryLastWritten.wakelockTag == null || cur.wakelockTag == null)
3684 && (mHistoryLastWritten.wakeReasonTag == null || cur.wakeReasonTag == null)
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003685 && mHistoryLastWritten.stepDetails == null
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003686 && (mHistoryLastWritten.eventCode == HistoryItem.EVENT_NONE
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003687 || cur.eventCode == HistoryItem.EVENT_NONE)
3688 && mHistoryLastWritten.batteryLevel == cur.batteryLevel
3689 && mHistoryLastWritten.batteryStatus == cur.batteryStatus
3690 && mHistoryLastWritten.batteryHealth == cur.batteryHealth
3691 && mHistoryLastWritten.batteryPlugType == cur.batteryPlugType
3692 && mHistoryLastWritten.batteryTemperature == cur.batteryTemperature
3693 && mHistoryLastWritten.batteryVoltage == cur.batteryVoltage) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003694 // We can merge this new change in with the last one. Merging is
Dianne Hackborn40c87252014-03-19 16:55:40 -07003695 // allowed as long as only the states have changed, and within those states
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003696 // as long as no bit has changed both between now and the last entry, as
3697 // well as the last entry and the one before it (so we capture any toggles).
3698 if (DEBUG) Slog.i(TAG, "ADD: rewinding back to " + mHistoryBufferLastPos);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003699 mHistoryBuffer.setDataSize(mHistoryBufferLastPos);
3700 mHistoryBuffer.setDataPosition(mHistoryBufferLastPos);
3701 mHistoryBufferLastPos = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003702 elapsedRealtimeMs = mHistoryLastWritten.time - mHistoryBaseTime;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003703 // If the last written history had a wakelock tag, we need to retain it.
3704 // Note that the condition above made sure that we aren't in a case where
3705 // both it and the current history item have a wakelock tag.
3706 if (mHistoryLastWritten.wakelockTag != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003707 cur.wakelockTag = cur.localWakelockTag;
3708 cur.wakelockTag.setTo(mHistoryLastWritten.wakelockTag);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003709 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003710 // If the last written history had a wake reason tag, we need to retain it.
3711 // Note that the condition above made sure that we aren't in a case where
3712 // both it and the current history item have a wakelock tag.
3713 if (mHistoryLastWritten.wakeReasonTag != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003714 cur.wakeReasonTag = cur.localWakeReasonTag;
3715 cur.wakeReasonTag.setTo(mHistoryLastWritten.wakeReasonTag);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003716 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003717 // If the last written history had an event, we need to retain it.
3718 // Note that the condition above made sure that we aren't in a case where
3719 // both it and the current history item have an event.
3720 if (mHistoryLastWritten.eventCode != HistoryItem.EVENT_NONE) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003721 cur.eventCode = mHistoryLastWritten.eventCode;
3722 cur.eventTag = cur.localEventTag;
3723 cur.eventTag.setTo(mHistoryLastWritten.eventTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003724 }
Dianne Hackborn1fadab52011-04-14 17:57:33 -07003725 mHistoryLastWritten.setTo(mHistoryLastLastWritten);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003726 }
3727
Adam Lesinski45489782016-12-15 23:45:17 -08003728 boolean recordResetDueToOverflow = false;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003729 final int dataSize = mHistoryBuffer.dataSize();
Adam Lesinski45489782016-12-15 23:45:17 -08003730 if (dataSize >= MAX_MAX_HISTORY_BUFFER*3) {
3731 // Clients can't deal with history buffers this large. This only
3732 // really happens when the device is on charger and interacted with
3733 // for long periods of time, like in retail mode. Since the device is
3734 // most likely charged, when unplugged, stats would have reset anyways.
3735 // Reset the stats and mark that we overflowed.
3736 // b/32540341
3737 resetAllStatsLocked();
3738
3739 // Mark that we want to set *OVERFLOW* event and the RESET:START
3740 // events.
3741 recordResetDueToOverflow = true;
3742
3743 } else if (dataSize >= MAX_HISTORY_BUFFER) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003744 if (!mHistoryOverflow) {
3745 mHistoryOverflow = true;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003746 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, cur);
3747 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_OVERFLOW, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003748 return;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003749 }
3750
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003751 // After overflow, we allow various bit-wise states to settle to 0.
3752 boolean writeAnyway = false;
3753 final int curStates = cur.states & HistoryItem.SETTLE_TO_ZERO_STATES
3754 & mActiveHistoryStates;
3755 if (mHistoryLastWritten.states != curStates) {
3756 // mActiveHistoryStates keeps track of which bits in .states are now being
3757 // forced to 0.
3758 int old = mActiveHistoryStates;
3759 mActiveHistoryStates &= curStates | ~HistoryItem.SETTLE_TO_ZERO_STATES;
3760 writeAnyway |= old != mActiveHistoryStates;
3761 }
3762 final int curStates2 = cur.states2 & HistoryItem.SETTLE_TO_ZERO_STATES2
3763 & mActiveHistoryStates2;
3764 if (mHistoryLastWritten.states2 != curStates2) {
3765 // mActiveHistoryStates2 keeps track of which bits in .states2 are now being
3766 // forced to 0.
3767 int old = mActiveHistoryStates2;
3768 mActiveHistoryStates2 &= curStates2 | ~HistoryItem.SETTLE_TO_ZERO_STATES2;
3769 writeAnyway |= old != mActiveHistoryStates2;
3770 }
3771
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003772 // Once we've reached the maximum number of items, we only
3773 // record changes to the battery level and the most interesting states.
3774 // Once we've reached the maximum maximum number of items, we only
3775 // record changes to the battery level.
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003776 if (!writeAnyway && mHistoryLastWritten.batteryLevel == cur.batteryLevel &&
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003777 (dataSize >= MAX_MAX_HISTORY_BUFFER
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003778 || ((mHistoryLastWritten.states^cur.states)
Dianne Hackborn3251b902014-06-20 14:40:53 -07003779 & HistoryItem.MOST_INTERESTING_STATES) == 0
3780 || ((mHistoryLastWritten.states2^cur.states2)
3781 & HistoryItem.MOST_INTERESTING_STATES2) == 0)) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003782 return;
3783 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003784
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003785 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003786 return;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003787 }
3788
Adam Lesinski45489782016-12-15 23:45:17 -08003789 if (dataSize == 0 || recordResetDueToOverflow) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003790 // The history is currently empty; we need it to start with a time stamp.
3791 cur.currentTime = System.currentTimeMillis();
Adam Lesinski45489782016-12-15 23:45:17 -08003792 if (recordResetDueToOverflow) {
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003793 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_OVERFLOW, cur);
Adam Lesinski45489782016-12-15 23:45:17 -08003794 }
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003795 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_RESET, cur);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003796 }
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003797 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003798 }
3799
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003800 private void addHistoryBufferLocked(long elapsedRealtimeMs, byte cmd, HistoryItem cur) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003801 if (mIteratingHistory) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003802 throw new IllegalStateException("Can't do this while iterating history!");
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003803 }
3804 mHistoryBufferLastPos = mHistoryBuffer.dataPosition();
3805 mHistoryLastLastWritten.setTo(mHistoryLastWritten);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003806 mHistoryLastWritten.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003807 mHistoryLastWritten.states &= mActiveHistoryStates;
3808 mHistoryLastWritten.states2 &= mActiveHistoryStates2;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003809 writeHistoryDelta(mHistoryBuffer, mHistoryLastWritten, mHistoryLastLastWritten);
Dianne Hackborn40c87252014-03-19 16:55:40 -07003810 mLastHistoryElapsedRealtime = elapsedRealtimeMs;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003811 cur.wakelockTag = null;
3812 cur.wakeReasonTag = null;
3813 cur.eventCode = HistoryItem.EVENT_NONE;
3814 cur.eventTag = null;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003815 if (DEBUG_HISTORY) Slog.i(TAG, "Writing history buffer: was " + mHistoryBufferLastPos
3816 + " now " + mHistoryBuffer.dataPosition()
3817 + " size is now " + mHistoryBuffer.dataSize());
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003818 }
3819
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003820 int mChangedStates = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003821 int mChangedStates2 = 0;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003822
Dianne Hackborn40c87252014-03-19 16:55:40 -07003823 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003824 if (mTrackRunningHistoryElapsedRealtime != 0) {
3825 final long diffElapsed = elapsedRealtimeMs - mTrackRunningHistoryElapsedRealtime;
3826 final long diffUptime = uptimeMs - mTrackRunningHistoryUptime;
3827 if (diffUptime < (diffElapsed-20)) {
3828 final long wakeElapsedTime = elapsedRealtimeMs - (diffElapsed - diffUptime);
3829 mHistoryAddTmp.setTo(mHistoryLastWritten);
3830 mHistoryAddTmp.wakelockTag = null;
3831 mHistoryAddTmp.wakeReasonTag = null;
3832 mHistoryAddTmp.eventCode = HistoryItem.EVENT_NONE;
3833 mHistoryAddTmp.states &= ~HistoryItem.STATE_CPU_RUNNING_FLAG;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003834 addHistoryRecordInnerLocked(wakeElapsedTime, mHistoryAddTmp);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003835 }
3836 }
3837 mHistoryCur.states |= HistoryItem.STATE_CPU_RUNNING_FLAG;
3838 mTrackRunningHistoryElapsedRealtime = elapsedRealtimeMs;
3839 mTrackRunningHistoryUptime = uptimeMs;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003840 addHistoryRecordInnerLocked(elapsedRealtimeMs, mHistoryCur);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003841 }
3842
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003843 void addHistoryRecordInnerLocked(long elapsedRealtimeMs, HistoryItem cur) {
3844 addHistoryBufferLocked(elapsedRealtimeMs, cur);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003845
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003846 if (!USE_OLD_HISTORY) {
3847 return;
3848 }
3849
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003850 if (!mHaveBatteryLevel || !mRecordingHistory) {
3851 return;
3852 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003853
3854 // If the current time is basically the same as the last time,
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003855 // and no states have since the last recorded entry changed and
3856 // are now resetting back to their original value, then just collapse
3857 // into one record.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003858 if (mHistoryEnd != null && mHistoryEnd.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn40c87252014-03-19 16:55:40 -07003859 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+1000)
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003860 && ((mHistoryEnd.states^cur.states)&mChangedStates&mActiveHistoryStates) == 0
3861 && ((mHistoryEnd.states2^cur.states2)&mChangedStates2&mActiveHistoryStates2) == 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003862 // If the current is the same as the one before, then we no
3863 // longer need the entry.
3864 if (mHistoryLastEnd != null && mHistoryLastEnd.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn40c87252014-03-19 16:55:40 -07003865 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+500)
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003866 && mHistoryLastEnd.sameNonEvent(cur)) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003867 mHistoryLastEnd.next = null;
3868 mHistoryEnd.next = mHistoryCache;
3869 mHistoryCache = mHistoryEnd;
3870 mHistoryEnd = mHistoryLastEnd;
3871 mHistoryLastEnd = null;
3872 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003873 mChangedStates |= mHistoryEnd.states^(cur.states&mActiveHistoryStates);
3874 mChangedStates2 |= mHistoryEnd.states^(cur.states2&mActiveHistoryStates2);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003875 mHistoryEnd.setTo(mHistoryEnd.time, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003876 }
3877 return;
3878 }
3879
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003880 mChangedStates = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003881 mChangedStates2 = 0;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003882
3883 if (mNumHistoryItems == MAX_HISTORY_ITEMS
3884 || mNumHistoryItems == MAX_MAX_HISTORY_ITEMS) {
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003885 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_OVERFLOW, cur);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07003886 }
3887
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003888 if (mNumHistoryItems >= MAX_HISTORY_ITEMS) {
3889 // Once we've reached the maximum number of items, we only
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003890 // record changes to the battery level and the most interesting states.
3891 // Once we've reached the maximum maximum number of items, we only
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003892 // record changes to the battery level.
3893 if (mHistoryEnd != null && mHistoryEnd.batteryLevel
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003894 == cur.batteryLevel &&
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003895 (mNumHistoryItems >= MAX_MAX_HISTORY_ITEMS
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003896 || ((mHistoryEnd.states^(cur.states&mActiveHistoryStates))
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003897 & HistoryItem.MOST_INTERESTING_STATES) == 0)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003898 return;
3899 }
3900 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003901
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003902 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003903 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003904
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003905 public void addHistoryEventLocked(long elapsedRealtimeMs, long uptimeMs, int code,
Dianne Hackborn40c87252014-03-19 16:55:40 -07003906 String name, int uid) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003907 mHistoryCur.eventCode = code;
3908 mHistoryCur.eventTag = mHistoryCur.localEventTag;
3909 mHistoryCur.eventTag.string = name;
3910 mHistoryCur.eventTag.uid = uid;
Dianne Hackborn4590e522014-03-24 13:36:46 -07003911 addHistoryRecordLocked(elapsedRealtimeMs, uptimeMs);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003912 }
3913
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003914 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs, byte cmd, HistoryItem cur) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003915 HistoryItem rec = mHistoryCache;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003916 if (rec != null) {
3917 mHistoryCache = rec.next;
3918 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003919 rec = new HistoryItem();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003920 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003921 rec.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003922
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003923 addHistoryRecordLocked(rec);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003924 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003925
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003926 void addHistoryRecordLocked(HistoryItem rec) {
3927 mNumHistoryItems++;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003928 rec.next = null;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003929 mHistoryLastEnd = mHistoryEnd;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003930 if (mHistoryEnd != null) {
3931 mHistoryEnd.next = rec;
3932 mHistoryEnd = rec;
3933 } else {
3934 mHistory = mHistoryEnd = rec;
3935 }
3936 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003937
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003938 void clearHistoryLocked() {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003939 if (DEBUG_HISTORY) Slog.i(TAG, "********** CLEARING HISTORY!");
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003940 if (USE_OLD_HISTORY) {
3941 if (mHistory != null) {
3942 mHistoryEnd.next = mHistoryCache;
3943 mHistoryCache = mHistory;
3944 mHistory = mHistoryLastEnd = mHistoryEnd = null;
3945 }
3946 mNumHistoryItems = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003947 }
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003948
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003949 mHistoryBaseTime = 0;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003950 mLastHistoryElapsedRealtime = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003951 mTrackRunningHistoryElapsedRealtime = 0;
3952 mTrackRunningHistoryUptime = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003953
3954 mHistoryBuffer.setDataSize(0);
3955 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003956 mHistoryBuffer.setDataCapacity(MAX_HISTORY_BUFFER / 2);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003957 mHistoryLastLastWritten.clear();
3958 mHistoryLastWritten.clear();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003959 mHistoryTagPool.clear();
3960 mNextHistoryTagIdx = 0;
3961 mNumHistoryTagChars = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003962 mHistoryBufferLastPos = -1;
3963 mHistoryOverflow = false;
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003964 mActiveHistoryStates = 0xffffffff;
3965 mActiveHistoryStates2 = 0xffffffff;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003966 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003967
Andreas Gampe3f24e692018-02-05 13:24:28 -08003968 @GuardedBy("this")
Mike Mac2f518a2017-09-19 16:06:03 -07003969 public void updateTimeBasesLocked(boolean unplugged, int screenState, long uptime,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003970 long realtime) {
Mike Maa7724752017-10-10 15:29:25 -07003971 final boolean screenOff = !isScreenOn(screenState);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003972 final boolean updateOnBatteryTimeBase = unplugged != mOnBatteryTimeBase.isRunning();
3973 final boolean updateOnBatteryScreenOffTimeBase =
3974 (unplugged && screenOff) != mOnBatteryScreenOffTimeBase.isRunning();
Bookatz867c0d72017-03-07 18:23:42 -08003975
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003976 if (updateOnBatteryScreenOffTimeBase || updateOnBatteryTimeBase) {
3977 if (updateOnBatteryScreenOffTimeBase) {
3978 updateKernelWakelocksLocked();
3979 updateBatteryPropertiesLocked();
Bookatz867c0d72017-03-07 18:23:42 -08003980 }
Bookatz82b341172017-09-07 19:06:08 -07003981 // This if{} is only necessary due to SCREEN_OFF_RPM_STATS_ENABLED, which exists because
3982 // updateRpmStatsLocked is too slow to run each screen change. When the speed is
3983 // improved, remove the surrounding if{}.
3984 if (SCREEN_OFF_RPM_STATS_ENABLED || updateOnBatteryTimeBase) {
3985 updateRpmStatsLocked(); // if either OnBattery or OnBatteryScreenOff timebase changes.
3986 }
Adam Lesinski72478f02015-06-17 15:39:43 -07003987 if (DEBUG_ENERGY_CPU) {
Mike Mac2f518a2017-09-19 16:06:03 -07003988 Slog.d(TAG, "Updating cpu time because screen is now "
3989 + Display.stateToString(screenState)
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003990 + " and battery is " + (unplugged ? "on" : "off"));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003991 }
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003992
3993 mOnBatteryTimeBase.setRunning(unplugged, uptime, realtime);
Mike Mac2f518a2017-09-19 16:06:03 -07003994 if (updateOnBatteryTimeBase) {
3995 for (int i = mUidStats.size() - 1; i >= 0; --i) {
3996 mUidStats.valueAt(i).updateOnBatteryBgTimeBase(uptime, realtime);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003997 }
Mike Mac2f518a2017-09-19 16:06:03 -07003998 }
3999 if (updateOnBatteryScreenOffTimeBase) {
4000 mOnBatteryScreenOffTimeBase.setRunning(unplugged && screenOff, uptime, realtime);
4001 for (int i = mUidStats.size() - 1; i >= 0; --i) {
4002 mUidStats.valueAt(i).updateOnBatteryScreenOffBgTimeBase(uptime, realtime);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07004003 }
Bookatzc8c44962017-05-11 12:12:54 -07004004 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004005 }
4006 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07004007
Adam Lesinskie1f480d2017-02-15 18:51:23 -08004008 private void updateBatteryPropertiesLocked() {
4009 try {
4010 IBatteryPropertiesRegistrar registrar = IBatteryPropertiesRegistrar.Stub.asInterface(
4011 ServiceManager.getService("batteryproperties"));
4012 registrar.scheduleUpdate();
4013 } catch (RemoteException e) {
4014 // Ignore.
4015 }
4016 }
4017
Dianne Hackborn099bc622014-01-22 13:39:16 -08004018 public void addIsolatedUidLocked(int isolatedUid, int appUid) {
4019 mIsolatedUids.put(isolatedUid, appUid);
Bookatz90867622018-01-31 15:05:57 -08004020 StatsLog.write(StatsLog.ISOLATED_UID_CHANGED, appUid, isolatedUid,
4021 StatsLog.ISOLATED_UID_CHANGED__EVENT__CREATED);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08004022 final Uid u = getUidStatsLocked(appUid);
4023 u.addIsolatedUid(isolatedUid);
Dianne Hackborn099bc622014-01-22 13:39:16 -08004024 }
4025
Adam Lesinski61db88f2015-07-01 15:05:07 -07004026 /**
4027 * Schedules a read of the latest cpu times before removing the isolated UID.
4028 * @see #removeIsolatedUidLocked(int)
4029 */
4030 public void scheduleRemoveIsolatedUidLocked(int isolatedUid, int appUid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004031 int curUid = mIsolatedUids.get(isolatedUid, -1);
4032 if (curUid == appUid) {
Adam Lesinski61db88f2015-07-01 15:05:07 -07004033 if (mExternalSync != null) {
4034 mExternalSync.scheduleCpuSyncDueToRemovedUid(isolatedUid);
4035 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08004036 }
4037 }
4038
Adam Lesinski61db88f2015-07-01 15:05:07 -07004039 /**
4040 * This should only be called after the cpu times have been read.
4041 * @see #scheduleRemoveIsolatedUidLocked(int, int)
4042 */
Andreas Gampe3f24e692018-02-05 13:24:28 -08004043 @GuardedBy("this")
Adam Lesinski61db88f2015-07-01 15:05:07 -07004044 public void removeIsolatedUidLocked(int isolatedUid) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08004045 StatsLog.write(
Bookatz90867622018-01-31 15:05:57 -08004046 StatsLog.ISOLATED_UID_CHANGED, mIsolatedUids.get(isolatedUid, -1),
4047 isolatedUid, StatsLog.ISOLATED_UID_CHANGED__EVENT__REMOVED);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08004048 final int idx = mIsolatedUids.indexOfKey(isolatedUid);
4049 if (idx >= 0) {
4050 final int ownerUid = mIsolatedUids.valueAt(idx);
4051 final Uid u = getUidStatsLocked(ownerUid);
4052 u.removeIsolatedUid(isolatedUid);
4053 mIsolatedUids.removeAt(idx);
4054 }
Mike Ma234d1822018-03-13 18:53:21 -07004055 mPendingRemovedUids.add(new UidToRemove(isolatedUid, mClocks.elapsedRealtime()));
Adam Lesinski61db88f2015-07-01 15:05:07 -07004056 }
4057
Dianne Hackborn099bc622014-01-22 13:39:16 -08004058 public int mapUid(int uid) {
4059 int isolated = mIsolatedUids.get(uid, -1);
4060 return isolated > 0 ? isolated : uid;
4061 }
4062
4063 public void noteEventLocked(int code, String name, int uid) {
4064 uid = mapUid(uid);
Dianne Hackborn37de0982014-05-09 09:32:18 -07004065 if (!mActiveEvents.updateState(code, name, uid, 0)) {
4066 return;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08004067 }
Joe Onoratoabded112016-02-08 16:49:39 -08004068 final long elapsedRealtime = mClocks.elapsedRealtime();
4069 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -07004070 addHistoryEventLocked(elapsedRealtime, uptime, code, name, uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -08004071 }
4072
Dianne Hackbornd48954f2015-07-22 17:20:33 -07004073 boolean ensureStartClockTime(final long currentTime) {
4074 final long ABOUT_ONE_YEAR = 365*24*60*60*1000L;
4075 if (currentTime > ABOUT_ONE_YEAR && mStartClockTime < (currentTime-ABOUT_ONE_YEAR)) {
4076 // If the start clock time has changed by more than a year, then presumably
4077 // the previous time was completely bogus. So we are going to figure out a
4078 // new time based on how much time has elapsed since we started counting.
Joe Onoratoabded112016-02-08 16:49:39 -08004079 mStartClockTime = currentTime - (mClocks.elapsedRealtime()-(mRealtimeStart/1000));
Dianne Hackbornd48954f2015-07-22 17:20:33 -07004080 return true;
4081 }
4082 return false;
4083 }
4084
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07004085 public void noteCurrentTimeChangedLocked() {
4086 final long currentTime = System.currentTimeMillis();
Joe Onoratoabded112016-02-08 16:49:39 -08004087 final long elapsedRealtime = mClocks.elapsedRealtime();
4088 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07004089 recordCurrentTimeChangeLocked(currentTime, elapsedRealtime, uptime);
Dianne Hackbornd48954f2015-07-22 17:20:33 -07004090 ensureStartClockTime(currentTime);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07004091 }
4092
Dianne Hackborn61659e52014-07-09 16:13:01 -07004093 public void noteProcessStartLocked(String name, int uid) {
4094 uid = mapUid(uid);
4095 if (isOnBattery()) {
4096 Uid u = getUidStatsLocked(uid);
4097 u.getProcessStatsLocked(name).incStartsLocked();
4098 }
4099 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_START, name, uid, 0)) {
4100 return;
4101 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004102 if (!mRecordAllHistory) {
4103 return;
4104 }
Joe Onoratoabded112016-02-08 16:49:39 -08004105 final long elapsedRealtime = mClocks.elapsedRealtime();
4106 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn61659e52014-07-09 16:13:01 -07004107 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_START, name, uid);
4108 }
4109
Dianne Hackborn1e01d162014-12-04 17:46:42 -08004110 public void noteProcessCrashLocked(String name, int uid) {
4111 uid = mapUid(uid);
4112 if (isOnBattery()) {
4113 Uid u = getUidStatsLocked(uid);
4114 u.getProcessStatsLocked(name).incNumCrashesLocked();
4115 }
4116 }
4117
4118 public void noteProcessAnrLocked(String name, int uid) {
4119 uid = mapUid(uid);
4120 if (isOnBattery()) {
4121 Uid u = getUidStatsLocked(uid);
4122 u.getProcessStatsLocked(name).incNumAnrsLocked();
4123 }
4124 }
4125
Dianne Hackborna8d10942015-11-19 17:55:19 -08004126 public void noteUidProcessStateLocked(int uid, int state) {
Amith Yamasanifd3caf62017-07-26 11:48:35 -07004127 int parentUid = mapUid(uid);
4128 if (uid != parentUid) {
4129 // Isolated UIDs process state is already rolled up into parent, so no need to track
4130 // Otherwise the parent's process state will get downgraded incorrectly
4131 return;
4132 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08004133 getUidStatsLocked(uid).updateUidProcessStateLocked(state);
Dianne Hackborn61659e52014-07-09 16:13:01 -07004134 }
4135
4136 public void noteProcessFinishLocked(String name, int uid) {
4137 uid = mapUid(uid);
4138 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_FINISH, name, uid, 0)) {
4139 return;
4140 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004141 if (!mRecordAllHistory) {
4142 return;
4143 }
Joe Onoratoabded112016-02-08 16:49:39 -08004144 final long elapsedRealtime = mClocks.elapsedRealtime();
4145 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004146 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_FINISH, name, uid);
Dianne Hackborn61659e52014-07-09 16:13:01 -07004147 }
4148
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004149 public void noteSyncStartLocked(String name, int uid) {
4150 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004151 final long elapsedRealtime = mClocks.elapsedRealtime();
4152 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004153 getUidStatsLocked(uid).noteStartSyncLocked(name, elapsedRealtime);
4154 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_START, name, uid, 0)) {
4155 return;
4156 }
4157 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_START, name, uid);
4158 }
4159
4160 public void noteSyncFinishLocked(String name, int uid) {
4161 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004162 final long elapsedRealtime = mClocks.elapsedRealtime();
4163 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004164 getUidStatsLocked(uid).noteStopSyncLocked(name, elapsedRealtime);
4165 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_FINISH, name, uid, 0)) {
4166 return;
4167 }
4168 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_FINISH, name, uid);
4169 }
4170
4171 public void noteJobStartLocked(String name, int uid) {
4172 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004173 final long elapsedRealtime = mClocks.elapsedRealtime();
4174 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004175 getUidStatsLocked(uid).noteStartJobLocked(name, elapsedRealtime);
4176 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_START, name, uid, 0)) {
4177 return;
4178 }
4179 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_START, name, uid);
4180 }
4181
Dianne Hackborn94326cb2017-06-28 16:17:20 -07004182 public void noteJobFinishLocked(String name, int uid, int stopReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004183 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004184 final long elapsedRealtime = mClocks.elapsedRealtime();
4185 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07004186 getUidStatsLocked(uid).noteStopJobLocked(name, elapsedRealtime, stopReason);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004187 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_FINISH, name, uid, 0)) {
4188 return;
4189 }
4190 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_FINISH, name, uid);
4191 }
4192
Amith Yamasani977e11f2018-02-16 11:29:54 -08004193 public void noteJobsDeferredLocked(int uid, int numDeferred, long sinceLast) {
4194 uid = mapUid(uid);
4195 getUidStatsLocked(uid).noteJobsDeferredLocked(numDeferred, sinceLast);
4196 }
4197
Narayan Kamath695cf722017-12-21 18:32:47 +00004198 public void noteAlarmStartLocked(String name, WorkSource workSource, int uid) {
4199 noteAlarmStartOrFinishLocked(HistoryItem.EVENT_ALARM_START, name, workSource, uid);
Dianne Hackborn1e383822015-04-10 14:02:33 -07004200 }
4201
Narayan Kamath695cf722017-12-21 18:32:47 +00004202 public void noteAlarmFinishLocked(String name, WorkSource workSource, int uid) {
4203 noteAlarmStartOrFinishLocked(HistoryItem.EVENT_ALARM_FINISH, name, workSource, uid);
4204 }
4205
4206 private void noteAlarmStartOrFinishLocked(int historyItem, String name, WorkSource workSource,
4207 int uid) {
Dianne Hackborn1e383822015-04-10 14:02:33 -07004208 if (!mRecordAllHistory) {
4209 return;
4210 }
Narayan Kamath695cf722017-12-21 18:32:47 +00004211
Joe Onoratoabded112016-02-08 16:49:39 -08004212 final long elapsedRealtime = mClocks.elapsedRealtime();
4213 final long uptime = mClocks.uptimeMillis();
Narayan Kamath695cf722017-12-21 18:32:47 +00004214
4215 if (workSource != null) {
4216 for (int i = 0; i < workSource.size(); ++i) {
4217 uid = mapUid(workSource.get(i));
4218 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4219 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4220 }
4221 }
4222
4223 List<WorkChain> workChains = workSource.getWorkChains();
4224 if (workChains != null) {
4225 for (int i = 0; i < workChains.size(); ++i) {
4226 uid = mapUid(workChains.get(i).getAttributionUid());
4227 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4228 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4229 }
4230 }
4231 }
4232 } else {
4233 uid = mapUid(uid);
4234
4235 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4236 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4237 }
4238 }
4239 }
4240
4241 public void noteWakupAlarmLocked(String packageName, int uid, WorkSource workSource,
4242 String tag) {
Narayan Kamath695cf722017-12-21 18:32:47 +00004243 if (workSource != null) {
4244 for (int i = 0; i < workSource.size(); ++i) {
4245 uid = workSource.get(i);
4246 final String workSourceName = workSource.getName(i);
4247
Tej Singh6f724c42018-01-03 20:02:03 -08004248 if (isOnBattery()) {
4249 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid,
4250 workSourceName != null ? workSourceName : packageName);
4251 pkg.noteWakeupAlarmLocked(tag);
4252 }
Yangster-mac2f5daec2018-01-16 10:23:15 -08004253 StatsLog.write_non_chained(StatsLog.WAKEUP_ALARM_OCCURRED, workSource.get(i),
4254 workSource.getName(i), tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004255 }
4256
4257 ArrayList<WorkChain> workChains = workSource.getWorkChains();
4258 if (workChains != null) {
4259 for (int i = 0; i < workChains.size(); ++i) {
4260 final WorkChain wc = workChains.get(i);
4261 uid = wc.getAttributionUid();
4262
Tej Singh6f724c42018-01-03 20:02:03 -08004263 if (isOnBattery()) {
4264 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid, packageName);
4265 pkg.noteWakeupAlarmLocked(tag);
4266 }
Yangster-macafad8c62018-01-05 22:30:49 -08004267 StatsLog.write(StatsLog.WAKEUP_ALARM_OCCURRED, wc.getUids(), wc.getTags(), tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004268 }
4269 }
4270 } else {
Tej Singh6f724c42018-01-03 20:02:03 -08004271 if (isOnBattery()) {
4272 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid, packageName);
4273 pkg.noteWakeupAlarmLocked(tag);
4274 }
Yangster-mac2f5daec2018-01-16 10:23:15 -08004275 StatsLog.write_non_chained(StatsLog.WAKEUP_ALARM_OCCURRED, uid, null, tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004276 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07004277 }
4278
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004279 private void requestWakelockCpuUpdate() {
Sudheer Shankac57729a2018-02-09 15:44:42 -08004280 mExternalSync.scheduleCpuSyncDueToWakelockChange(DELAY_UPDATE_WAKELOCKS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004281 }
4282
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004283 private void requestImmediateCpuUpdate() {
Sudheer Shankac57729a2018-02-09 15:44:42 -08004284 mExternalSync.scheduleCpuSyncDueToWakelockChange(0 /* delayMillis */);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004285 }
4286
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004287 public void setRecordAllHistoryLocked(boolean enabled) {
4288 mRecordAllHistory = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004289 if (!enabled) {
4290 // Clear out any existing state.
4291 mActiveEvents.removeEvents(HistoryItem.EVENT_WAKE_LOCK);
Dianne Hackborn1e383822015-04-10 14:02:33 -07004292 mActiveEvents.removeEvents(HistoryItem.EVENT_ALARM);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004293 // Record the currently running processes as stopping, now that we are no
4294 // longer tracking them.
4295 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
4296 HistoryItem.EVENT_PROC);
4297 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08004298 long mSecRealtime = mClocks.elapsedRealtime();
4299 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004300 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
4301 SparseIntArray uids = ent.getValue();
4302 for (int j=0; j<uids.size(); j++) {
4303 addHistoryEventLocked(mSecRealtime, mSecUptime,
4304 HistoryItem.EVENT_PROC_FINISH, ent.getKey(), uids.keyAt(j));
4305 }
4306 }
4307 }
4308 } else {
4309 // Record the currently running processes as starting, now that we are tracking them.
4310 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
4311 HistoryItem.EVENT_PROC);
4312 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08004313 long mSecRealtime = mClocks.elapsedRealtime();
4314 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004315 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
4316 SparseIntArray uids = ent.getValue();
4317 for (int j=0; j<uids.size(); j++) {
4318 addHistoryEventLocked(mSecRealtime, mSecUptime,
4319 HistoryItem.EVENT_PROC_START, ent.getKey(), uids.keyAt(j));
4320 }
4321 }
4322 }
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004323 }
4324 }
4325
Dianne Hackborn9a755432014-05-15 17:05:22 -07004326 public void setNoAutoReset(boolean enabled) {
4327 mNoAutoReset = enabled;
4328 }
4329
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004330 public void setPretendScreenOff(boolean pretendScreenOff) {
Mike Mac2f518a2017-09-19 16:06:03 -07004331 if (mPretendScreenOff != pretendScreenOff) {
4332 mPretendScreenOff = pretendScreenOff;
4333 noteScreenStateLocked(pretendScreenOff ? Display.STATE_OFF : Display.STATE_ON);
4334 }
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004335 }
4336
Dianne Hackborn9a755432014-05-15 17:05:22 -07004337 private String mInitialAcquireWakeName;
4338 private int mInitialAcquireWakeUid = -1;
4339
Narayan Kamath81822022017-12-08 11:56:01 +00004340 public void noteStartWakeLocked(int uid, int pid, WorkChain wc, String name, String historyName,
4341 int type, boolean unimportantForLogging, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004342 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004343 if (type == WAKE_TYPE_PARTIAL) {
4344 // Only care about partial wake locks, since full wake locks
4345 // will be canceled when the user puts the screen to sleep.
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004346 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07004347 if (historyName == null) {
4348 historyName = name;
4349 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004350 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07004351 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_START, historyName,
4352 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07004353 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07004354 HistoryItem.EVENT_WAKE_LOCK_START, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07004355 }
4356 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004357 if (mWakeLockNesting == 0) {
4358 mHistoryCur.states |= HistoryItem.STATE_WAKE_LOCK_FLAG;
4359 if (DEBUG_HISTORY) Slog.v(TAG, "Start wake lock to: "
4360 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08004361 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004362 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07004363 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004364 mWakeLockImportant = !unimportantForLogging;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004365 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07004366 } else if (!mWakeLockImportant && !unimportantForLogging
4367 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004368 if (mHistoryLastWritten.wakelockTag != null) {
4369 // We'll try to update the last tag.
4370 mHistoryLastWritten.wakelockTag = null;
4371 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004372 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07004373 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004374 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004375 }
4376 mWakeLockImportant = true;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004377 }
4378 mWakeLockNesting++;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004379 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004380 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07004381 if (mOnBatteryScreenOffTimeBase.isRunning()) {
4382 // We only update the cpu time when a wake lock is acquired if the screen is off.
4383 // If the screen is on, we don't distribute the power amongst partial wakelocks.
4384 if (DEBUG_ENERGY_CPU) {
4385 Slog.d(TAG, "Updating cpu time because of +wake_lock");
4386 }
4387 requestWakelockCpuUpdate();
4388 }
Narayan Kamath81822022017-12-08 11:56:01 +00004389
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004390 getUidStatsLocked(uid).noteStartWakeLocked(pid, name, type, elapsedRealtime);
Narayan Kamath81822022017-12-08 11:56:01 +00004391
Yangster-mac20877162017-12-22 17:19:39 -08004392 if (wc != null) {
Bookatz1a1b0462018-01-12 11:47:03 -08004393 StatsLog.write(StatsLog.WAKELOCK_STATE_CHANGED, wc.getUids(), wc.getTags(),
Bookatz90867622018-01-31 15:05:57 -08004394 getPowerManagerWakeLockLevel(type), name,
4395 StatsLog.WAKELOCK_STATE_CHANGED__STATE__ACQUIRE);
Yangster-macafad8c62018-01-05 22:30:49 -08004396 } else {
Bookatz1a1b0462018-01-12 11:47:03 -08004397 StatsLog.write_non_chained(StatsLog.WAKELOCK_STATE_CHANGED, uid, null,
Bookatz90867622018-01-31 15:05:57 -08004398 getPowerManagerWakeLockLevel(type), name,
4399 StatsLog.WAKELOCK_STATE_CHANGED__STATE__ACQUIRE);
Narayan Kamath81822022017-12-08 11:56:01 +00004400 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004401 }
4402 }
4403
Narayan Kamath81822022017-12-08 11:56:01 +00004404 public void noteStopWakeLocked(int uid, int pid, WorkChain wc, String name, String historyName,
4405 int type, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004406 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004407 if (type == WAKE_TYPE_PARTIAL) {
4408 mWakeLockNesting--;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004409 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07004410 if (historyName == null) {
4411 historyName = name;
4412 }
4413 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName,
4414 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07004415 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07004416 HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07004417 }
4418 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004419 if (mWakeLockNesting == 0) {
4420 mHistoryCur.states &= ~HistoryItem.STATE_WAKE_LOCK_FLAG;
4421 if (DEBUG_HISTORY) Slog.v(TAG, "Stop wake lock to: "
4422 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn37de0982014-05-09 09:32:18 -07004423 mInitialAcquireWakeName = null;
4424 mInitialAcquireWakeUid = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004425 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004426 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004427 }
4428 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07004429 if (mOnBatteryScreenOffTimeBase.isRunning()) {
4430 if (DEBUG_ENERGY_CPU) {
4431 Slog.d(TAG, "Updating cpu time because of -wake_lock");
4432 }
4433 requestWakelockCpuUpdate();
4434 }
Narayan Kamath81822022017-12-08 11:56:01 +00004435
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004436 getUidStatsLocked(uid).noteStopWakeLocked(pid, name, type, elapsedRealtime);
Yangster-mac20877162017-12-22 17:19:39 -08004437 if (wc != null) {
Bookatz1a1b0462018-01-12 11:47:03 -08004438 StatsLog.write(StatsLog.WAKELOCK_STATE_CHANGED, wc.getUids(), wc.getTags(),
Bookatz90867622018-01-31 15:05:57 -08004439 getPowerManagerWakeLockLevel(type), name,
4440 StatsLog.WAKELOCK_STATE_CHANGED__STATE__RELEASE);
Yangster-macafad8c62018-01-05 22:30:49 -08004441 } else {
Bookatz1a1b0462018-01-12 11:47:03 -08004442 StatsLog.write_non_chained(StatsLog.WAKELOCK_STATE_CHANGED, uid, null,
Bookatz90867622018-01-31 15:05:57 -08004443 getPowerManagerWakeLockLevel(type), name,
4444 StatsLog.WAKELOCK_STATE_CHANGED__STATE__RELEASE);
Narayan Kamath81822022017-12-08 11:56:01 +00004445 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004446 }
4447 }
4448
Bookatz1a1b0462018-01-12 11:47:03 -08004449 /**
4450 * Converts BatteryStats wakelock types back into PowerManager wakelock levels.
4451 * This is the inverse map of Notifier.getBatteryStatsWakeLockMonitorType().
4452 * These are estimations, since batterystats loses some of the original data.
4453 * TODO: Delete this. Instead, StatsLog.write should be called from PowerManager's Notifier.
4454 */
4455 private int getPowerManagerWakeLockLevel(int battertStatsWakelockType) {
4456 switch (battertStatsWakelockType) {
4457 // PowerManager.PARTIAL_WAKE_LOCK or PROXIMITY_SCREEN_OFF_WAKE_LOCK
4458 case BatteryStats.WAKE_TYPE_PARTIAL:
4459 return PowerManager.PARTIAL_WAKE_LOCK;
4460
4461 // PowerManager.SCREEN_DIM_WAKE_LOCK or SCREEN_BRIGHT_WAKE_LOCK
4462 case BatteryStats.WAKE_TYPE_FULL:
4463 return PowerManager.FULL_WAKE_LOCK;
4464
4465 case BatteryStats.WAKE_TYPE_DRAW:
4466 return PowerManager.DRAW_WAKE_LOCK;
4467
4468 // It appears that nothing can ever make a Window and PowerManager lacks an equivalent.
4469 case BatteryStats.WAKE_TYPE_WINDOW:
4470 Slog.e(TAG, "Illegal window wakelock type observed in batterystats.");
4471 return -1;
4472
4473 default:
4474 Slog.e(TAG, "Illegal wakelock type in batterystats: " + battertStatsWakelockType);
4475 return -1;
4476 }
4477 }
4478
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004479 public void noteStartWakeFromSourceLocked(WorkSource ws, int pid, String name,
4480 String historyName, int type, boolean unimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08004481 final long elapsedRealtime = mClocks.elapsedRealtime();
4482 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004483 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004484 for (int i=0; i<N; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004485 noteStartWakeLocked(ws.get(i), pid, null, name, historyName, type,
4486 unimportantForLogging, elapsedRealtime, uptime);
4487 }
4488
4489 List<WorkChain> wcs = ws.getWorkChains();
4490 if (wcs != null) {
4491 for (int i = 0; i < wcs.size(); ++i) {
4492 final WorkChain wc = wcs.get(i);
4493 noteStartWakeLocked(wc.getAttributionUid(), pid, wc, name, historyName, type,
4494 unimportantForLogging, elapsedRealtime, uptime);
4495 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004496 }
4497 }
4498
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004499 public void noteChangeWakelockFromSourceLocked(WorkSource ws, int pid, String name,
4500 String historyName, int type, WorkSource newWs, int newPid, String newName,
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004501 String newHistoryName, int newType, boolean newUnimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08004502 final long elapsedRealtime = mClocks.elapsedRealtime();
4503 final long uptime = mClocks.uptimeMillis();
Narayan Kamath81822022017-12-08 11:56:01 +00004504
4505 List<WorkChain>[] wcs = WorkSource.diffChains(ws, newWs);
4506
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004507 // For correct semantics, we start the need worksources first, so that we won't
4508 // make inappropriate history items as if all wake locks went away and new ones
4509 // appeared. This is okay because tracking of wake locks allows nesting.
Narayan Kamath81822022017-12-08 11:56:01 +00004510 //
4511 // First the starts :
Dianne Hackborn40c87252014-03-19 16:55:40 -07004512 final int NN = newWs.size();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004513 for (int i=0; i<NN; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004514 noteStartWakeLocked(newWs.get(i), newPid, null, newName, newHistoryName, newType,
Dianne Hackborn40c87252014-03-19 16:55:40 -07004515 newUnimportantForLogging, elapsedRealtime, uptime);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004516 }
Narayan Kamath81822022017-12-08 11:56:01 +00004517 if (wcs != null) {
4518 List<WorkChain> newChains = wcs[0];
4519 if (newChains != null) {
4520 for (int i = 0; i < newChains.size(); ++i) {
4521 final WorkChain newChain = newChains.get(i);
4522 noteStartWakeLocked(newChain.getAttributionUid(), newPid, newChain, newName,
4523 newHistoryName, newType, newUnimportantForLogging, elapsedRealtime,
4524 uptime);
4525 }
4526 }
4527 }
4528
4529 // Then the stops :
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004530 final int NO = ws.size();
4531 for (int i=0; i<NO; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004532 noteStopWakeLocked(ws.get(i), pid, null, name, historyName, type, elapsedRealtime,
4533 uptime);
4534 }
4535 if (wcs != null) {
4536 List<WorkChain> goneChains = wcs[1];
4537 if (goneChains != null) {
4538 for (int i = 0; i < goneChains.size(); ++i) {
4539 final WorkChain goneChain = goneChains.get(i);
4540 noteStopWakeLocked(goneChain.getAttributionUid(), pid, goneChain, name,
4541 historyName, type, elapsedRealtime, uptime);
4542 }
4543 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004544 }
4545 }
4546
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004547 public void noteStopWakeFromSourceLocked(WorkSource ws, int pid, String name,
4548 String historyName, int type) {
Joe Onoratoabded112016-02-08 16:49:39 -08004549 final long elapsedRealtime = mClocks.elapsedRealtime();
4550 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004551 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004552 for (int i=0; i<N; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004553 noteStopWakeLocked(ws.get(i), pid, null, name, historyName, type, elapsedRealtime,
4554 uptime);
4555 }
4556
4557 List<WorkChain> wcs = ws.getWorkChains();
4558 if (wcs != null) {
4559 for (int i = 0; i < wcs.size(); ++i) {
4560 final WorkChain wc = wcs.get(i);
4561 noteStopWakeLocked(wc.getAttributionUid(), pid, wc, name, historyName, type,
4562 elapsedRealtime, uptime);
4563 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004564 }
4565 }
4566
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004567 public void noteLongPartialWakelockStart(String name, String historyName, int uid) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08004568 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004569 uid, null, name, historyName,
4570 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
Yangster-macafad8c62018-01-05 22:30:49 -08004571
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004572 uid = mapUid(uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004573 noteLongPartialWakeLockStartInternal(name, historyName, uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004574 }
4575
4576 public void noteLongPartialWakelockStartFromSource(String name, String historyName,
4577 WorkSource workSource) {
4578 final int N = workSource.size();
4579 for (int i = 0; i < N; ++i) {
4580 final int uid = mapUid(workSource.get(i));
4581 noteLongPartialWakeLockStartInternal(name, historyName, uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08004582 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004583 workSource.get(i), workSource.getName(i), name, historyName,
4584 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath96a92562018-01-02 18:57:17 +00004585 }
4586
4587 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
4588 if (workChains != null) {
4589 for (int i = 0; i < workChains.size(); ++i) {
4590 final WorkChain workChain = workChains.get(i);
4591 final int uid = workChain.getAttributionUid();
4592 noteLongPartialWakeLockStartInternal(name, historyName, uid);
4593
Yangster-macafad8c62018-01-05 22:30:49 -08004594 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004595 workChain.getUids(), workChain.getTags(), name, historyName,
4596 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath96a92562018-01-02 18:57:17 +00004597 }
4598 }
4599 }
4600
4601 private void noteLongPartialWakeLockStartInternal(String name, String historyName, int uid) {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004602 final long elapsedRealtime = mClocks.elapsedRealtime();
4603 final long uptime = mClocks.uptimeMillis();
4604 if (historyName == null) {
4605 historyName = name;
4606 }
4607 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_START, historyName, uid,
4608 0)) {
4609 return;
4610 }
4611 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_START,
4612 historyName, uid);
4613 }
4614
4615 public void noteLongPartialWakelockFinish(String name, String historyName, int uid) {
Bookatz90867622018-01-31 15:05:57 -08004616 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED, uid, null,
4617 name, historyName, StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
Yangster-macafad8c62018-01-05 22:30:49 -08004618
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004619 uid = mapUid(uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004620 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004621 }
4622
4623 public void noteLongPartialWakelockFinishFromSource(String name, String historyName,
4624 WorkSource workSource) {
4625 final int N = workSource.size();
4626 for (int i = 0; i < N; ++i) {
4627 final int uid = mapUid(workSource.get(i));
4628 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08004629 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004630 workSource.get(i), workSource.getName(i), name, historyName,
4631 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath96a92562018-01-02 18:57:17 +00004632 }
4633
4634 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
4635 if (workChains != null) {
4636 for (int i = 0; i < workChains.size(); ++i) {
4637 final WorkChain workChain = workChains.get(i);
4638 final int uid = workChain.getAttributionUid();
Narayan Kamath96a92562018-01-02 18:57:17 +00004639 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Yangster-macafad8c62018-01-05 22:30:49 -08004640 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004641 workChain.getUids(), workChain.getTags(), name, historyName,
4642 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath96a92562018-01-02 18:57:17 +00004643 }
4644 }
4645 }
4646
4647 private void noteLongPartialWakeLockFinishInternal(String name, String historyName, int uid) {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004648 final long elapsedRealtime = mClocks.elapsedRealtime();
4649 final long uptime = mClocks.uptimeMillis();
4650 if (historyName == null) {
4651 historyName = name;
4652 }
4653 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH, historyName, uid,
4654 0)) {
4655 return;
4656 }
4657 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH,
4658 historyName, uid);
4659 }
4660
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004661 void aggregateLastWakeupUptimeLocked(long uptimeMs) {
4662 if (mLastWakeupReason != null) {
4663 long deltaUptime = uptimeMs - mLastWakeupUptimeMs;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004664 SamplingTimer timer = getWakeupReasonTimerLocked(mLastWakeupReason);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07004665 timer.add(deltaUptime * 1000, 1); // time in in microseconds
Bookatz90867622018-01-31 15:05:57 -08004666 StatsLog.write(StatsLog.KERNEL_WAKEUP_REPORTED, mLastWakeupReason,
4667 /* duration_usec */ deltaUptime * 1000);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004668 mLastWakeupReason = null;
4669 }
4670 }
4671
4672 public void noteWakeupReasonLocked(String reason) {
Joe Onoratoabded112016-02-08 16:49:39 -08004673 final long elapsedRealtime = mClocks.elapsedRealtime();
4674 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004675 if (DEBUG_HISTORY) Slog.v(TAG, "Wakeup reason \"" + reason +"\": "
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004676 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004677 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004678 mHistoryCur.wakeReasonTag = mHistoryCur.localWakeReasonTag;
4679 mHistoryCur.wakeReasonTag.string = reason;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004680 mHistoryCur.wakeReasonTag.uid = 0;
4681 mLastWakeupReason = reason;
4682 mLastWakeupUptimeMs = uptime;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004683 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004684 }
4685
Adam Lesinski72478f02015-06-17 15:39:43 -07004686 public boolean startAddingCpuLocked() {
Sudheer Shankac57729a2018-02-09 15:44:42 -08004687 mExternalSync.cancelCpuSyncDueToWakelockChange();
Adam Lesinski72478f02015-06-17 15:39:43 -07004688 return mOnBatteryInternal;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004689 }
4690
Adam Lesinski72478f02015-06-17 15:39:43 -07004691 public void finishAddingCpuLocked(int totalUTime, int totalSTime, int statUserTime,
4692 int statSystemTime, int statIOWaitTime, int statIrqTime,
4693 int statSoftIrqTime, int statIdleTime) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004694 if (DEBUG) Slog.d(TAG, "Adding cpu: tuser=" + totalUTime + " tsys=" + totalSTime
4695 + " user=" + statUserTime + " sys=" + statSystemTime
4696 + " io=" + statIOWaitTime + " irq=" + statIrqTime
4697 + " sirq=" + statSoftIrqTime + " idle=" + statIdleTime);
4698 mCurStepCpuUserTime += totalUTime;
4699 mCurStepCpuSystemTime += totalSTime;
4700 mCurStepStatUserTime += statUserTime;
4701 mCurStepStatSystemTime += statSystemTime;
4702 mCurStepStatIOWaitTime += statIOWaitTime;
4703 mCurStepStatIrqTime += statIrqTime;
4704 mCurStepStatSoftIrqTime += statSoftIrqTime;
4705 mCurStepStatIdleTime += statIdleTime;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004706 }
4707
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004708 public void noteProcessDiedLocked(int uid, int pid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004709 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004710 Uid u = mUidStats.get(uid);
4711 if (u != null) {
4712 u.mPids.remove(pid);
4713 }
4714 }
4715
4716 public long getProcessWakeTime(int uid, int pid, long realtime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004717 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004718 Uid u = mUidStats.get(uid);
4719 if (u != null) {
4720 Uid.Pid p = u.mPids.get(pid);
4721 if (p != null) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004722 return p.mWakeSumMs + (p.mWakeNesting > 0 ? (realtime - p.mWakeStartMs) : 0);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004723 }
4724 }
4725 return 0;
4726 }
4727
Dianne Hackborn287952c2010-09-22 22:34:31 -07004728 public void reportExcessiveCpuLocked(int uid, String proc, long overTime, long usedTime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004729 uid = mapUid(uid);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004730 Uid u = mUidStats.get(uid);
4731 if (u != null) {
4732 u.reportExcessiveCpuLocked(proc, overTime, usedTime);
4733 }
4734 }
4735
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004736 int mSensorNesting;
4737
4738 public void noteStartSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004739 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004740 final long elapsedRealtime = mClocks.elapsedRealtime();
4741 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004742 if (mSensorNesting == 0) {
4743 mHistoryCur.states |= HistoryItem.STATE_SENSOR_ON_FLAG;
4744 if (DEBUG_HISTORY) Slog.v(TAG, "Start sensor to: "
4745 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004746 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004747 }
4748 mSensorNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004749 getUidStatsLocked(uid).noteStartSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004750 }
4751
4752 public void noteStopSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004753 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004754 final long elapsedRealtime = mClocks.elapsedRealtime();
4755 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004756 mSensorNesting--;
4757 if (mSensorNesting == 0) {
4758 mHistoryCur.states &= ~HistoryItem.STATE_SENSOR_ON_FLAG;
4759 if (DEBUG_HISTORY) Slog.v(TAG, "Stop sensor to: "
4760 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004761 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004762 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004763 getUidStatsLocked(uid).noteStopSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004764 }
4765
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004766 int mGpsNesting;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004767
Narayan Kamath32684dd2018-01-08 17:32:51 +00004768 public void noteGpsChangedLocked(WorkSource oldWs, WorkSource newWs) {
4769 for (int i = 0; i < newWs.size(); ++i) {
4770 noteStartGpsLocked(newWs.get(i), null);
4771 }
4772
4773 for (int i = 0; i < oldWs.size(); ++i) {
4774 noteStopGpsLocked((oldWs.get(i)), null);
4775 }
4776
4777 List<WorkChain>[] wcs = WorkSource.diffChains(oldWs, newWs);
4778 if (wcs != null) {
4779 if (wcs[0] != null) {
4780 final List<WorkChain> newChains = wcs[0];
4781 for (int i = 0; i < newChains.size(); ++i) {
4782 noteStartGpsLocked(-1, newChains.get(i));
4783 }
4784 }
4785
4786 if (wcs[1] != null) {
4787 final List<WorkChain> goneChains = wcs[1];
4788 for (int i = 0; i < goneChains.size(); ++i) {
4789 noteStopGpsLocked(-1, goneChains.get(i));
4790 }
4791 }
4792 }
4793 }
4794
4795 private void noteStartGpsLocked(int uid, WorkChain workChain) {
4796 uid = getAttributionUid(uid, workChain);
Joe Onoratoabded112016-02-08 16:49:39 -08004797 final long elapsedRealtime = mClocks.elapsedRealtime();
4798 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004799 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004800 mHistoryCur.states |= HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004801 if (DEBUG_HISTORY) Slog.v(TAG, "Start GPS to: "
4802 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004803 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004804 }
4805 mGpsNesting++;
Narayan Kamath32684dd2018-01-08 17:32:51 +00004806
4807 if (workChain == null) {
Bookatz90867622018-01-31 15:05:57 -08004808 StatsLog.write_non_chained(StatsLog.GPS_SCAN_STATE_CHANGED, uid, null,
4809 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004810 } else {
4811 StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004812 workChain.getUids(), workChain.getTags(),
4813 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004814 }
4815
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004816 getUidStatsLocked(uid).noteStartGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004817 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004818
Narayan Kamath32684dd2018-01-08 17:32:51 +00004819 private void noteStopGpsLocked(int uid, WorkChain workChain) {
4820 uid = getAttributionUid(uid, workChain);
Joe Onoratoabded112016-02-08 16:49:39 -08004821 final long elapsedRealtime = mClocks.elapsedRealtime();
4822 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004823 mGpsNesting--;
4824 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004825 mHistoryCur.states &= ~HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004826 if (DEBUG_HISTORY) Slog.v(TAG, "Stop GPS to: "
4827 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004828 addHistoryRecordLocked(elapsedRealtime, uptime);
Siddharth Ray78ccaf52017-12-23 16:16:21 -08004829 stopAllGpsSignalQualityTimersLocked(-1);
4830 mGpsSignalQualityBin = -1;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004831 }
Narayan Kamath32684dd2018-01-08 17:32:51 +00004832
4833 if (workChain == null) {
Bookatz90867622018-01-31 15:05:57 -08004834 StatsLog.write_non_chained(StatsLog.GPS_SCAN_STATE_CHANGED, uid, null,
4835 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004836 } else {
4837 StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED, workChain.getUids(),
Bookatz90867622018-01-31 15:05:57 -08004838 workChain.getTags(), StatsLog.GPS_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004839 }
4840
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004841 getUidStatsLocked(uid).noteStopGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004842 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07004843
Siddharth Ray78ccaf52017-12-23 16:16:21 -08004844 public void noteGpsSignalQualityLocked(int signalLevel) {
4845 if (mGpsNesting == 0) {
4846 return;
4847 }
4848 if (signalLevel < 0 || signalLevel >= GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS) {
4849 stopAllGpsSignalQualityTimersLocked(-1);
4850 return;
4851 }
4852 final long elapsedRealtime = mClocks.elapsedRealtime();
4853 final long uptime = mClocks.uptimeMillis();
4854 if (mGpsSignalQualityBin != signalLevel) {
4855 if (mGpsSignalQualityBin >= 0) {
4856 mGpsSignalQualityTimer[mGpsSignalQualityBin].stopRunningLocked(elapsedRealtime);
4857 }
4858 if(!mGpsSignalQualityTimer[signalLevel].isRunningLocked()) {
4859 mGpsSignalQualityTimer[signalLevel].startRunningLocked(elapsedRealtime);
4860 }
4861 mHistoryCur.states2 = (mHistoryCur.states2&~HistoryItem.STATE2_GPS_SIGNAL_QUALITY_MASK)
4862 | (signalLevel << HistoryItem.STATE2_GPS_SIGNAL_QUALITY_SHIFT);
4863 addHistoryRecordLocked(elapsedRealtime, uptime);
4864 mGpsSignalQualityBin = signalLevel;
4865 }
4866 return;
4867 }
4868
Andreas Gampe3f24e692018-02-05 13:24:28 -08004869 @GuardedBy("this")
Jeff Browne95c3cd2014-05-02 16:59:26 -07004870 public void noteScreenStateLocked(int state) {
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004871 state = mPretendScreenOff ? Display.STATE_OFF : state;
Santos Cordone94f0502017-02-24 12:31:20 -08004872
4873 // Battery stats relies on there being 4 states. To accommodate this, new states beyond the
4874 // original 4 are mapped to one of the originals.
4875 if (state > MAX_TRACKED_SCREEN_STATE) {
4876 switch (state) {
4877 case Display.STATE_VR:
4878 state = Display.STATE_ON;
4879 break;
4880 default:
4881 Slog.wtf(TAG, "Unknown screen state (not mapped): " + state);
4882 break;
4883 }
4884 }
4885
Jeff Browne95c3cd2014-05-02 16:59:26 -07004886 if (mScreenState != state) {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08004887 recordDailyStatsIfNeededLocked(true);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004888 final int oldState = mScreenState;
4889 mScreenState = state;
4890 if (DEBUG) Slog.v(TAG, "Screen state: oldState=" + Display.stateToString(oldState)
4891 + ", newState=" + Display.stateToString(state));
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004892
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004893 if (state != Display.STATE_UNKNOWN) {
4894 int stepState = state-1;
Santos Cordone94f0502017-02-24 12:31:20 -08004895 if ((stepState & STEP_LEVEL_MODE_SCREEN_STATE) == stepState) {
4896 mModStepMode |= (mCurStepMode & STEP_LEVEL_MODE_SCREEN_STATE) ^ stepState;
4897 mCurStepMode = (mCurStepMode & ~STEP_LEVEL_MODE_SCREEN_STATE) | stepState;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004898 } else {
4899 Slog.wtf(TAG, "Unexpected screen state: " + state);
4900 }
4901 }
4902
Mike Mac2f518a2017-09-19 16:06:03 -07004903 final long elapsedRealtime = mClocks.elapsedRealtime();
4904 final long uptime = mClocks.uptimeMillis();
4905
4906 boolean updateHistory = false;
4907 if (isScreenDoze(state)) {
4908 mHistoryCur.states |= HistoryItem.STATE_SCREEN_DOZE_FLAG;
4909 mScreenDozeTimer.startRunningLocked(elapsedRealtime);
4910 updateHistory = true;
4911 } else if (isScreenDoze(oldState)) {
4912 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_DOZE_FLAG;
4913 mScreenDozeTimer.stopRunningLocked(elapsedRealtime);
4914 updateHistory = true;
4915 }
4916 if (isScreenOn(state)) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07004917 mHistoryCur.states |= HistoryItem.STATE_SCREEN_ON_FLAG;
4918 if (DEBUG_HISTORY) Slog.v(TAG, "Screen on to: "
4919 + Integer.toHexString(mHistoryCur.states));
Jeff Browne95c3cd2014-05-02 16:59:26 -07004920 mScreenOnTimer.startRunningLocked(elapsedRealtime);
4921 if (mScreenBrightnessBin >= 0) {
4922 mScreenBrightnessTimer[mScreenBrightnessBin].startRunningLocked(elapsedRealtime);
4923 }
Mike Mac2f518a2017-09-19 16:06:03 -07004924 updateHistory = true;
4925 } else if (isScreenOn(oldState)) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07004926 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_ON_FLAG;
4927 if (DEBUG_HISTORY) Slog.v(TAG, "Screen off to: "
4928 + Integer.toHexString(mHistoryCur.states));
Jeff Browne95c3cd2014-05-02 16:59:26 -07004929 mScreenOnTimer.stopRunningLocked(elapsedRealtime);
4930 if (mScreenBrightnessBin >= 0) {
4931 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
4932 }
Mike Mac2f518a2017-09-19 16:06:03 -07004933 updateHistory = true;
4934 }
4935 if (updateHistory) {
4936 if (DEBUG_HISTORY) Slog.v(TAG, "Screen state to: "
4937 + Display.stateToString(state));
4938 addHistoryRecordLocked(elapsedRealtime, uptime);
4939 }
Sudheer Shankac57729a2018-02-09 15:44:42 -08004940 mExternalSync.scheduleCpuSyncDueToScreenStateChange(
4941 mOnBatteryTimeBase.isRunning(), mOnBatteryScreenOffTimeBase.isRunning());
Mike Mac2f518a2017-09-19 16:06:03 -07004942 if (isScreenOn(state)) {
4943 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), state,
4944 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
4945 // Fake a wake lock, so we consider the device waked as long as the screen is on.
Narayan Kamath81822022017-12-08 11:56:01 +00004946 noteStartWakeLocked(-1, -1, null, "screen", null, WAKE_TYPE_PARTIAL, false,
Mike Mac2f518a2017-09-19 16:06:03 -07004947 elapsedRealtime, uptime);
4948 } else if (isScreenOn(oldState)) {
Narayan Kamath81822022017-12-08 11:56:01 +00004949 noteStopWakeLocked(-1, -1, null, "screen", "screen", WAKE_TYPE_PARTIAL,
Jeff Browne95c3cd2014-05-02 16:59:26 -07004950 elapsedRealtime, uptime);
Mike Mac2f518a2017-09-19 16:06:03 -07004951 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), state,
Joe Onoratoabded112016-02-08 16:49:39 -08004952 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
Mike Mac2f518a2017-09-19 16:06:03 -07004953 }
4954 // Update discharge amounts.
4955 if (mOnBatteryInternal) {
4956 updateDischargeScreenLevelsLocked(oldState, state);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08004957 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07004958 }
4959 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004960
Dianne Hackborn617f8772009-03-31 15:04:46 -07004961 public void noteScreenBrightnessLocked(int brightness) {
4962 // Bin the brightness.
4963 int bin = brightness / (256/NUM_SCREEN_BRIGHTNESS_BINS);
4964 if (bin < 0) bin = 0;
4965 else if (bin >= NUM_SCREEN_BRIGHTNESS_BINS) bin = NUM_SCREEN_BRIGHTNESS_BINS-1;
4966 if (mScreenBrightnessBin != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08004967 final long elapsedRealtime = mClocks.elapsedRealtime();
4968 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004969 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_BRIGHTNESS_MASK)
4970 | (bin << HistoryItem.STATE_BRIGHTNESS_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004971 if (DEBUG_HISTORY) Slog.v(TAG, "Screen brightness " + bin + " to: "
4972 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004973 addHistoryRecordLocked(elapsedRealtime, uptime);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004974 if (mScreenState == Display.STATE_ON) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07004975 if (mScreenBrightnessBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004976 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07004977 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004978 mScreenBrightnessTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07004979 }
4980 mScreenBrightnessBin = bin;
4981 }
4982 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004983
Dianne Hackborn617f8772009-03-31 15:04:46 -07004984 public void noteUserActivityLocked(int uid, int event) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08004985 if (mOnBatteryInternal) {
4986 uid = mapUid(uid);
4987 getUidStatsLocked(uid).noteUserActivityLocked(event);
4988 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004989 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004990
Dianne Hackborn280a64e2015-07-13 14:48:08 -07004991 public void noteWakeUpLocked(String reason, int reasonUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004992 final long elapsedRealtime = mClocks.elapsedRealtime();
4993 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn280a64e2015-07-13 14:48:08 -07004994 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SCREEN_WAKE_UP,
4995 reason, reasonUid);
4996 }
4997
Jeff Browne95c3cd2014-05-02 16:59:26 -07004998 public void noteInteractiveLocked(boolean interactive) {
4999 if (mInteractive != interactive) {
Joe Onoratoabded112016-02-08 16:49:39 -08005000 final long elapsedRealtime = mClocks.elapsedRealtime();
Jeff Browne95c3cd2014-05-02 16:59:26 -07005001 mInteractive = interactive;
5002 if (DEBUG) Slog.v(TAG, "Interactive: " + interactive);
5003 if (interactive) {
5004 mInteractiveTimer.startRunningLocked(elapsedRealtime);
5005 } else {
5006 mInteractiveTimer.stopRunningLocked(elapsedRealtime);
5007 }
5008 }
5009 }
5010
Dianne Hackborn1e01d162014-12-04 17:46:42 -08005011 public void noteConnectivityChangedLocked(int type, String extra) {
Joe Onoratoabded112016-02-08 16:49:39 -08005012 final long elapsedRealtime = mClocks.elapsedRealtime();
5013 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08005014 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_CONNECTIVITY_CHANGED,
5015 extra, type);
5016 mNumConnectivityChange++;
5017 }
5018
Adam Lesinski5f056f62016-07-14 16:56:08 -07005019 private void noteMobileRadioApWakeupLocked(final long elapsedRealtimeMillis,
5020 final long uptimeMillis, int uid) {
5021 uid = mapUid(uid);
5022 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
5023 uid);
5024 getUidStatsLocked(uid).noteMobileRadioApWakeupLocked();
5025 }
5026
Adam Lesinski14ae39a2017-05-26 11:50:40 -07005027 /**
5028 * Updates the radio power state and returns true if an external stats collection should occur.
5029 */
5030 public boolean noteMobileRadioPowerStateLocked(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005031 final long elapsedRealtime = mClocks.elapsedRealtime();
5032 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005033 if (mMobileRadioPowerState != powerState) {
5034 long realElapsedRealtimeMs;
5035 final boolean active =
5036 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
5037 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
5038 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07005039 if (uid > 0) {
5040 noteMobileRadioApWakeupLocked(elapsedRealtime, uptime, uid);
5041 }
5042
Adam Lesinski9acfd812016-04-19 18:29:50 -07005043 mMobileRadioActiveStartTime = realElapsedRealtimeMs = timestampNs / (1000 * 1000);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005044 mHistoryCur.states |= HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
5045 } else {
5046 realElapsedRealtimeMs = timestampNs / (1000*1000);
Dianne Hackbornf7097a52014-05-13 09:56:14 -07005047 long lastUpdateTimeMs = mMobileRadioActiveStartTime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005048 if (realElapsedRealtimeMs < lastUpdateTimeMs) {
5049 Slog.wtf(TAG, "Data connection inactive timestamp " + realElapsedRealtimeMs
5050 + " is before start time " + lastUpdateTimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005051 realElapsedRealtimeMs = elapsedRealtime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005052 } else if (realElapsedRealtimeMs < elapsedRealtime) {
5053 mMobileRadioActiveAdjustedTime.addCountLocked(elapsedRealtime
5054 - realElapsedRealtimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005055 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005056 mHistoryCur.states &= ~HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
5057 }
5058 if (DEBUG_HISTORY) Slog.v(TAG, "Mobile network active " + active + " to: "
5059 + Integer.toHexString(mHistoryCur.states));
5060 addHistoryRecordLocked(elapsedRealtime, uptime);
5061 mMobileRadioPowerState = powerState;
Bookatzddccf0a2017-11-28 16:48:14 -08005062 StatsLog.write(StatsLog.MOBILE_RADIO_POWER_STATE_CHANGED, uid, powerState);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005063 if (active) {
5064 mMobileRadioActiveTimer.startRunningLocked(elapsedRealtime);
5065 mMobileRadioActivePerAppTimer.startRunningLocked(elapsedRealtime);
5066 } else {
5067 mMobileRadioActiveTimer.stopRunningLocked(realElapsedRealtimeMs);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005068 mMobileRadioActivePerAppTimer.stopRunningLocked(realElapsedRealtimeMs);
Adam Lesinski14ae39a2017-05-26 11:50:40 -07005069 // Tell the caller to collect radio network/power stats.
5070 return true;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08005071 }
Dianne Hackborne13c4c02014-02-11 17:18:35 -08005072 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -07005073 return false;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08005074 }
5075
Adam Lesinski14ae39a2017-05-26 11:50:40 -07005076 public void notePowerSaveModeLocked(boolean enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005077 if (mPowerSaveModeEnabled != enabled) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07005078 int stepState = enabled ? STEP_LEVEL_MODE_POWER_SAVE : 0;
5079 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_POWER_SAVE) ^ stepState;
5080 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_POWER_SAVE) | stepState;
Joe Onoratoabded112016-02-08 16:49:39 -08005081 final long elapsedRealtime = mClocks.elapsedRealtime();
5082 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005083 mPowerSaveModeEnabled = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005084 if (enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005085 mHistoryCur.states2 |= HistoryItem.STATE2_POWER_SAVE_FLAG;
5086 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode enabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005087 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005088 mPowerSaveModeEnabledTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005089 } else {
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 disabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005092 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005093 mPowerSaveModeEnabledTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005094 }
5095 addHistoryRecordLocked(elapsedRealtime, uptime);
Bookatz90867622018-01-31 15:05:57 -08005096 StatsLog.write(StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED, enabled ?
5097 StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED__STATE__ON :
5098 StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED__STATE__OFF);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005099 }
5100 }
5101
Bookatzddccf0a2017-11-28 16:48:14 -08005102 public void noteDeviceIdleModeLocked(final int mode, String activeReason, int activeUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005103 final long elapsedRealtime = mClocks.elapsedRealtime();
5104 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005105 boolean nowIdling = mode == DEVICE_IDLE_MODE_DEEP;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005106 if (mDeviceIdling && !nowIdling && activeReason == null) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005107 // We don't go out of general idling mode until explicitly taken out of
5108 // device idle through going active or significant motion.
5109 nowIdling = true;
5110 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005111 boolean nowLightIdling = mode == DEVICE_IDLE_MODE_LIGHT;
5112 if (mDeviceLightIdling && !nowLightIdling && !nowIdling && activeReason == null) {
5113 // We don't go out of general light idling mode until explicitly taken out of
5114 // device idle through going active or significant motion.
5115 nowLightIdling = true;
5116 }
5117 if (activeReason != null && (mDeviceIdling || mDeviceLightIdling)) {
5118 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_ACTIVE,
5119 activeReason, activeUid);
5120 }
Bookatzddccf0a2017-11-28 16:48:14 -08005121 if (mDeviceIdling != nowIdling || mDeviceLightIdling != nowLightIdling) {
5122 int statsmode;
5123 if (nowIdling) statsmode = DEVICE_IDLE_MODE_DEEP;
5124 else if (nowLightIdling) statsmode = DEVICE_IDLE_MODE_LIGHT;
5125 else statsmode = DEVICE_IDLE_MODE_OFF;
5126 StatsLog.write(StatsLog.DEVICE_IDLING_MODE_STATE_CHANGED, statsmode);
5127 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005128 if (mDeviceIdling != nowIdling) {
5129 mDeviceIdling = nowIdling;
5130 int stepState = nowIdling ? STEP_LEVEL_MODE_DEVICE_IDLE : 0;
5131 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_DEVICE_IDLE) ^ stepState;
5132 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_DEVICE_IDLE) | stepState;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005133 if (nowIdling) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005134 mDeviceIdlingTimer.startRunningLocked(elapsedRealtime);
5135 } else {
5136 mDeviceIdlingTimer.stopRunningLocked(elapsedRealtime);
5137 }
5138 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005139 if (mDeviceLightIdling != nowLightIdling) {
5140 mDeviceLightIdling = nowLightIdling;
5141 if (nowLightIdling) {
5142 mDeviceLightIdlingTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005143 } else {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005144 mDeviceLightIdlingTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005145 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005146 }
5147 if (mDeviceIdleMode != mode) {
5148 mHistoryCur.states2 = (mHistoryCur.states2 & ~HistoryItem.STATE2_DEVICE_IDLE_MASK)
5149 | (mode << HistoryItem.STATE2_DEVICE_IDLE_SHIFT);
5150 if (DEBUG_HISTORY) Slog.v(TAG, "Device idle mode changed to: "
5151 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005152 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005153 long lastDuration = elapsedRealtime - mLastIdleTimeStart;
5154 mLastIdleTimeStart = elapsedRealtime;
5155 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
5156 if (lastDuration > mLongestLightIdleTime) {
5157 mLongestLightIdleTime = lastDuration;
5158 }
5159 mDeviceIdleModeLightTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005160 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005161 if (lastDuration > mLongestFullIdleTime) {
5162 mLongestFullIdleTime = lastDuration;
5163 }
5164 mDeviceIdleModeFullTimer.stopRunningLocked(elapsedRealtime);
5165 }
5166 if (mode == DEVICE_IDLE_MODE_LIGHT) {
5167 mDeviceIdleModeLightTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005168 } else if (mode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005169 mDeviceIdleModeFullTimer.startRunningLocked(elapsedRealtime);
5170 }
5171 mDeviceIdleMode = mode;
Bookatzddccf0a2017-11-28 16:48:14 -08005172 StatsLog.write(StatsLog.DEVICE_IDLE_MODE_STATE_CHANGED, mode);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005173 }
5174 }
5175
Dianne Hackborn3accca02013-09-20 09:32:11 -07005176 public void notePackageInstalledLocked(String pkgName, long versionCode) {
Joe Onoratoabded112016-02-08 16:49:39 -08005177 final long elapsedRealtime = mClocks.elapsedRealtime();
5178 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3accca02013-09-20 09:32:11 -07005179 // XXX need to figure out what to do with long version codes.
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005180 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_INSTALLED,
Dianne Hackborn3accca02013-09-20 09:32:11 -07005181 pkgName, (int)versionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005182 PackageChange pc = new PackageChange();
5183 pc.mPackageName = pkgName;
5184 pc.mUpdate = true;
5185 pc.mVersionCode = versionCode;
5186 addPackageChange(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005187 }
5188
5189 public void notePackageUninstalledLocked(String pkgName) {
Joe Onoratoabded112016-02-08 16:49:39 -08005190 final long elapsedRealtime = mClocks.elapsedRealtime();
5191 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005192 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_UNINSTALLED,
5193 pkgName, 0);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005194 PackageChange pc = new PackageChange();
5195 pc.mPackageName = pkgName;
5196 pc.mUpdate = true;
5197 addPackageChange(pc);
5198 }
5199
5200 private void addPackageChange(PackageChange pc) {
5201 if (mDailyPackageChanges == null) {
5202 mDailyPackageChanges = new ArrayList<>();
5203 }
5204 mDailyPackageChanges.add(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005205 }
5206
Siddharth Ray78ccaf52017-12-23 16:16:21 -08005207 void stopAllGpsSignalQualityTimersLocked(int except) {
5208 final long elapsedRealtime = mClocks.elapsedRealtime();
5209 for (int i = 0; i < GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
5210 if (i == except) {
5211 continue;
5212 }
5213 while (mGpsSignalQualityTimer[i].isRunningLocked()) {
5214 mGpsSignalQualityTimer[i].stopRunningLocked(elapsedRealtime);
5215 }
5216 }
5217 }
5218
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005219 public void notePhoneOnLocked() {
5220 if (!mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005221 final long elapsedRealtime = mClocks.elapsedRealtime();
5222 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005223 mHistoryCur.states2 |= HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005224 if (DEBUG_HISTORY) Slog.v(TAG, "Phone on to: "
5225 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005226 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005227 mPhoneOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005228 mPhoneOnTimer.startRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005229 }
5230 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005232 public void notePhoneOffLocked() {
5233 if (mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005234 final long elapsedRealtime = mClocks.elapsedRealtime();
5235 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005236 mHistoryCur.states2 &= ~HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005237 if (DEBUG_HISTORY) Slog.v(TAG, "Phone off to: "
5238 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005239 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005240 mPhoneOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005241 mPhoneOnTimer.stopRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005242 }
5243 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07005244
Mike Ma926a97c2018-03-25 02:32:35 -07005245 public void noteUsbConnectionStateLocked(boolean connected) {
5246 int newState = connected ? 2 : 1;
5247 if (mUsbDataState != newState) {
5248 mUsbDataState = newState;
5249 if (connected) {
5250 mHistoryCur.states2 |= HistoryItem.STATE2_USB_DATA_LINK_FLAG;
5251 } else {
5252 mHistoryCur.states2 &= ~HistoryItem.STATE2_USB_DATA_LINK_FLAG;
5253 }
5254 addHistoryRecordLocked(mClocks.elapsedRealtime(), mClocks.uptimeMillis());
5255 }
5256 }
5257
Dianne Hackborn3251b902014-06-20 14:40:53 -07005258 void stopAllPhoneSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005259 final long elapsedRealtime = mClocks.elapsedRealtime();
Wink Saville52840902011-02-18 12:40:47 -08005260 for (int i = 0; i < SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005261 if (i == except) {
5262 continue;
5263 }
5264 while (mPhoneSignalStrengthsTimer[i].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005265 mPhoneSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005266 }
5267 }
5268 }
5269
Dianne Hackborne4a59512010-12-07 11:08:07 -08005270 private int fixPhoneServiceState(int state, int signalBin) {
5271 if (mPhoneSimStateRaw == TelephonyManager.SIM_STATE_ABSENT) {
5272 // In this case we will always be STATE_OUT_OF_SERVICE, so need
5273 // to infer that we are scanning from other data.
5274 if (state == ServiceState.STATE_OUT_OF_SERVICE
Wink Saville52840902011-02-18 12:40:47 -08005275 && signalBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005276 state = ServiceState.STATE_IN_SERVICE;
5277 }
5278 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005279
Dianne Hackborne4a59512010-12-07 11:08:07 -08005280 return state;
5281 }
5282
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005283 private void updateAllPhoneStateLocked(int state, int simState, int strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005284 boolean scanning = false;
5285 boolean newHistory = false;
5286
5287 mPhoneServiceStateRaw = state;
5288 mPhoneSimStateRaw = simState;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005289 mPhoneSignalStrengthBinRaw = strengthBin;
5290
Joe Onoratoabded112016-02-08 16:49:39 -08005291 final long elapsedRealtime = mClocks.elapsedRealtime();
5292 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne4a59512010-12-07 11:08:07 -08005293
5294 if (simState == TelephonyManager.SIM_STATE_ABSENT) {
5295 // In this case we will always be STATE_OUT_OF_SERVICE, so need
5296 // to infer that we are scanning from other data.
5297 if (state == ServiceState.STATE_OUT_OF_SERVICE
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005298 && strengthBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005299 state = ServiceState.STATE_IN_SERVICE;
5300 }
5301 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005302
5303 // If the phone is powered off, stop all timers.
5304 if (state == ServiceState.STATE_POWER_OFF) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005305 strengthBin = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -07005306
Dianne Hackborne4a59512010-12-07 11:08:07 -08005307 // If we are in service, make sure the correct signal string timer is running.
5308 } else if (state == ServiceState.STATE_IN_SERVICE) {
5309 // Bin will be changed below.
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005310
5311 // If we're out of service, we are in the lowest signal strength
5312 // bin and have the scanning bit set.
Amith Yamasanif37447b2009-10-08 18:28:01 -07005313 } else if (state == ServiceState.STATE_OUT_OF_SERVICE) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005314 scanning = true;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005315 strengthBin = SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN;
Amith Yamasanif37447b2009-10-08 18:28:01 -07005316 if (!mPhoneSignalScanningTimer.isRunningLocked()) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005317 mHistoryCur.states |= HistoryItem.STATE_PHONE_SCANNING_FLAG;
Dianne Hackborne4a59512010-12-07 11:08:07 -08005318 newHistory = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005319 if (DEBUG_HISTORY) Slog.v(TAG, "Phone started scanning to: "
5320 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005321 mPhoneSignalScanningTimer.startRunningLocked(elapsedRealtime);
Amith Yamasanif37447b2009-10-08 18:28:01 -07005322 }
5323 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005324
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005325 if (!scanning) {
5326 // If we are no longer scanning, then stop the scanning timer.
5327 if (mPhoneSignalScanningTimer.isRunningLocked()) {
5328 mHistoryCur.states &= ~HistoryItem.STATE_PHONE_SCANNING_FLAG;
5329 if (DEBUG_HISTORY) Slog.v(TAG, "Phone stopped scanning to: "
5330 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08005331 newHistory = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005332 mPhoneSignalScanningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005333 }
5334 }
5335
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005336 if (mPhoneServiceState != state) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005337 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_STATE_MASK)
5338 | (state << HistoryItem.STATE_PHONE_STATE_SHIFT);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005339 if (DEBUG_HISTORY) Slog.v(TAG, "Phone state " + state + " to: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005340 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08005341 newHistory = true;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005342 mPhoneServiceState = state;
5343 }
Dianne Hackborne4a59512010-12-07 11:08:07 -08005344
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005345 if (mPhoneSignalStrengthBin != strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005346 if (mPhoneSignalStrengthBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005347 mPhoneSignalStrengthsTimer[mPhoneSignalStrengthBin].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005348 elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005349 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005350 if (strengthBin >= 0) {
5351 if (!mPhoneSignalStrengthsTimer[strengthBin].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005352 mPhoneSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005353 }
Dianne Hackborn3251b902014-06-20 14:40:53 -07005354 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_MASK)
5355 | (strengthBin << HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_SHIFT);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005356 if (DEBUG_HISTORY) Slog.v(TAG, "Signal strength " + strengthBin + " to: "
Dianne Hackborne4a59512010-12-07 11:08:07 -08005357 + Integer.toHexString(mHistoryCur.states));
5358 newHistory = true;
Bookatze5885242017-10-24 20:10:31 -07005359 StatsLog.write(StatsLog.PHONE_SIGNAL_STRENGTH_CHANGED, strengthBin);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005360 } else {
Dianne Hackborn3251b902014-06-20 14:40:53 -07005361 stopAllPhoneSignalStrengthTimersLocked(-1);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005362 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005363 mPhoneSignalStrengthBin = strengthBin;
Dianne Hackborne4a59512010-12-07 11:08:07 -08005364 }
5365
5366 if (newHistory) {
Dianne Hackborn40c87252014-03-19 16:55:40 -07005367 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005368 }
5369 }
5370
5371 /**
5372 * Telephony stack updates the phone state.
5373 * @param state phone state from ServiceState.getState()
5374 */
5375 public void notePhoneStateLocked(int state, int simState) {
5376 updateAllPhoneStateLocked(state, simState, mPhoneSignalStrengthBinRaw);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07005377 }
5378
Wink Savillee9b06d72009-05-18 21:47:50 -07005379 public void notePhoneSignalStrengthLocked(SignalStrength signalStrength) {
Dianne Hackborn627bba72009-03-24 22:32:56 -07005380 // Bin the strength.
Wink Saville52840902011-02-18 12:40:47 -08005381 int bin = signalStrength.getLevel();
Dianne Hackborne4a59512010-12-07 11:08:07 -08005382 updateAllPhoneStateLocked(mPhoneServiceStateRaw, mPhoneSimStateRaw, bin);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005383 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005384
Dianne Hackborn627bba72009-03-24 22:32:56 -07005385 public void notePhoneDataConnectionStateLocked(int dataType, boolean hasData) {
Tej Singheee317b2018-03-07 19:28:05 -08005386 // BatteryStats uses 0 to represent no network type.
5387 // Telephony does not have a concept of no network type, and uses 0 to represent unknown.
5388 // Unknown is included in DATA_CONNECTION_OTHER.
Dianne Hackborn627bba72009-03-24 22:32:56 -07005389 int bin = DATA_CONNECTION_NONE;
5390 if (hasData) {
Tej Singheee317b2018-03-07 19:28:05 -08005391 if (dataType > 0 && dataType <= TelephonyManager.MAX_NETWORK_TYPE) {
5392 bin = dataType;
5393 } else {
5394 bin = DATA_CONNECTION_OTHER;
Dianne Hackborn627bba72009-03-24 22:32:56 -07005395 }
5396 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07005397 if (DEBUG) Log.i(TAG, "Phone Data Connection -> " + dataType + " = " + hasData);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005398 if (mPhoneDataConnectionType != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005399 final long elapsedRealtime = mClocks.elapsedRealtime();
5400 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005401 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_DATA_CONNECTION_MASK)
5402 | (bin << HistoryItem.STATE_DATA_CONNECTION_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005403 if (DEBUG_HISTORY) Slog.v(TAG, "Data connection " + bin + " to: "
5404 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005405 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005406 if (mPhoneDataConnectionType >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005407 mPhoneDataConnectionsTimer[mPhoneDataConnectionType].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005408 elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005409 }
5410 mPhoneDataConnectionType = bin;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005411 mPhoneDataConnectionsTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005412 }
5413 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005414
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005415 public void noteWifiOnLocked() {
The Android Open Source Project10592532009-03-18 17:39:46 -07005416 if (!mWifiOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005417 final long elapsedRealtime = mClocks.elapsedRealtime();
5418 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005419 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005420 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI on to: "
5421 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005422 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005423 mWifiOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005424 mWifiOnTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005425 scheduleSyncExternalStatsLocked("wifi-off", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07005426 }
5427 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005428
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005429 public void noteWifiOffLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08005430 final long elapsedRealtime = mClocks.elapsedRealtime();
5431 final long uptime = mClocks.uptimeMillis();
The Android Open Source Project10592532009-03-18 17:39:46 -07005432 if (mWifiOn) {
Dianne Hackborn3251b902014-06-20 14:40:53 -07005433 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005434 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI off to: "
5435 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005436 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005437 mWifiOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005438 mWifiOnTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005439 scheduleSyncExternalStatsLocked("wifi-on", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07005440 }
5441 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005442
5443 public void noteAudioOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005444 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005445 final long elapsedRealtime = mClocks.elapsedRealtime();
5446 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005447 if (mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005448 mHistoryCur.states |= HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005449 if (DEBUG_HISTORY) Slog.v(TAG, "Audio on to: "
5450 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005451 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005452 mAudioOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005453 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005454 mAudioOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005455 getUidStatsLocked(uid).noteAudioTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005456 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005457
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005458 public void noteAudioOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005459 if (mAudioOnNesting == 0) {
5460 return;
5461 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08005462 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005463 final long elapsedRealtime = mClocks.elapsedRealtime();
5464 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005465 if (--mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005466 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005467 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
5468 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005469 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005470 mAudioOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005471 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005472 getUidStatsLocked(uid).noteAudioTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005473 }
5474
5475 public void noteVideoOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005476 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005477 final long elapsedRealtime = mClocks.elapsedRealtime();
5478 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005479 if (mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005480 mHistoryCur.states2 |= HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005481 if (DEBUG_HISTORY) Slog.v(TAG, "Video on to: "
5482 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005483 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005484 mVideoOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005485 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005486 mVideoOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005487 getUidStatsLocked(uid).noteVideoTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005488 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005489
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005490 public void noteVideoOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005491 if (mVideoOnNesting == 0) {
5492 return;
5493 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08005494 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005495 final long elapsedRealtime = mClocks.elapsedRealtime();
5496 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005497 if (--mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005498 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005499 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
5500 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005501 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005502 mVideoOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005503 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005504 getUidStatsLocked(uid).noteVideoTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005505 }
5506
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005507 public void noteResetAudioLocked() {
5508 if (mAudioOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005509 final long elapsedRealtime = mClocks.elapsedRealtime();
5510 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005511 mAudioOnNesting = 0;
5512 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
5513 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
5514 + Integer.toHexString(mHistoryCur.states));
5515 addHistoryRecordLocked(elapsedRealtime, uptime);
5516 mAudioOnTimer.stopAllRunningLocked(elapsedRealtime);
5517 for (int i=0; i<mUidStats.size(); i++) {
5518 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5519 uid.noteResetAudioLocked(elapsedRealtime);
5520 }
5521 }
5522 }
5523
5524 public void noteResetVideoLocked() {
5525 if (mVideoOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005526 final long elapsedRealtime = mClocks.elapsedRealtime();
5527 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005528 mAudioOnNesting = 0;
5529 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
5530 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
5531 + Integer.toHexString(mHistoryCur.states));
5532 addHistoryRecordLocked(elapsedRealtime, uptime);
5533 mVideoOnTimer.stopAllRunningLocked(elapsedRealtime);
5534 for (int i=0; i<mUidStats.size(); i++) {
5535 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5536 uid.noteResetVideoLocked(elapsedRealtime);
5537 }
5538 }
5539 }
5540
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005541 public void noteActivityResumedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005542 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005543 getUidStatsLocked(uid).noteActivityResumedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005544 }
5545
5546 public void noteActivityPausedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005547 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005548 getUidStatsLocked(uid).noteActivityPausedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005549 }
5550
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005551 public void noteVibratorOnLocked(int uid, long durationMillis) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005552 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005553 getUidStatsLocked(uid).noteVibratorOnLocked(durationMillis);
5554 }
5555
5556 public void noteVibratorOffLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005557 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005558 getUidStatsLocked(uid).noteVibratorOffLocked();
5559 }
5560
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005561 public void noteFlashlightOnLocked(int uid) {
5562 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005563 final long elapsedRealtime = mClocks.elapsedRealtime();
5564 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005565 if (mFlashlightOnNesting++ == 0) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005566 mHistoryCur.states2 |= HistoryItem.STATE2_FLASHLIGHT_FLAG;
5567 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight on to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005568 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005569 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005570 mFlashlightOnTimer.startRunningLocked(elapsedRealtime);
5571 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005572 getUidStatsLocked(uid).noteFlashlightTurnedOnLocked(elapsedRealtime);
5573 }
5574
5575 public void noteFlashlightOffLocked(int uid) {
5576 if (mFlashlightOnNesting == 0) {
5577 return;
5578 }
5579 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005580 final long elapsedRealtime = mClocks.elapsedRealtime();
5581 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005582 if (--mFlashlightOnNesting == 0) {
5583 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
5584 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
5585 + Integer.toHexString(mHistoryCur.states2));
5586 addHistoryRecordLocked(elapsedRealtime, uptime);
5587 mFlashlightOnTimer.stopRunningLocked(elapsedRealtime);
5588 }
5589 getUidStatsLocked(uid).noteFlashlightTurnedOffLocked(elapsedRealtime);
5590 }
5591
5592 public void noteCameraOnLocked(int uid) {
5593 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005594 final long elapsedRealtime = mClocks.elapsedRealtime();
5595 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005596 if (mCameraOnNesting++ == 0) {
5597 mHistoryCur.states2 |= HistoryItem.STATE2_CAMERA_FLAG;
5598 if (DEBUG_HISTORY) Slog.v(TAG, "Camera on to: "
5599 + Integer.toHexString(mHistoryCur.states2));
5600 addHistoryRecordLocked(elapsedRealtime, uptime);
5601 mCameraOnTimer.startRunningLocked(elapsedRealtime);
5602 }
5603 getUidStatsLocked(uid).noteCameraTurnedOnLocked(elapsedRealtime);
5604 }
5605
5606 public void noteCameraOffLocked(int uid) {
5607 if (mCameraOnNesting == 0) {
5608 return;
5609 }
5610 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005611 final long elapsedRealtime = mClocks.elapsedRealtime();
5612 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005613 if (--mCameraOnNesting == 0) {
5614 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
5615 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
5616 + Integer.toHexString(mHistoryCur.states2));
5617 addHistoryRecordLocked(elapsedRealtime, uptime);
5618 mCameraOnTimer.stopRunningLocked(elapsedRealtime);
5619 }
5620 getUidStatsLocked(uid).noteCameraTurnedOffLocked(elapsedRealtime);
5621 }
5622
5623 public void noteResetCameraLocked() {
5624 if (mCameraOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005625 final long elapsedRealtime = mClocks.elapsedRealtime();
5626 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005627 mCameraOnNesting = 0;
5628 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
5629 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
5630 + Integer.toHexString(mHistoryCur.states2));
5631 addHistoryRecordLocked(elapsedRealtime, uptime);
5632 mCameraOnTimer.stopAllRunningLocked(elapsedRealtime);
5633 for (int i=0; i<mUidStats.size(); i++) {
5634 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5635 uid.noteResetCameraLocked(elapsedRealtime);
5636 }
5637 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005638 }
5639
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005640 public void noteResetFlashlightLocked() {
5641 if (mFlashlightOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005642 final long elapsedRealtime = mClocks.elapsedRealtime();
5643 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005644 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005645 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
5646 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005647 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005648 addHistoryRecordLocked(elapsedRealtime, uptime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005649 mFlashlightOnTimer.stopAllRunningLocked(elapsedRealtime);
5650 for (int i=0; i<mUidStats.size(); i++) {
5651 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5652 uid.noteResetFlashlightLocked(elapsedRealtime);
5653 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005654 }
5655 }
5656
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005657 private void noteBluetoothScanStartedLocked(WorkChain workChain, int uid,
5658 boolean isUnoptimized) {
5659 uid = getAttributionUid(uid, workChain);
Bookatz867c0d72017-03-07 18:23:42 -08005660 final long elapsedRealtime = mClocks.elapsedRealtime();
5661 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005662 if (mBluetoothScanNesting == 0) {
5663 mHistoryCur.states2 |= HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5664 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan started for: "
5665 + Integer.toHexString(mHistoryCur.states2));
5666 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005667 mBluetoothScanTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005668 }
5669 mBluetoothScanNesting++;
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005670
Yangster-macafad8c62018-01-05 22:30:49 -08005671 if (workChain != null) {
5672 StatsLog.write(StatsLog.BLE_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08005673 workChain.getUids(), workChain.getTags(),
5674 StatsLog.BLE_SCAN_STATE_CHANGED__STATE__ON);
Yangster-macafad8c62018-01-05 22:30:49 -08005675 if (isUnoptimized) {
5676 StatsLog.write(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08005677 workChain.getUids(), workChain.getTags(),
5678 StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED__STATE__ON);
Yangster-macafad8c62018-01-05 22:30:49 -08005679 }
5680 } else {
Bookatz90867622018-01-31 15:05:57 -08005681 StatsLog.write_non_chained(StatsLog.BLE_SCAN_STATE_CHANGED, uid, null,
5682 StatsLog.BLE_SCAN_STATE_CHANGED__STATE__ON);
Yangster-macafad8c62018-01-05 22:30:49 -08005683 if (isUnoptimized) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08005684 StatsLog.write_non_chained(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED, uid, null,
Bookatz90867622018-01-31 15:05:57 -08005685 StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED__STATE__ON);
Yangster-macafad8c62018-01-05 22:30:49 -08005686 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005687 }
5688
Bookatzb1f04f32017-05-19 13:57:32 -07005689 getUidStatsLocked(uid).noteBluetoothScanStartedLocked(elapsedRealtime, isUnoptimized);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005690 if (workChain != null) {
5691 getUidStatsLocked(uid).addBluetoothWorkChain(workChain, isUnoptimized);
5692 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005693 }
5694
Bookatzb1f04f32017-05-19 13:57:32 -07005695 public void noteBluetoothScanStartedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005696 final int N = ws.size();
5697 for (int i = 0; i < N; i++) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005698 noteBluetoothScanStartedLocked(null, ws.get(i), isUnoptimized);
5699 }
5700
5701 final List<WorkChain> workChains = ws.getWorkChains();
5702 if (workChains != null) {
5703 for (int i = 0; i < workChains.size(); ++i) {
5704 noteBluetoothScanStartedLocked(workChains.get(i), -1, isUnoptimized);
5705 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005706 }
5707 }
5708
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005709 private void noteBluetoothScanStoppedLocked(WorkChain workChain, int uid,
5710 boolean isUnoptimized) {
5711 uid = getAttributionUid(uid, workChain);
Bookatz867c0d72017-03-07 18:23:42 -08005712 final long elapsedRealtime = mClocks.elapsedRealtime();
5713 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005714 mBluetoothScanNesting--;
5715 if (mBluetoothScanNesting == 0) {
5716 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5717 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan stopped for: "
5718 + Integer.toHexString(mHistoryCur.states2));
5719 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005720 mBluetoothScanTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005721 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005722
Yangster-macafad8c62018-01-05 22:30:49 -08005723 if (workChain != null) {
5724 StatsLog.write(
Bookatz90867622018-01-31 15:05:57 -08005725 StatsLog.BLE_SCAN_STATE_CHANGED, workChain.getUids(), workChain.getTags(),
5726 StatsLog.BLE_SCAN_STATE_CHANGED__STATE__OFF);
Yangster-macafad8c62018-01-05 22:30:49 -08005727 if (isUnoptimized) {
5728 StatsLog.write(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08005729 workChain.getUids(), workChain.getTags(),
5730 StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED__STATE__OFF);
Yangster-macafad8c62018-01-05 22:30:49 -08005731 }
5732 } else {
Bookatz90867622018-01-31 15:05:57 -08005733 StatsLog.write_non_chained(StatsLog.BLE_SCAN_STATE_CHANGED, uid, null,
5734 StatsLog.BLE_SCAN_STATE_CHANGED__STATE__OFF);
Yangster-macafad8c62018-01-05 22:30:49 -08005735 if (isUnoptimized) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08005736 StatsLog.write_non_chained(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED, uid, null,
Bookatz90867622018-01-31 15:05:57 -08005737 StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED__STATE__OFF);
Yangster-macafad8c62018-01-05 22:30:49 -08005738 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005739 }
5740
Bookatz94c5a312017-07-11 16:49:17 -07005741 getUidStatsLocked(uid).noteBluetoothScanStoppedLocked(elapsedRealtime, isUnoptimized);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005742 if (workChain != null) {
5743 getUidStatsLocked(uid).removeBluetoothWorkChain(workChain, isUnoptimized);
5744 }
5745 }
5746
5747 private int getAttributionUid(int uid, WorkChain workChain) {
5748 if (workChain != null) {
5749 return mapUid(workChain.getAttributionUid());
5750 }
5751
5752 return mapUid(uid);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005753 }
5754
Bookatz94c5a312017-07-11 16:49:17 -07005755 public void noteBluetoothScanStoppedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005756 final int N = ws.size();
5757 for (int i = 0; i < N; i++) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005758 noteBluetoothScanStoppedLocked(null, ws.get(i), isUnoptimized);
5759 }
5760
5761 final List<WorkChain> workChains = ws.getWorkChains();
5762 if (workChains != null) {
5763 for (int i = 0; i < workChains.size(); ++i) {
5764 noteBluetoothScanStoppedLocked(workChains.get(i), -1, isUnoptimized);
5765 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005766 }
5767 }
5768
5769 public void noteResetBluetoothScanLocked() {
5770 if (mBluetoothScanNesting > 0) {
Bookatz867c0d72017-03-07 18:23:42 -08005771 final long elapsedRealtime = mClocks.elapsedRealtime();
5772 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005773 mBluetoothScanNesting = 0;
5774 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5775 if (DEBUG_HISTORY) Slog.v(TAG, "BLE can stopped for: "
5776 + Integer.toHexString(mHistoryCur.states2));
5777 addHistoryRecordLocked(elapsedRealtime, uptime);
5778 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtime);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005779
5780
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005781 for (int i=0; i<mUidStats.size(); i++) {
5782 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5783 uid.noteResetBluetoothScanLocked(elapsedRealtime);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005784
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005785 List<WorkChain> allWorkChains = uid.getAllBluetoothWorkChains();
5786 if (allWorkChains != null) {
5787 for (int j = 0; j < allWorkChains.size(); ++j) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005788 StatsLog.write(StatsLog.BLE_SCAN_STATE_CHANGED,
Yangster-macafad8c62018-01-05 22:30:49 -08005789 allWorkChains.get(j).getUids(),
Bookatz90867622018-01-31 15:05:57 -08005790 allWorkChains.get(j).getTags(),
5791 StatsLog.BLE_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005792 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005793 allWorkChains.clear();
5794 }
5795
5796 List<WorkChain> unoptimizedWorkChains = uid.getUnoptimizedBluetoothWorkChains();
5797 if (unoptimizedWorkChains != null) {
5798 for (int j = 0; j < unoptimizedWorkChains.size(); ++j) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005799 StatsLog.write(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED,
Yangster-macafad8c62018-01-05 22:30:49 -08005800 unoptimizedWorkChains.get(j).getUids(),
Bookatz90867622018-01-31 15:05:57 -08005801 unoptimizedWorkChains.get(j).getTags(),
5802 StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005803 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005804 unoptimizedWorkChains.clear();
5805 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005806 }
5807 }
5808 }
5809
Bookatz4ebc0642017-05-11 12:21:19 -07005810 public void noteBluetoothScanResultsFromSourceLocked(WorkSource ws, int numNewResults) {
Bookatz956f36bf2017-04-28 09:48:17 -07005811 final int N = ws.size();
5812 for (int i = 0; i < N; i++) {
5813 int uid = mapUid(ws.get(i));
Bookatz4ebc0642017-05-11 12:21:19 -07005814 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Yangster-mac2f5daec2018-01-16 10:23:15 -08005815 StatsLog.write_non_chained(StatsLog.BLE_SCAN_RESULT_RECEIVED, ws.get(i), ws.getName(i),
5816 numNewResults);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005817 }
5818
5819 final List<WorkChain> workChains = ws.getWorkChains();
5820 if (workChains != null) {
5821 for (int i = 0; i < workChains.size(); ++i) {
5822 final WorkChain wc = workChains.get(i);
5823 int uid = mapUid(wc.getAttributionUid());
5824 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Yangster-macafad8c62018-01-05 22:30:49 -08005825 StatsLog.write(StatsLog.BLE_SCAN_RESULT_RECEIVED,
5826 wc.getUids(), wc.getTags(), numNewResults);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005827 }
Bookatz956f36bf2017-04-28 09:48:17 -07005828 }
5829 }
5830
Adam Lesinski5f056f62016-07-14 16:56:08 -07005831 private void noteWifiRadioApWakeupLocked(final long elapsedRealtimeMillis,
5832 final long uptimeMillis, int uid) {
5833 uid = mapUid(uid);
5834 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
5835 uid);
5836 getUidStatsLocked(uid).noteWifiRadioApWakeupLocked();
5837 }
5838
5839 public void noteWifiRadioPowerState(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005840 final long elapsedRealtime = mClocks.elapsedRealtime();
5841 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005842 if (mWifiRadioPowerState != powerState) {
5843 final boolean active =
5844 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
5845 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
5846 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07005847 if (uid > 0) {
5848 noteWifiRadioApWakeupLocked(elapsedRealtime, uptime, uid);
5849 }
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005850 mHistoryCur.states |= HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
Siddharth Rayb50a6842017-12-14 15:15:28 -08005851 mWifiActiveTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005852 } else {
5853 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
Siddharth Rayb50a6842017-12-14 15:15:28 -08005854 mWifiActiveTimer.stopRunningLocked(
5855 timestampNs / (1000 * 1000));
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005856 }
5857 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi network active " + active + " to: "
5858 + Integer.toHexString(mHistoryCur.states));
5859 addHistoryRecordLocked(elapsedRealtime, uptime);
5860 mWifiRadioPowerState = powerState;
Bookatzddccf0a2017-11-28 16:48:14 -08005861 StatsLog.write(StatsLog.WIFI_RADIO_POWER_STATE_CHANGED, uid, powerState);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005862 }
5863 }
5864
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005865 public void noteWifiRunningLocked(WorkSource ws) {
5866 if (!mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005867 final long elapsedRealtime = mClocks.elapsedRealtime();
5868 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005869 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005870 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI running to: "
5871 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005872 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005873 mGlobalWifiRunning = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005874 mGlobalWifiRunningTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005875 int N = ws.size();
5876 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005877 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005878 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005879 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005880
5881 List<WorkChain> workChains = ws.getWorkChains();
5882 if (workChains != null) {
5883 for (int i = 0; i < workChains.size(); ++i) {
5884 int uid = mapUid(workChains.get(i).getAttributionUid());
5885 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
5886 }
5887 }
5888
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005889 scheduleSyncExternalStatsLocked("wifi-running", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005890 } else {
5891 Log.w(TAG, "noteWifiRunningLocked -- called while WIFI running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005892 }
5893 }
5894
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005895 public void noteWifiRunningChangedLocked(WorkSource oldWs, WorkSource newWs) {
5896 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005897 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005898 int N = oldWs.size();
5899 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005900 int uid = mapUid(oldWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005901 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005902 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005903
5904 List<WorkChain> workChains = oldWs.getWorkChains();
5905 if (workChains != null) {
5906 for (int i = 0; i < workChains.size(); ++i) {
5907 int uid = mapUid(workChains.get(i).getAttributionUid());
5908 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
5909 }
5910 }
5911
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005912 N = newWs.size();
5913 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005914 int uid = mapUid(newWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005915 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005916 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005917
5918 workChains = newWs.getWorkChains();
5919 if (workChains != null) {
5920 for (int i = 0; i < workChains.size(); ++i) {
5921 int uid = mapUid(workChains.get(i).getAttributionUid());
5922 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
5923 }
5924 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005925 } else {
5926 Log.w(TAG, "noteWifiRunningChangedLocked -- called while WIFI not running");
5927 }
5928 }
5929
5930 public void noteWifiStoppedLocked(WorkSource ws) {
5931 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005932 final long elapsedRealtime = mClocks.elapsedRealtime();
5933 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005934 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005935 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI stopped to: "
5936 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005937 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005938 mGlobalWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005939 mGlobalWifiRunningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005940 int N = ws.size();
5941 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005942 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005943 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005944 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005945
5946 List<WorkChain> workChains = ws.getWorkChains();
5947 if (workChains != null) {
5948 for (int i = 0; i < workChains.size(); ++i) {
5949 int uid = mapUid(workChains.get(i).getAttributionUid());
5950 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
5951 }
5952 }
5953
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005954 scheduleSyncExternalStatsLocked("wifi-stopped", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005955 } else {
5956 Log.w(TAG, "noteWifiStoppedLocked -- called while WIFI not running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005957 }
5958 }
5959
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005960 public void noteWifiStateLocked(int wifiState, String accessPoint) {
5961 if (DEBUG) Log.i(TAG, "WiFi state -> " + wifiState);
5962 if (mWifiState != wifiState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005963 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005964 if (mWifiState >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005965 mWifiStateTimer[mWifiState].stopRunningLocked(elapsedRealtime);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005966 }
5967 mWifiState = wifiState;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005968 mWifiStateTimer[wifiState].startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005969 scheduleSyncExternalStatsLocked("wifi-state", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005970 }
5971 }
5972
Dianne Hackborn3251b902014-06-20 14:40:53 -07005973 public void noteWifiSupplicantStateChangedLocked(int supplState, boolean failedAuth) {
5974 if (DEBUG) Log.i(TAG, "WiFi suppl state -> " + supplState);
5975 if (mWifiSupplState != supplState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005976 final long elapsedRealtime = mClocks.elapsedRealtime();
5977 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005978 if (mWifiSupplState >= 0) {
5979 mWifiSupplStateTimer[mWifiSupplState].stopRunningLocked(elapsedRealtime);
5980 }
5981 mWifiSupplState = supplState;
5982 mWifiSupplStateTimer[supplState].startRunningLocked(elapsedRealtime);
5983 mHistoryCur.states2 =
5984 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SUPPL_STATE_MASK)
5985 | (supplState << HistoryItem.STATE2_WIFI_SUPPL_STATE_SHIFT);
5986 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi suppl state " + supplState + " to: "
5987 + Integer.toHexString(mHistoryCur.states2));
5988 addHistoryRecordLocked(elapsedRealtime, uptime);
5989 }
5990 }
5991
5992 void stopAllWifiSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005993 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005994 for (int i = 0; i < NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
5995 if (i == except) {
5996 continue;
5997 }
5998 while (mWifiSignalStrengthsTimer[i].isRunningLocked()) {
5999 mWifiSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
6000 }
6001 }
6002 }
6003
6004 public void noteWifiRssiChangedLocked(int newRssi) {
6005 int strengthBin = WifiManager.calculateSignalLevel(newRssi, NUM_WIFI_SIGNAL_STRENGTH_BINS);
6006 if (DEBUG) Log.i(TAG, "WiFi rssi -> " + newRssi + " bin=" + strengthBin);
6007 if (mWifiSignalStrengthBin != strengthBin) {
Joe Onoratoabded112016-02-08 16:49:39 -08006008 final long elapsedRealtime = mClocks.elapsedRealtime();
6009 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07006010 if (mWifiSignalStrengthBin >= 0) {
6011 mWifiSignalStrengthsTimer[mWifiSignalStrengthBin].stopRunningLocked(
6012 elapsedRealtime);
6013 }
6014 if (strengthBin >= 0) {
6015 if (!mWifiSignalStrengthsTimer[strengthBin].isRunningLocked()) {
6016 mWifiSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
Bookatze5885242017-10-24 20:10:31 -07006017 StatsLog.write(StatsLog.WIFI_SIGNAL_STRENGTH_CHANGED, strengthBin);
Dianne Hackborn3251b902014-06-20 14:40:53 -07006018 }
6019 mHistoryCur.states2 =
6020 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_MASK)
6021 | (strengthBin << HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_SHIFT);
6022 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi signal strength " + strengthBin + " to: "
6023 + Integer.toHexString(mHistoryCur.states2));
6024 addHistoryRecordLocked(elapsedRealtime, uptime);
6025 } else {
6026 stopAllWifiSignalStrengthTimersLocked(-1);
6027 }
6028 mWifiSignalStrengthBin = strengthBin;
6029 }
6030 }
6031
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006032 int mWifiFullLockNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006033
The Android Open Source Project10592532009-03-18 17:39:46 -07006034 public void noteFullWifiLockAcquiredLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006035 final long elapsedRealtime = mClocks.elapsedRealtime();
6036 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006037 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006038 mHistoryCur.states |= HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006039 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock on to: "
6040 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006041 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006042 }
6043 mWifiFullLockNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006044 getUidStatsLocked(uid).noteFullWifiLockAcquiredLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006045 }
6046
6047 public void noteFullWifiLockReleasedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006048 final long elapsedRealtime = mClocks.elapsedRealtime();
6049 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006050 mWifiFullLockNesting--;
6051 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006052 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006053 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock off to: "
6054 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006055 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006056 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006057 getUidStatsLocked(uid).noteFullWifiLockReleasedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006058 }
6059
Nick Pelly6ccaa542012-06-15 15:22:47 -07006060 int mWifiScanNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006061
Nick Pelly6ccaa542012-06-15 15:22:47 -07006062 public void noteWifiScanStartedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006063 final long elapsedRealtime = mClocks.elapsedRealtime();
6064 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07006065 if (mWifiScanNesting == 0) {
6066 mHistoryCur.states |= HistoryItem.STATE_WIFI_SCAN_FLAG;
6067 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan started for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006068 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006069 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006070 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07006071 mWifiScanNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006072 getUidStatsLocked(uid).noteWifiScanStartedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006073 }
6074
Nick Pelly6ccaa542012-06-15 15:22:47 -07006075 public void noteWifiScanStoppedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006076 final long elapsedRealtime = mClocks.elapsedRealtime();
6077 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07006078 mWifiScanNesting--;
6079 if (mWifiScanNesting == 0) {
6080 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_SCAN_FLAG;
6081 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan stopped for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006082 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006083 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006084 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006085 getUidStatsLocked(uid).noteWifiScanStoppedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006086 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006087
Robert Greenwalta029ea12013-09-25 16:38:12 -07006088 public void noteWifiBatchedScanStartedLocked(int uid, int csph) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006089 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006090 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006091 getUidStatsLocked(uid).noteWifiBatchedScanStartedLocked(csph, elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006092 }
6093
6094 public void noteWifiBatchedScanStoppedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006095 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006096 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006097 getUidStatsLocked(uid).noteWifiBatchedScanStoppedLocked(elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006098 }
6099
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006100 int mWifiMulticastNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006101
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006102 public void noteWifiMulticastEnabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006103 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006104 final long elapsedRealtime = mClocks.elapsedRealtime();
6105 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006106 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006107 mHistoryCur.states |= HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006108 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast on to: "
6109 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006110 addHistoryRecordLocked(elapsedRealtime, uptime);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006111
6112 // Start Wifi Multicast overall timer
6113 if (!mWifiMulticastWakelockTimer.isRunningLocked()) {
6114 if (DEBUG_HISTORY) Slog.v(TAG, "WiFi Multicast Overall Timer Started");
6115 mWifiMulticastWakelockTimer.startRunningLocked(elapsedRealtime);
6116 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006117 }
6118 mWifiMulticastNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006119 getUidStatsLocked(uid).noteWifiMulticastEnabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006120 }
6121
6122 public void noteWifiMulticastDisabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006123 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006124 final long elapsedRealtime = mClocks.elapsedRealtime();
6125 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006126 mWifiMulticastNesting--;
6127 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006128 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006129 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast off to: "
6130 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006131 addHistoryRecordLocked(elapsedRealtime, uptime);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006132
6133 // Stop Wifi Multicast overall timer
6134 if (mWifiMulticastWakelockTimer.isRunningLocked()) {
6135 if (DEBUG_HISTORY) Slog.v(TAG, "Multicast Overall Timer Stopped");
6136 mWifiMulticastWakelockTimer.stopRunningLocked(elapsedRealtime);
6137 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006138 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006139 getUidStatsLocked(uid).noteWifiMulticastDisabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006140 }
6141
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006142 public void noteFullWifiLockAcquiredFromSourceLocked(WorkSource ws) {
6143 int N = ws.size();
6144 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006145 final int uid = mapUid(ws.get(i));
6146 noteFullWifiLockAcquiredLocked(uid);
Bookatz90867622018-01-31 15:05:57 -08006147 StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, ws.get(i), ws.getName(i),
6148 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006149 }
6150
6151 final List<WorkChain> workChains = ws.getWorkChains();
6152 if (workChains != null) {
6153 for (int i = 0; i < workChains.size(); ++i) {
6154 final WorkChain workChain = workChains.get(i);
6155 final int uid = mapUid(workChain.getAttributionUid());
6156 noteFullWifiLockAcquiredLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006157 StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006158 workChain.getUids(), workChain.getTags(),
6159 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006160 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006161 }
6162 }
6163
6164 public void noteFullWifiLockReleasedFromSourceLocked(WorkSource ws) {
6165 int N = ws.size();
6166 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006167 final int uid = mapUid(ws.get(i));
6168 noteFullWifiLockReleasedLocked(uid);
Bookatz90867622018-01-31 15:05:57 -08006169 StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, ws.get(i), ws.getName(i),
6170 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006171 }
6172
6173 final List<WorkChain> workChains = ws.getWorkChains();
6174 if (workChains != null) {
6175 for (int i = 0; i < workChains.size(); ++i) {
6176 final WorkChain workChain = workChains.get(i);
6177 final int uid = mapUid(workChain.getAttributionUid());
6178 noteFullWifiLockReleasedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006179 StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006180 workChain.getUids(), workChain.getTags(),
6181 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006182 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006183 }
6184 }
6185
Nick Pelly6ccaa542012-06-15 15:22:47 -07006186 public void noteWifiScanStartedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006187 int N = ws.size();
6188 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006189 final int uid = mapUid(ws.get(i));
6190 noteWifiScanStartedLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08006191 StatsLog.write_non_chained(StatsLog.WIFI_SCAN_STATE_CHANGED, ws.get(i), ws.getName(i),
Bookatz90867622018-01-31 15:05:57 -08006192 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006193 }
6194
6195 final List<WorkChain> workChains = ws.getWorkChains();
6196 if (workChains != null) {
6197 for (int i = 0; i < workChains.size(); ++i) {
6198 final WorkChain workChain = workChains.get(i);
6199 final int uid = mapUid(workChain.getAttributionUid());
6200 noteWifiScanStartedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006201 StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED, workChain.getUids(),
Bookatz90867622018-01-31 15:05:57 -08006202 workChain.getTags(), StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006203 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006204 }
6205 }
6206
Nick Pelly6ccaa542012-06-15 15:22:47 -07006207 public void noteWifiScanStoppedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006208 int N = ws.size();
6209 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006210 final int uid = mapUid(ws.get(i));
6211 noteWifiScanStoppedLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08006212 StatsLog.write_non_chained(StatsLog.WIFI_SCAN_STATE_CHANGED, ws.get(i), ws.getName(i),
Bookatz90867622018-01-31 15:05:57 -08006213 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006214 }
6215
6216 final List<WorkChain> workChains = ws.getWorkChains();
6217 if (workChains != null) {
6218 for (int i = 0; i < workChains.size(); ++i) {
6219 final WorkChain workChain = workChains.get(i);
6220 final int uid = mapUid(workChain.getAttributionUid());
6221 noteWifiScanStoppedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006222 StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006223 workChain.getUids(), workChain.getTags(),
6224 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006225 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006226 }
6227 }
6228
Robert Greenwalta029ea12013-09-25 16:38:12 -07006229 public void noteWifiBatchedScanStartedFromSourceLocked(WorkSource ws, int csph) {
6230 int N = ws.size();
6231 for (int i=0; i<N; i++) {
6232 noteWifiBatchedScanStartedLocked(ws.get(i), csph);
6233 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00006234
6235 final List<WorkChain> workChains = ws.getWorkChains();
6236 if (workChains != null) {
6237 for (int i = 0; i < workChains.size(); ++i) {
6238 noteWifiBatchedScanStartedLocked(workChains.get(i).getAttributionUid(), csph);
6239 }
6240 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006241 }
6242
6243 public void noteWifiBatchedScanStoppedFromSourceLocked(WorkSource ws) {
6244 int N = ws.size();
6245 for (int i=0; i<N; i++) {
6246 noteWifiBatchedScanStoppedLocked(ws.get(i));
6247 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00006248
6249 final List<WorkChain> workChains = ws.getWorkChains();
6250 if (workChains != null) {
6251 for (int i = 0; i < workChains.size(); ++i) {
6252 noteWifiBatchedScanStoppedLocked(workChains.get(i).getAttributionUid());
6253 }
6254 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006255 }
6256
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08006257 private static String[] includeInStringArray(String[] array, String str) {
6258 if (ArrayUtils.indexOf(array, str) >= 0) {
6259 return array;
6260 }
6261 String[] newArray = new String[array.length+1];
6262 System.arraycopy(array, 0, newArray, 0, array.length);
6263 newArray[array.length] = str;
6264 return newArray;
6265 }
6266
6267 private static String[] excludeFromStringArray(String[] array, String str) {
6268 int index = ArrayUtils.indexOf(array, str);
6269 if (index >= 0) {
6270 String[] newArray = new String[array.length-1];
6271 if (index > 0) {
6272 System.arraycopy(array, 0, newArray, 0, index);
6273 }
6274 if (index < array.length-1) {
6275 System.arraycopy(array, index+1, newArray, index, array.length-index-1);
6276 }
6277 return newArray;
6278 }
6279 return array;
6280 }
6281
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07006282 public void noteNetworkInterfaceTypeLocked(String iface, int networkType) {
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07006283 if (TextUtils.isEmpty(iface)) return;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006284
Adam Lesinski14ae39a2017-05-26 11:50:40 -07006285 synchronized (mModemNetworkLock) {
6286 if (ConnectivityManager.isNetworkTypeMobile(networkType)) {
6287 mModemIfaces = includeInStringArray(mModemIfaces, iface);
6288 if (DEBUG) Slog.d(TAG, "Note mobile iface " + iface + ": " + mModemIfaces);
6289 } else {
6290 mModemIfaces = excludeFromStringArray(mModemIfaces, iface);
6291 if (DEBUG) Slog.d(TAG, "Note non-mobile iface " + iface + ": " + mModemIfaces);
6292 }
6293 }
6294
6295 synchronized (mWifiNetworkLock) {
6296 if (ConnectivityManager.isNetworkTypeWifi(networkType)) {
6297 mWifiIfaces = includeInStringArray(mWifiIfaces, iface);
6298 if (DEBUG) Slog.d(TAG, "Note wifi iface " + iface + ": " + mWifiIfaces);
6299 } else {
6300 mWifiIfaces = excludeFromStringArray(mWifiIfaces, iface);
6301 if (DEBUG) Slog.d(TAG, "Note non-wifi iface " + iface + ": " + mWifiIfaces);
6302 }
6303 }
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07006304 }
6305
David Chenc8a43242017-10-17 16:23:28 -07006306 public String[] getWifiIfaces() {
6307 synchronized (mWifiNetworkLock) {
6308 return mWifiIfaces;
6309 }
6310 }
6311
6312 public String[] getMobileIfaces() {
6313 synchronized (mModemNetworkLock) {
6314 return mModemIfaces;
6315 }
6316 }
6317
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006318 @Override public long getScreenOnTime(long elapsedRealtimeUs, int which) {
6319 return mScreenOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006320 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006321
Dianne Hackborn77b987f2014-02-26 16:20:52 -08006322 @Override public int getScreenOnCount(int which) {
6323 return mScreenOnTimer.getCountLocked(which);
6324 }
6325
Mike Mac2f518a2017-09-19 16:06:03 -07006326 @Override public long getScreenDozeTime(long elapsedRealtimeUs, int which) {
6327 return mScreenDozeTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6328 }
6329
6330 @Override public int getScreenDozeCount(int which) {
6331 return mScreenDozeTimer.getCountLocked(which);
6332 }
6333
Dianne Hackborn617f8772009-03-31 15:04:46 -07006334 @Override public long getScreenBrightnessTime(int brightnessBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006335 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006336 return mScreenBrightnessTimer[brightnessBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006337 elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006338 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006339
Kweku Adams87b19ec2017-10-09 12:40:03 -07006340 @Override public Timer getScreenBrightnessTimer(int brightnessBin) {
6341 return mScreenBrightnessTimer[brightnessBin];
6342 }
6343
Jeff Browne95c3cd2014-05-02 16:59:26 -07006344 @Override public long getInteractiveTime(long elapsedRealtimeUs, int which) {
6345 return mInteractiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006346 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006347
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006348 @Override public long getPowerSaveModeEnabledTime(long elapsedRealtimeUs, int which) {
6349 return mPowerSaveModeEnabledTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07006350 }
6351
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006352 @Override public int getPowerSaveModeEnabledCount(int which) {
6353 return mPowerSaveModeEnabledTimer.getCountLocked(which);
6354 }
6355
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006356 @Override public long getDeviceIdleModeTime(int mode, long elapsedRealtimeUs,
6357 int which) {
6358 switch (mode) {
6359 case DEVICE_IDLE_MODE_LIGHT:
6360 return mDeviceIdleModeLightTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006361 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006362 return mDeviceIdleModeFullTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6363 }
6364 return 0;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006365 }
6366
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006367 @Override public int getDeviceIdleModeCount(int mode, int which) {
6368 switch (mode) {
6369 case DEVICE_IDLE_MODE_LIGHT:
6370 return mDeviceIdleModeLightTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006371 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006372 return mDeviceIdleModeFullTimer.getCountLocked(which);
6373 }
6374 return 0;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07006375 }
6376
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006377 @Override public long getLongestDeviceIdleModeTime(int mode) {
6378 switch (mode) {
6379 case DEVICE_IDLE_MODE_LIGHT:
6380 return mLongestLightIdleTime;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006381 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006382 return mLongestFullIdleTime;
6383 }
6384 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07006385 }
6386
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006387 @Override public long getDeviceIdlingTime(int mode, long elapsedRealtimeUs, int which) {
6388 switch (mode) {
6389 case DEVICE_IDLE_MODE_LIGHT:
6390 return mDeviceLightIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006391 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006392 return mDeviceIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6393 }
6394 return 0;
6395 }
6396
6397 @Override public int getDeviceIdlingCount(int mode, int which) {
6398 switch (mode) {
6399 case DEVICE_IDLE_MODE_LIGHT:
6400 return mDeviceLightIdlingTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006401 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006402 return mDeviceIdlingTimer.getCountLocked(which);
6403 }
6404 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07006405 }
6406
Dianne Hackborn1e01d162014-12-04 17:46:42 -08006407 @Override public int getNumConnectivityChange(int which) {
6408 int val = mNumConnectivityChange;
6409 if (which == STATS_CURRENT) {
6410 val -= mLoadedNumConnectivityChange;
6411 } else if (which == STATS_SINCE_UNPLUGGED) {
6412 val -= mUnpluggedNumConnectivityChange;
6413 }
6414 return val;
6415 }
6416
Siddharth Ray78ccaf52017-12-23 16:16:21 -08006417 @Override public long getGpsSignalQualityTime(int strengthBin,
6418 long elapsedRealtimeUs, int which) {
6419 if (strengthBin < 0 || strengthBin >= GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS) {
6420 return 0;
6421 }
6422 return mGpsSignalQualityTimer[strengthBin].getTotalTimeLocked(
6423 elapsedRealtimeUs, which);
6424 }
6425
6426 @Override public long getGpsBatteryDrainMaMs() {
Siddharth Ray0ed2e952018-01-22 11:32:14 -08006427 final double opVolt = mPowerProfile.getAveragePower(
6428 PowerProfile.POWER_GPS_OPERATING_VOLTAGE) / 1000.0;
6429 if (opVolt == 0) {
6430 return 0;
6431 }
6432 double energyUsedMaMs = 0.0;
6433 final int which = STATS_SINCE_CHARGED;
6434 final long rawRealtime = SystemClock.elapsedRealtime() * 1000;
6435 for(int i=0; i < GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
6436 energyUsedMaMs
6437 += mPowerProfile.getAveragePower(PowerProfile.POWER_GPS_SIGNAL_QUALITY_BASED, i)
6438 * (getGpsSignalQualityTime(i, rawRealtime, which) / 1000);
6439 }
6440 return (long) energyUsedMaMs;
Siddharth Ray78ccaf52017-12-23 16:16:21 -08006441 }
6442
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006443 @Override public long getPhoneOnTime(long elapsedRealtimeUs, int which) {
6444 return mPhoneOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006445 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006446
Dianne Hackborn77b987f2014-02-26 16:20:52 -08006447 @Override public int getPhoneOnCount(int which) {
6448 return mPhoneOnTimer.getCountLocked(which);
6449 }
6450
Dianne Hackborn627bba72009-03-24 22:32:56 -07006451 @Override public long getPhoneSignalStrengthTime(int strengthBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006452 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006453 return mPhoneSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006454 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07006455 }
Amith Yamasanif37447b2009-10-08 18:28:01 -07006456
6457 @Override public long getPhoneSignalScanningTime(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006458 long elapsedRealtimeUs, int which) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07006459 return mPhoneSignalScanningTimer.getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006460 elapsedRealtimeUs, which);
Amith Yamasanif37447b2009-10-08 18:28:01 -07006461 }
6462
Kweku Adams87b19ec2017-10-09 12:40:03 -07006463 @Override public Timer getPhoneSignalScanningTimer() {
6464 return mPhoneSignalScanningTimer;
6465 }
6466
Catherine Liufb900812012-07-17 14:12:56 -05006467 @Override public int getPhoneSignalStrengthCount(int strengthBin, int which) {
6468 return mPhoneSignalStrengthsTimer[strengthBin].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006469 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006470
Kweku Adams87b19ec2017-10-09 12:40:03 -07006471 @Override public Timer getPhoneSignalStrengthTimer(int strengthBin) {
6472 return mPhoneSignalStrengthsTimer[strengthBin];
6473 }
6474
Dianne Hackborn627bba72009-03-24 22:32:56 -07006475 @Override public long getPhoneDataConnectionTime(int dataType,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006476 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006477 return mPhoneDataConnectionsTimer[dataType].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006478 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07006479 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006480
Dianne Hackborn617f8772009-03-31 15:04:46 -07006481 @Override public int getPhoneDataConnectionCount(int dataType, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006482 return mPhoneDataConnectionsTimer[dataType].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006483 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006484
Kweku Adams87b19ec2017-10-09 12:40:03 -07006485 @Override public Timer getPhoneDataConnectionTimer(int dataType) {
6486 return mPhoneDataConnectionsTimer[dataType];
6487 }
6488
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006489 @Override public long getMobileRadioActiveTime(long elapsedRealtimeUs, int which) {
6490 return mMobileRadioActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborne13c4c02014-02-11 17:18:35 -08006491 }
6492
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006493 @Override public int getMobileRadioActiveCount(int which) {
6494 return mMobileRadioActiveTimer.getCountLocked(which);
6495 }
6496
Dianne Hackborna1bd7922014-03-21 11:07:11 -07006497 @Override public long getMobileRadioActiveAdjustedTime(int which) {
6498 return mMobileRadioActiveAdjustedTime.getCountLocked(which);
6499 }
6500
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006501 @Override public long getMobileRadioActiveUnknownTime(int which) {
6502 return mMobileRadioActiveUnknownTime.getCountLocked(which);
6503 }
6504
6505 @Override public int getMobileRadioActiveUnknownCount(int which) {
6506 return (int)mMobileRadioActiveUnknownCount.getCountLocked(which);
6507 }
6508
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006509 @Override public long getWifiMulticastWakelockTime(
6510 long elapsedRealtimeUs, int which) {
6511 return mWifiMulticastWakelockTimer.getTotalTimeLocked(
6512 elapsedRealtimeUs, which);
6513 }
6514
6515 @Override public int getWifiMulticastWakelockCount(int which) {
6516 return mWifiMulticastWakelockTimer.getCountLocked(which);
6517 }
6518
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006519 @Override public long getWifiOnTime(long elapsedRealtimeUs, int which) {
6520 return mWifiOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07006521 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006522
Siddharth Rayb50a6842017-12-14 15:15:28 -08006523 @Override public long getWifiActiveTime(long elapsedRealtimeUs, int which) {
6524 return mWifiActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6525 }
6526
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006527 @Override public long getGlobalWifiRunningTime(long elapsedRealtimeUs, int which) {
6528 return mGlobalWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07006529 }
6530
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006531 @Override public long getWifiStateTime(int wifiState,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006532 long elapsedRealtimeUs, int which) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006533 return mWifiStateTimer[wifiState].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006534 elapsedRealtimeUs, which);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006535 }
6536
6537 @Override public int getWifiStateCount(int wifiState, int which) {
6538 return mWifiStateTimer[wifiState].getCountLocked(which);
6539 }
6540
Kweku Adams87b19ec2017-10-09 12:40:03 -07006541 @Override public Timer getWifiStateTimer(int wifiState) {
6542 return mWifiStateTimer[wifiState];
6543 }
6544
Dianne Hackborn3251b902014-06-20 14:40:53 -07006545 @Override public long getWifiSupplStateTime(int state,
6546 long elapsedRealtimeUs, int which) {
6547 return mWifiSupplStateTimer[state].getTotalTimeLocked(
6548 elapsedRealtimeUs, which);
6549 }
6550
6551 @Override public int getWifiSupplStateCount(int state, int which) {
6552 return mWifiSupplStateTimer[state].getCountLocked(which);
6553 }
6554
Kweku Adams87b19ec2017-10-09 12:40:03 -07006555 @Override public Timer getWifiSupplStateTimer(int state) {
6556 return mWifiSupplStateTimer[state];
6557 }
6558
Dianne Hackborn3251b902014-06-20 14:40:53 -07006559 @Override public long getWifiSignalStrengthTime(int strengthBin,
6560 long elapsedRealtimeUs, int which) {
6561 return mWifiSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
6562 elapsedRealtimeUs, which);
6563 }
6564
6565 @Override public int getWifiSignalStrengthCount(int strengthBin, int which) {
6566 return mWifiSignalStrengthsTimer[strengthBin].getCountLocked(which);
6567 }
6568
Kweku Adams87b19ec2017-10-09 12:40:03 -07006569 @Override public Timer getWifiSignalStrengthTimer(int strengthBin) {
6570 return mWifiSignalStrengthsTimer[strengthBin];
6571 }
6572
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006573 @Override
6574 public ControllerActivityCounter getBluetoothControllerActivity() {
6575 return mBluetoothActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07006576 }
6577
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006578 @Override
6579 public ControllerActivityCounter getWifiControllerActivity() {
6580 return mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -07006581 }
6582
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006583 @Override
6584 public ControllerActivityCounter getModemControllerActivity() {
6585 return mModemActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07006586 }
6587
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006588 @Override
6589 public boolean hasBluetoothActivityReporting() {
6590 return mHasBluetoothReporting;
6591 }
6592
6593 @Override
6594 public boolean hasWifiActivityReporting() {
6595 return mHasWifiReporting;
6596 }
6597
6598 @Override
6599 public boolean hasModemActivityReporting() {
6600 return mHasModemReporting;
Adam Lesinski33dac552015-03-09 15:24:48 -07006601 }
6602
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006603 @Override
6604 public long getFlashlightOnTime(long elapsedRealtimeUs, int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07006605 return mFlashlightOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6606 }
6607
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006608 @Override
6609 public long getFlashlightOnCount(int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07006610 return mFlashlightOnTimer.getCountLocked(which);
6611 }
6612
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006613 @Override
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006614 public long getCameraOnTime(long elapsedRealtimeUs, int which) {
6615 return mCameraOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6616 }
6617
6618 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006619 public long getBluetoothScanTime(long elapsedRealtimeUs, int which) {
6620 return mBluetoothScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6621 }
6622
6623 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006624 public long getNetworkActivityBytes(int type, int which) {
6625 if (type >= 0 && type < mNetworkByteActivityCounters.length) {
6626 return mNetworkByteActivityCounters[type].getCountLocked(which);
6627 } else {
6628 return 0;
6629 }
6630 }
6631
6632 @Override
6633 public long getNetworkActivityPackets(int type, int which) {
6634 if (type >= 0 && type < mNetworkPacketActivityCounters.length) {
6635 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006636 } else {
6637 return 0;
6638 }
6639 }
6640
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08006641 @Override public long getStartClockTime() {
Dianne Hackbornd48954f2015-07-22 17:20:33 -07006642 final long currentTime = System.currentTimeMillis();
6643 if (ensureStartClockTime(currentTime)) {
Joe Onoratoabded112016-02-08 16:49:39 -08006644 recordCurrentTimeChangeLocked(currentTime, mClocks.elapsedRealtime(),
6645 mClocks.uptimeMillis());
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07006646 }
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08006647 return mStartClockTime;
6648 }
6649
Dianne Hackborncd0e3352014-08-07 17:08:09 -07006650 @Override public String getStartPlatformVersion() {
6651 return mStartPlatformVersion;
6652 }
6653
6654 @Override public String getEndPlatformVersion() {
6655 return mEndPlatformVersion;
6656 }
6657
6658 @Override public int getParcelVersion() {
6659 return VERSION;
6660 }
6661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006662 @Override public boolean getIsOnBattery() {
6663 return mOnBattery;
6664 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006666 @Override public SparseArray<? extends BatteryStats.Uid> getUidStats() {
6667 return mUidStats;
6668 }
6669
Adam Lesinski5f056f62016-07-14 16:56:08 -07006670 private static void detachTimerIfNotNull(BatteryStatsImpl.Timer timer) {
6671 if (timer != null) {
6672 timer.detach();
6673 }
6674 }
6675
6676 private static boolean resetTimerIfNotNull(BatteryStatsImpl.Timer timer,
6677 boolean detachIfReset) {
6678 if (timer != null) {
6679 return timer.reset(detachIfReset);
6680 }
6681 return true;
6682 }
6683
Bookatz867c0d72017-03-07 18:23:42 -08006684 private static boolean resetTimerIfNotNull(DualTimer timer, boolean detachIfReset) {
6685 if (timer != null) {
6686 return timer.reset(detachIfReset);
6687 }
6688 return true;
6689 }
6690
Adam Lesinski5f056f62016-07-14 16:56:08 -07006691 private static void detachLongCounterIfNotNull(LongSamplingCounter counter) {
6692 if (counter != null) {
6693 counter.detach();
6694 }
6695 }
6696
6697 private static void resetLongCounterIfNotNull(LongSamplingCounter counter,
6698 boolean detachIfReset) {
6699 if (counter != null) {
6700 counter.reset(detachIfReset);
6701 }
6702 }
6703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006704 /**
6705 * The statistics associated with a particular uid.
6706 */
Joe Onoratoabded112016-02-08 16:49:39 -08006707 public static class Uid extends BatteryStats.Uid {
6708 /**
6709 * BatteryStatsImpl that we are associated with.
6710 */
6711 protected BatteryStatsImpl mBsi;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006713 final int mUid;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006714
Bookatz867c0d72017-03-07 18:23:42 -08006715 /** TimeBase for when uid is in background and device is on battery. */
6716 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6717 public final TimeBase mOnBatteryBackgroundTimeBase;
Bookatzc8c44962017-05-11 12:12:54 -07006718 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6719 public final TimeBase mOnBatteryScreenOffBackgroundTimeBase;
Bookatz867c0d72017-03-07 18:23:42 -08006720
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006721 boolean mWifiRunning;
6722 StopwatchTimer mWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006723
The Android Open Source Project10592532009-03-18 17:39:46 -07006724 boolean mFullWifiLockOut;
Evan Millarc64edde2009-04-18 12:26:32 -07006725 StopwatchTimer mFullWifiLockTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006726
Nick Pelly6ccaa542012-06-15 15:22:47 -07006727 boolean mWifiScanStarted;
Bookatz867c0d72017-03-07 18:23:42 -08006728 DualTimer mWifiScanTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006729
Dianne Hackborn61659e52014-07-09 16:13:01 -07006730 static final int NO_BATCHED_SCAN_STARTED = -1;
Robert Greenwalta029ea12013-09-25 16:38:12 -07006731 int mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
6732 StopwatchTimer[] mWifiBatchedScanTimer;
6733
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006734 boolean mWifiMulticastEnabled;
6735 StopwatchTimer mWifiMulticastTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006736
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006737 StopwatchTimer mAudioTurnedOnTimer;
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006738 StopwatchTimer mVideoTurnedOnTimer;
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006739 StopwatchTimer mFlashlightTurnedOnTimer;
6740 StopwatchTimer mCameraTurnedOnTimer;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006741 StopwatchTimer mForegroundActivityTimer;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006742 StopwatchTimer mForegroundServiceTimer;
Bookatzc8c44962017-05-11 12:12:54 -07006743 /** Total time spent by the uid holding any partial wakelocks. */
6744 DualTimer mAggregatedPartialWakelockTimer;
Bookatz867c0d72017-03-07 18:23:42 -08006745 DualTimer mBluetoothScanTimer;
Bookatzb1f04f32017-05-19 13:57:32 -07006746 DualTimer mBluetoothUnoptimizedScanTimer;
Bookatz956f36bf2017-04-28 09:48:17 -07006747 Counter mBluetoothScanResultCounter;
Bookatzb1f04f32017-05-19 13:57:32 -07006748 Counter mBluetoothScanResultBgCounter;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006749
Dianne Hackborna8d10942015-11-19 17:55:19 -08006750 int mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07006751 StopwatchTimer[] mProcessStateTimer;
6752
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006753 boolean mInForegroundService = false;
6754
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006755 BatchTimer mVibratorOnTimer;
6756
Dianne Hackborn617f8772009-03-31 15:04:46 -07006757 Counter[] mUserActivityCounters;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006758
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006759 LongSamplingCounter[] mNetworkByteActivityCounters;
6760 LongSamplingCounter[] mNetworkPacketActivityCounters;
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006761 LongSamplingCounter mMobileRadioActiveTime;
6762 LongSamplingCounter mMobileRadioActiveCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006764 /**
Adam Lesinski5f056f62016-07-14 16:56:08 -07006765 * How many times this UID woke up the Application Processor due to a Mobile radio packet.
6766 */
6767 private LongSamplingCounter mMobileRadioApWakeupCount;
6768
6769 /**
6770 * How many times this UID woke up the Application Processor due to a Wifi packet.
6771 */
6772 private LongSamplingCounter mWifiRadioApWakeupCount;
6773
6774 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07006775 * The amount of time this uid has kept the WiFi controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006776 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07006777 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006778 private ControllerActivityCounterImpl mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006779
6780 /**
6781 * The amount of time this uid has kept the Bluetooth controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006782 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07006783 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006784 private ControllerActivityCounterImpl mBluetoothControllerActivity;
6785
6786 /**
6787 * The amount of time this uid has kept the Modem controller in idle, tx, and rx mode.
6788 * Can be null if the UID has had no such activity.
6789 */
6790 private ControllerActivityCounterImpl mModemControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006791
6792 /**
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006793 * The CPU times we had at the last history details update.
6794 */
6795 long mLastStepUserTime;
6796 long mLastStepSystemTime;
6797 long mCurStepUserTime;
6798 long mCurStepSystemTime;
6799
Joe Onoratoabded112016-02-08 16:49:39 -08006800 LongSamplingCounter mUserCpuTime;
6801 LongSamplingCounter mSystemCpuTime;
Sudheer Shankaaf857412017-07-21 00:14:24 -07006802 LongSamplingCounter[][] mCpuClusterSpeedTimesUs;
Mike Ma3d422c32017-10-25 11:08:57 -07006803 LongSamplingCounter mCpuActiveTimeMs;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006804
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006805 LongSamplingCounterArray mCpuFreqTimeMs;
6806 LongSamplingCounterArray mScreenOffCpuFreqTimeMs;
Mike Ma3d422c32017-10-25 11:08:57 -07006807 LongSamplingCounterArray mCpuClusterTimesMs;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006808
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006809 LongSamplingCounterArray[] mProcStateTimeMs;
6810 LongSamplingCounterArray[] mProcStateScreenOffTimeMs;
6811
6812 IntArray mChildUids;
6813
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006814 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006815 * The statistics we have collected for this uid's wake locks.
6816 */
Joe Onoratoabded112016-02-08 16:49:39 -08006817 final OverflowArrayMap<Wakelock> mWakelockStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006818
6819 /**
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006820 * The statistics we have collected for this uid's syncs.
6821 */
Bookatz2bffb5b2017-04-13 11:59:33 -07006822 final OverflowArrayMap<DualTimer> mSyncStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006823
6824 /**
6825 * The statistics we have collected for this uid's jobs.
6826 */
Bookatzaa4594a2017-03-24 12:39:56 -07006827 final OverflowArrayMap<DualTimer> mJobStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006828
6829 /**
Dianne Hackborn94326cb2017-06-28 16:17:20 -07006830 * Count of the jobs that have completed and the reasons why they completed.
6831 */
6832 final ArrayMap<String, SparseIntArray> mJobCompletions = new ArrayMap<>();
6833
6834 /**
Amith Yamasani977e11f2018-02-16 11:29:54 -08006835 * Count of app launch events that had associated deferred job counts or info about
6836 * last time a job was run.
6837 */
6838 Counter mJobsDeferredEventCount;
6839
6840 /**
6841 * Count of deferred jobs that were pending when the app was launched or brought to
6842 * the foreground through a user interaction.
6843 */
6844 Counter mJobsDeferredCount;
6845
6846 /**
6847 * Sum of time since the last time a job was run for this app before it was launched.
6848 */
6849 LongSamplingCounter mJobsFreshnessTimeMs;
6850
6851 /**
6852 * Array of counts of instances where the time since the last job was run for the app
6853 * fell within one of the thresholds in {@link #JOB_FRESHNESS_BUCKETS}.
6854 */
6855 final Counter[] mJobsFreshnessBuckets;
6856
6857 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006858 * The statistics we have collected for this uid's sensor activations.
6859 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006860 final SparseArray<Sensor> mSensorStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006861
6862 /**
6863 * The statistics we have collected for this uid's processes.
6864 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006865 final ArrayMap<String, Proc> mProcessStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006866
6867 /**
6868 * The statistics we have collected for this uid's processes.
6869 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006870 final ArrayMap<String, Pkg> mPackageStats = new ArrayMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006871
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006872 /**
6873 * The transient wake stats we have collected for this uid's pids.
6874 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006875 final SparseArray<Pid> mPids = new SparseArray<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006876
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00006877 /**
6878 * The list of WorkChains associated with active bluetooth scans.
6879 *
6880 * NOTE: This is a hack and it only needs to exist because there's a "reset" API that is
6881 * supposed to stop and log all WorkChains that were currently active.
6882 */
6883 ArrayList<WorkChain> mAllBluetoothChains = null;
6884 ArrayList<WorkChain> mUnoptimizedBluetoothChains = null;
6885
Joe Onoratoabded112016-02-08 16:49:39 -08006886 public Uid(BatteryStatsImpl bsi, int uid) {
6887 mBsi = bsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006888 mUid = uid;
Joe Onoratoabded112016-02-08 16:49:39 -08006889
Bookatz867c0d72017-03-07 18:23:42 -08006890 mOnBatteryBackgroundTimeBase = new TimeBase();
6891 mOnBatteryBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
6892 mBsi.mClocks.elapsedRealtime() * 1000);
6893
Bookatzc8c44962017-05-11 12:12:54 -07006894 mOnBatteryScreenOffBackgroundTimeBase = new TimeBase();
6895 mOnBatteryScreenOffBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
6896 mBsi.mClocks.elapsedRealtime() * 1000);
6897
Joe Onoratoabded112016-02-08 16:49:39 -08006898 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6899 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Mike Ma3d422c32017-10-25 11:08:57 -07006900 mCpuActiveTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6901 mCpuClusterTimesMs = new LongSamplingCounterArray(mBsi.mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006902
Dianne Hackborn657153b2016-07-29 14:54:14 -07006903 mWakelockStats = mBsi.new OverflowArrayMap<Wakelock>(uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006904 @Override public Wakelock instantiateObject() {
6905 return new Wakelock(mBsi, Uid.this);
6906 }
6907 };
Bookatz2bffb5b2017-04-13 11:59:33 -07006908 mSyncStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
6909 @Override public DualTimer instantiateObject() {
6910 return new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
6911 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006912 }
6913 };
Bookatzaa4594a2017-03-24 12:39:56 -07006914 mJobStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
6915 @Override public DualTimer instantiateObject() {
6916 return new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
6917 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006918 }
6919 };
6920
6921 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_RUNNING,
6922 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
6923 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, this, FULL_WIFI_LOCK,
6924 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Bookatz867c0d72017-03-07 18:23:42 -08006925 mWifiScanTimer = new DualTimer(mBsi.mClocks, this, WIFI_SCAN,
6926 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006927 mWifiBatchedScanTimer = new StopwatchTimer[NUM_WIFI_BATCHED_SCAN_BINS];
Joe Onoratoabded112016-02-08 16:49:39 -08006928 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_MULTICAST_ENABLED,
6929 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006930 mProcessStateTimer = new StopwatchTimer[NUM_PROCESS_STATE];
Amith Yamasani977e11f2018-02-16 11:29:54 -08006931 mJobsDeferredEventCount = new Counter(mBsi.mOnBatteryTimeBase);
6932 mJobsDeferredCount = new Counter(mBsi.mOnBatteryTimeBase);
6933 mJobsFreshnessTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6934 mJobsFreshnessBuckets = new Counter[JOB_FRESHNESS_BUCKETS.length];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006935 }
6936
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006937 @VisibleForTesting
6938 public void setProcessStateForTest(int procState) {
6939 mProcessState = procState;
6940 }
6941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006942 @Override
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006943 public long[] getCpuFreqTimes(int which) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006944 return nullIfAllZeros(mCpuFreqTimeMs, which);
6945 }
6946
6947 @Override
6948 public long[] getScreenOffCpuFreqTimes(int which) {
6949 return nullIfAllZeros(mScreenOffCpuFreqTimeMs, which);
6950 }
6951
6952 @Override
Mike Ma3d422c32017-10-25 11:08:57 -07006953 public long getCpuActiveTime() {
6954 return mCpuActiveTimeMs.getCountLocked(STATS_SINCE_CHARGED);
6955 }
6956
6957 @Override
6958 public long[] getCpuClusterTimes() {
6959 return nullIfAllZeros(mCpuClusterTimesMs, STATS_SINCE_CHARGED);
6960 }
6961
6962
6963 @Override
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006964 public long[] getCpuFreqTimes(int which, int procState) {
6965 if (which < 0 || which >= NUM_PROCESS_STATE) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006966 return null;
6967 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006968 if (mProcStateTimeMs == null) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006969 return null;
6970 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006971 if (!mBsi.mPerProcStateCpuTimesAvailable) {
6972 mProcStateTimeMs = null;
6973 return null;
6974 }
6975 return nullIfAllZeros(mProcStateTimeMs[procState], which);
6976 }
6977
6978 @Override
6979 public long[] getScreenOffCpuFreqTimes(int which, int procState) {
6980 if (which < 0 || which >= NUM_PROCESS_STATE) {
6981 return null;
6982 }
6983 if (mProcStateScreenOffTimeMs == null) {
6984 return null;
6985 }
6986 if (!mBsi.mPerProcStateCpuTimesAvailable) {
6987 mProcStateScreenOffTimeMs = null;
6988 return null;
6989 }
6990 return nullIfAllZeros(mProcStateScreenOffTimeMs[procState], which);
6991 }
6992
6993 public void addIsolatedUid(int isolatedUid) {
6994 if (mChildUids == null) {
6995 mChildUids = new IntArray();
6996 } else if (mChildUids.indexOf(isolatedUid) >= 0) {
6997 return;
6998 }
6999 mChildUids.add(isolatedUid);
7000 }
7001
7002 public void removeIsolatedUid(int isolatedUid) {
7003 final int idx = mChildUids == null ? -1 : mChildUids.indexOf(isolatedUid);
7004 if (idx < 0) {
7005 return;
7006 }
7007 mChildUids.remove(idx);
7008 }
7009
7010 private long[] nullIfAllZeros(LongSamplingCounterArray cpuTimesMs, int which) {
7011 if (cpuTimesMs == null) {
7012 return null;
7013 }
7014 final long[] counts = cpuTimesMs.getCountsLocked(which);
7015 if (counts == null) {
7016 return null;
7017 }
7018 // Return counts only if at least one of the elements is non-zero.
7019 for (int i = counts.length - 1; i >= 0; --i) {
7020 if (counts[i] != 0) {
7021 return counts;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007022 }
7023 }
7024 return null;
7025 }
7026
Sudheer Shankae544d162017-12-28 17:06:20 -08007027 private void addProcStateTimesMs(int procState, long[] cpuTimesMs, boolean onBattery) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007028 if (mProcStateTimeMs == null) {
7029 mProcStateTimeMs = new LongSamplingCounterArray[NUM_PROCESS_STATE];
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007030 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007031 if (mProcStateTimeMs[procState] == null
7032 || mProcStateTimeMs[procState].getSize() != cpuTimesMs.length) {
7033 mProcStateTimeMs[procState] = new LongSamplingCounterArray(
7034 mBsi.mOnBatteryTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007035 }
Sudheer Shankae544d162017-12-28 17:06:20 -08007036 mProcStateTimeMs[procState].addCountLocked(cpuTimesMs, onBattery);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007037 }
7038
Sudheer Shankae544d162017-12-28 17:06:20 -08007039 private void addProcStateScreenOffTimesMs(int procState, long[] cpuTimesMs,
7040 boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007041 if (mProcStateScreenOffTimeMs == null) {
7042 mProcStateScreenOffTimeMs = new LongSamplingCounterArray[NUM_PROCESS_STATE];
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007043 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007044 if (mProcStateScreenOffTimeMs[procState] == null
7045 || mProcStateScreenOffTimeMs[procState].getSize() != cpuTimesMs.length) {
7046 mProcStateScreenOffTimeMs[procState] = new LongSamplingCounterArray(
7047 mBsi.mOnBatteryScreenOffTimeBase);
7048 }
Sudheer Shankae544d162017-12-28 17:06:20 -08007049 mProcStateScreenOffTimeMs[procState].addCountLocked(cpuTimesMs, onBatteryScreenOff);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007050 }
7051
7052 @Override
Bookatzc8c44962017-05-11 12:12:54 -07007053 public Timer getAggregatedPartialWakelockTimer() {
7054 return mAggregatedPartialWakelockTimer;
7055 }
7056
7057 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007058 public ArrayMap<String, ? extends BatteryStats.Uid.Wakelock> getWakelockStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007059 return mWakelockStats.getMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007060 }
7061
7062 @Override
Ahmed ElArabawyddd09692017-10-30 17:58:29 -07007063 public Timer getMulticastWakelockStats() {
7064 return mWifiMulticastTimer;
7065 }
7066
7067 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007068 public ArrayMap<String, ? extends BatteryStats.Timer> getSyncStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007069 return mSyncStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007070 }
7071
7072 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007073 public ArrayMap<String, ? extends BatteryStats.Timer> getJobStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007074 return mJobStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007075 }
7076
7077 @Override
Dianne Hackborn94326cb2017-06-28 16:17:20 -07007078 public ArrayMap<String, SparseIntArray> getJobCompletionStats() {
7079 return mJobCompletions;
7080 }
7081
7082 @Override
Dianne Hackborn61659e52014-07-09 16:13:01 -07007083 public SparseArray<? extends BatteryStats.Uid.Sensor> getSensorStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007084 return mSensorStats;
7085 }
7086
7087 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007088 public ArrayMap<String, ? extends BatteryStats.Uid.Proc> getProcessStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007089 return mProcessStats;
7090 }
7091
7092 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007093 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg> getPackageStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007094 return mPackageStats;
7095 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007096
7097 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007098 public int getUid() {
7099 return mUid;
7100 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007101
7102 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007103 public void noteWifiRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007104 if (!mWifiRunning) {
7105 mWifiRunning = true;
7106 if (mWifiRunningTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007107 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
7108 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007109 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007110 mWifiRunningTimer.startRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007111 }
7112 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007113
Dianne Hackborn617f8772009-03-31 15:04:46 -07007114 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007115 public void noteWifiStoppedLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007116 if (mWifiRunning) {
7117 mWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007118 mWifiRunningTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007119 }
7120 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007121
Dianne Hackborn617f8772009-03-31 15:04:46 -07007122 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007123 public void noteFullWifiLockAcquiredLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07007124 if (!mFullWifiLockOut) {
7125 mFullWifiLockOut = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007126 if (mFullWifiLockTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007127 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
7128 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007129 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007130 mFullWifiLockTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007131 }
7132 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007133
The Android Open Source Project10592532009-03-18 17:39:46 -07007134 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007135 public void noteFullWifiLockReleasedLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07007136 if (mFullWifiLockOut) {
7137 mFullWifiLockOut = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007138 mFullWifiLockTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007139 }
7140 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007141
The Android Open Source Project10592532009-03-18 17:39:46 -07007142 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007143 public void noteWifiScanStartedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007144 if (!mWifiScanStarted) {
7145 mWifiScanStarted = true;
7146 if (mWifiScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007147 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
7148 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase,
7149 mOnBatteryBackgroundTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007150 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007151 mWifiScanTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007152 }
7153 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007154
The Android Open Source Project10592532009-03-18 17:39:46 -07007155 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007156 public void noteWifiScanStoppedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007157 if (mWifiScanStarted) {
7158 mWifiScanStarted = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007159 mWifiScanTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007160 }
7161 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007162
7163 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007164 public void noteWifiBatchedScanStartedLocked(int csph, long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007165 int bin = 0;
Navtej Singh Mann3c0ce5c2015-06-11 16:53:11 -07007166 while (csph > 8 && bin < NUM_WIFI_BATCHED_SCAN_BINS-1) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007167 csph = csph >> 3;
7168 bin++;
7169 }
7170
7171 if (mWifiBatchedScanBinStarted == bin) return;
7172
7173 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
7174 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007175 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007176 }
7177 mWifiBatchedScanBinStarted = bin;
7178 if (mWifiBatchedScanTimer[bin] == null) {
7179 makeWifiBatchedScanBin(bin, null);
7180 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007181 mWifiBatchedScanTimer[bin].startRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007182 }
7183
7184 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007185 public void noteWifiBatchedScanStoppedLocked(long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007186 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
7187 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007188 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007189 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
7190 }
7191 }
7192
7193 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007194 public void noteWifiMulticastEnabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007195 if (!mWifiMulticastEnabled) {
7196 mWifiMulticastEnabled = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007197 if (mWifiMulticastTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007198 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7199 WIFI_MULTICAST_ENABLED, mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007200 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007201 mWifiMulticastTimer.startRunningLocked(elapsedRealtimeMs);
Tej Singh4503e102018-01-04 14:35:01 -08007202 StatsLog.write_non_chained(
Bookatz90867622018-01-31 15:05:57 -08007203 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED, getUid(), null,
7204 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED__STATE__ON);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007205 }
7206 }
7207
7208 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007209 public void noteWifiMulticastDisabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007210 if (mWifiMulticastEnabled) {
7211 mWifiMulticastEnabled = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007212 mWifiMulticastTimer.stopRunningLocked(elapsedRealtimeMs);
Tej Singh4503e102018-01-04 14:35:01 -08007213 StatsLog.write_non_chained(
Bookatz90867622018-01-31 15:05:57 -08007214 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED, getUid(), null,
7215 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED__STATE__OFF);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007216 }
7217 }
7218
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007219 @Override
7220 public ControllerActivityCounter getWifiControllerActivity() {
7221 return mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07007222 }
7223
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007224 @Override
7225 public ControllerActivityCounter getBluetoothControllerActivity() {
7226 return mBluetoothControllerActivity;
7227 }
7228
7229 @Override
7230 public ControllerActivityCounter getModemControllerActivity() {
7231 return mModemControllerActivity;
7232 }
7233
7234 public ControllerActivityCounterImpl getOrCreateWifiControllerActivityLocked() {
7235 if (mWifiControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007236 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007237 NUM_BT_TX_LEVELS);
Adam Lesinski50e47602015-12-04 17:04:54 -08007238 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007239 return mWifiControllerActivity;
7240 }
7241
7242 public ControllerActivityCounterImpl getOrCreateBluetoothControllerActivityLocked() {
7243 if (mBluetoothControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007244 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007245 NUM_BT_TX_LEVELS);
7246 }
7247 return mBluetoothControllerActivity;
7248 }
7249
7250 public ControllerActivityCounterImpl getOrCreateModemControllerActivityLocked() {
7251 if (mModemControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007252 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007253 ModemActivityInfo.TX_POWER_LEVELS);
7254 }
7255 return mModemControllerActivity;
Adam Lesinski50e47602015-12-04 17:04:54 -08007256 }
7257
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007258 public StopwatchTimer createAudioTurnedOnTimerLocked() {
7259 if (mAudioTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007260 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
7261 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007262 }
7263 return mAudioTurnedOnTimer;
7264 }
7265
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007266 public void noteAudioTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007267 createAudioTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007268 StatsLog.write_non_chained(StatsLog.AUDIO_STATE_CHANGED, getUid(), null,
7269 StatsLog.AUDIO_STATE_CHANGED__STATE__ON);
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007270 }
7271
7272 public void noteAudioTurnedOffLocked(long elapsedRealtimeMs) {
7273 if (mAudioTurnedOnTimer != null) {
7274 mAudioTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007275 if (!mAudioTurnedOnTimer.isRunningLocked()) { // only tell statsd if truly stopped
Bookatz90867622018-01-31 15:05:57 -08007276 StatsLog.write_non_chained(StatsLog.AUDIO_STATE_CHANGED, getUid(), null,
7277 StatsLog.AUDIO_STATE_CHANGED__STATE__OFF);
Bookatzc1a050a2017-10-10 15:49:28 -07007278 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007279 }
7280 }
7281
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007282 public void noteResetAudioLocked(long elapsedRealtimeMs) {
7283 if (mAudioTurnedOnTimer != null) {
7284 mAudioTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007285 StatsLog.write_non_chained(StatsLog.AUDIO_STATE_CHANGED, getUid(), null,
7286 StatsLog.AUDIO_STATE_CHANGED__STATE__OFF);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007287 }
7288 }
7289
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007290 public StopwatchTimer createVideoTurnedOnTimerLocked() {
7291 if (mVideoTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007292 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
7293 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007294 }
7295 return mVideoTurnedOnTimer;
7296 }
7297
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007298 public void noteVideoTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007299 createVideoTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007300 StatsLog.write_non_chained(StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED, getUid(), null,
7301 StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED__STATE__ON);
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007302 }
7303
7304 public void noteVideoTurnedOffLocked(long elapsedRealtimeMs) {
7305 if (mVideoTurnedOnTimer != null) {
7306 mVideoTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007307 if (!mVideoTurnedOnTimer.isRunningLocked()) { // only tell statsd if truly stopped
Yangster-mac2f5daec2018-01-16 10:23:15 -08007308 StatsLog.write_non_chained(StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED, getUid(),
Bookatz90867622018-01-31 15:05:57 -08007309 null, StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED__STATE__OFF);
Bookatzc1a050a2017-10-10 15:49:28 -07007310 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007311 }
7312 }
7313
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007314 public void noteResetVideoLocked(long elapsedRealtimeMs) {
7315 if (mVideoTurnedOnTimer != null) {
7316 mVideoTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08007317 StatsLog.write_non_chained(StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED, getUid(), null,
Bookatz90867622018-01-31 15:05:57 -08007318 StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED__STATE__OFF);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007319 }
7320 }
7321
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007322 public StopwatchTimer createFlashlightTurnedOnTimerLocked() {
7323 if (mFlashlightTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007324 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7325 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007326 }
7327 return mFlashlightTurnedOnTimer;
7328 }
7329
7330 public void noteFlashlightTurnedOnLocked(long elapsedRealtimeMs) {
7331 createFlashlightTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007332 StatsLog.write_non_chained(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), null,
7333 StatsLog.FLASHLIGHT_STATE_CHANGED__STATE__ON);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007334 }
7335
7336 public void noteFlashlightTurnedOffLocked(long elapsedRealtimeMs) {
7337 if (mFlashlightTurnedOnTimer != null) {
7338 mFlashlightTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007339 if (!mFlashlightTurnedOnTimer.isRunningLocked()) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08007340 StatsLog.write_non_chained(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), null,
Bookatz90867622018-01-31 15:05:57 -08007341 StatsLog.FLASHLIGHT_STATE_CHANGED__STATE__OFF);
Bookatzc1a050a2017-10-10 15:49:28 -07007342 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007343 }
7344 }
7345
7346 public void noteResetFlashlightLocked(long elapsedRealtimeMs) {
7347 if (mFlashlightTurnedOnTimer != null) {
7348 mFlashlightTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007349 StatsLog.write_non_chained(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), null,
7350 StatsLog.FLASHLIGHT_STATE_CHANGED__STATE__OFF);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007351 }
7352 }
7353
7354 public StopwatchTimer createCameraTurnedOnTimerLocked() {
7355 if (mCameraTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007356 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
7357 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007358 }
7359 return mCameraTurnedOnTimer;
7360 }
7361
7362 public void noteCameraTurnedOnLocked(long elapsedRealtimeMs) {
7363 createCameraTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007364 StatsLog.write_non_chained(StatsLog.CAMERA_STATE_CHANGED, getUid(), null,
7365 StatsLog.CAMERA_STATE_CHANGED__STATE__ON);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007366 }
7367
7368 public void noteCameraTurnedOffLocked(long elapsedRealtimeMs) {
7369 if (mCameraTurnedOnTimer != null) {
7370 mCameraTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007371 if (!mCameraTurnedOnTimer.isRunningLocked()) { // only tell statsd if truly stopped
Bookatz90867622018-01-31 15:05:57 -08007372 StatsLog.write_non_chained(StatsLog.CAMERA_STATE_CHANGED, getUid(), null,
7373 StatsLog.CAMERA_STATE_CHANGED__STATE__OFF);
Bookatzc1a050a2017-10-10 15:49:28 -07007374 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007375 }
7376 }
7377
7378 public void noteResetCameraLocked(long elapsedRealtimeMs) {
7379 if (mCameraTurnedOnTimer != null) {
7380 mCameraTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007381 StatsLog.write_non_chained(StatsLog.CAMERA_STATE_CHANGED, getUid(), null,
7382 StatsLog.CAMERA_STATE_CHANGED__STATE__OFF);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007383 }
7384 }
7385
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007386 public StopwatchTimer createForegroundActivityTimerLocked() {
7387 if (mForegroundActivityTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007388 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7389 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007390 }
7391 return mForegroundActivityTimer;
7392 }
7393
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007394 public StopwatchTimer createForegroundServiceTimerLocked() {
7395 if (mForegroundServiceTimer == null) {
7396 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7397 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase);
7398 }
7399 return mForegroundServiceTimer;
7400 }
7401
Bookatzc8c44962017-05-11 12:12:54 -07007402 public DualTimer createAggregatedPartialWakelockTimerLocked() {
7403 if (mAggregatedPartialWakelockTimer == null) {
7404 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
7405 AGGREGATED_WAKE_TYPE_PARTIAL, null,
7406 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase);
7407 }
7408 return mAggregatedPartialWakelockTimer;
7409 }
7410
Bookatz867c0d72017-03-07 18:23:42 -08007411 public DualTimer createBluetoothScanTimerLocked() {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007412 if (mBluetoothScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007413 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
7414 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
7415 mOnBatteryBackgroundTimeBase);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007416 }
7417 return mBluetoothScanTimer;
7418 }
7419
Bookatzb1f04f32017-05-19 13:57:32 -07007420 public DualTimer createBluetoothUnoptimizedScanTimerLocked() {
7421 if (mBluetoothUnoptimizedScanTimer == null) {
7422 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
7423 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
7424 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
7425 }
7426 return mBluetoothUnoptimizedScanTimer;
7427 }
7428
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00007429 public void noteBluetoothScanStartedLocked(long elapsedRealtimeMs,
7430 boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007431 createBluetoothScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatzb1f04f32017-05-19 13:57:32 -07007432 if (isUnoptimized) {
7433 createBluetoothUnoptimizedScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
7434 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007435 }
7436
Bookatz94c5a312017-07-11 16:49:17 -07007437 public void noteBluetoothScanStoppedLocked(long elapsedRealtimeMs, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007438 if (mBluetoothScanTimer != null) {
7439 mBluetoothScanTimer.stopRunningLocked(elapsedRealtimeMs);
7440 }
Bookatz94c5a312017-07-11 16:49:17 -07007441 if (isUnoptimized && mBluetoothUnoptimizedScanTimer != null) {
Bookatzb1f04f32017-05-19 13:57:32 -07007442 mBluetoothUnoptimizedScanTimer.stopRunningLocked(elapsedRealtimeMs);
7443 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007444 }
7445
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00007446 public void addBluetoothWorkChain(WorkChain workChain, boolean isUnoptimized) {
7447 if (mAllBluetoothChains == null) {
7448 mAllBluetoothChains = new ArrayList<WorkChain>(4);
7449 }
7450
7451 if (isUnoptimized && mUnoptimizedBluetoothChains == null) {
7452 mUnoptimizedBluetoothChains = new ArrayList<WorkChain>(4);
7453 }
7454
7455 mAllBluetoothChains.add(workChain);
7456 if (isUnoptimized) {
7457 mUnoptimizedBluetoothChains.add(workChain);
7458 }
7459 }
7460
7461 public void removeBluetoothWorkChain(WorkChain workChain, boolean isUnoptimized) {
7462 if (mAllBluetoothChains != null) {
7463 mAllBluetoothChains.remove(workChain);
7464 }
7465
7466 if (isUnoptimized && mUnoptimizedBluetoothChains != null) {
7467 mUnoptimizedBluetoothChains.remove(workChain);
7468 }
7469 }
7470
7471 public List<WorkChain> getAllBluetoothWorkChains() {
7472 return mAllBluetoothChains;
7473 }
7474
7475 public List<WorkChain> getUnoptimizedBluetoothWorkChains() {
7476 return mUnoptimizedBluetoothChains;
7477 }
7478
7479
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007480 public void noteResetBluetoothScanLocked(long elapsedRealtimeMs) {
7481 if (mBluetoothScanTimer != null) {
7482 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
7483 }
Bookatzb1f04f32017-05-19 13:57:32 -07007484 if (mBluetoothUnoptimizedScanTimer != null) {
7485 mBluetoothUnoptimizedScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
7486 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007487 }
7488
Bookatz956f36bf2017-04-28 09:48:17 -07007489 public Counter createBluetoothScanResultCounterLocked() {
7490 if (mBluetoothScanResultCounter == null) {
7491 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase);
7492 }
7493 return mBluetoothScanResultCounter;
7494 }
7495
Bookatzb1f04f32017-05-19 13:57:32 -07007496 public Counter createBluetoothScanResultBgCounterLocked() {
7497 if (mBluetoothScanResultBgCounter == null) {
7498 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase);
7499 }
7500 return mBluetoothScanResultBgCounter;
7501 }
7502
Bookatz4ebc0642017-05-11 12:21:19 -07007503 public void noteBluetoothScanResultsLocked(int numNewResults) {
7504 createBluetoothScanResultCounterLocked().addAtomic(numNewResults);
Bookatzb1f04f32017-05-19 13:57:32 -07007505 // Uses background timebase, so the count will only be incremented if uid in background.
7506 createBluetoothScanResultBgCounterLocked().addAtomic(numNewResults);
Bookatz956f36bf2017-04-28 09:48:17 -07007507 }
7508
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007509 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007510 public void noteActivityResumedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007511 // We always start, since we want multiple foreground PIDs to nest
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007512 createForegroundActivityTimerLocked().startRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007513 }
7514
7515 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007516 public void noteActivityPausedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007517 if (mForegroundActivityTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007518 mForegroundActivityTimer.stopRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007519 }
7520 }
7521
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007522 public void noteForegroundServiceResumedLocked(long elapsedRealtimeMs) {
7523 createForegroundServiceTimerLocked().startRunningLocked(elapsedRealtimeMs);
7524 }
7525
7526 public void noteForegroundServicePausedLocked(long elapsedRealtimeMs) {
7527 if (mForegroundServiceTimer != null) {
7528 mForegroundServiceTimer.stopRunningLocked(elapsedRealtimeMs);
7529 }
7530 }
7531
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007532 public BatchTimer createVibratorOnTimerLocked() {
7533 if (mVibratorOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007534 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
7535 mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007536 }
7537 return mVibratorOnTimer;
7538 }
7539
7540 public void noteVibratorOnLocked(long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08007541 createVibratorOnTimerLocked().addDuration(mBsi, durationMillis);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007542 }
7543
7544 public void noteVibratorOffLocked() {
7545 if (mVibratorOnTimer != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007546 mVibratorOnTimer.abortLastDuration(mBsi);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007547 }
7548 }
7549
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007550 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007551 public long getWifiRunningTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007552 if (mWifiRunningTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007553 return 0;
7554 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007555 return mWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007556 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07007557
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007558 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007559 public long getFullWifiLockTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007560 if (mFullWifiLockTimer == null) {
7561 return 0;
7562 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007563 return mFullWifiLockTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07007564 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007565
7566 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007567 public long getWifiScanTime(long elapsedRealtimeUs, int which) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007568 if (mWifiScanTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007569 return 0;
7570 }
Bookatzaa4594a2017-03-24 12:39:56 -07007571 return mWifiScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07007572 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007573
7574 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07007575 public int getWifiScanCount(int which) {
7576 if (mWifiScanTimer == null) {
7577 return 0;
7578 }
Bookatzaa4594a2017-03-24 12:39:56 -07007579 return mWifiScanTimer.getCountLocked(which);
Bookatz867c0d72017-03-07 18:23:42 -08007580 }
7581
7582 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07007583 public Timer getWifiScanTimer() {
7584 return mWifiScanTimer;
7585 }
7586
7587 @Override
Bookatz867c0d72017-03-07 18:23:42 -08007588 public int getWifiScanBackgroundCount(int which) {
Bookatzaa4594a2017-03-24 12:39:56 -07007589 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007590 return 0;
7591 }
7592 return mWifiScanTimer.getSubTimer().getCountLocked(which);
7593 }
7594
7595 @Override
7596 public long getWifiScanActualTime(final long elapsedRealtimeUs) {
7597 if (mWifiScanTimer == null) {
7598 return 0;
7599 }
7600 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
Bookatzaa4594a2017-03-24 12:39:56 -07007601 return mWifiScanTimer.getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Bookatz867c0d72017-03-07 18:23:42 -08007602 }
7603
7604 @Override
7605 public long getWifiScanBackgroundTime(final long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07007606 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007607 return 0;
7608 }
7609 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
7610 return mWifiScanTimer.getSubTimer().getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Dianne Hackborn62793e42015-03-09 11:15:41 -07007611 }
7612
7613 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07007614 public Timer getWifiScanBackgroundTimer() {
7615 if (mWifiScanTimer == null) {
7616 return null;
7617 }
7618 return mWifiScanTimer.getSubTimer();
7619 }
7620
7621 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007622 public long getWifiBatchedScanTime(int csphBin, long elapsedRealtimeUs, int which) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007623 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
7624 if (mWifiBatchedScanTimer[csphBin] == null) {
7625 return 0;
7626 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007627 return mWifiBatchedScanTimer[csphBin].getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007628 }
7629
7630 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07007631 public int getWifiBatchedScanCount(int csphBin, int which) {
7632 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
7633 if (mWifiBatchedScanTimer[csphBin] == null) {
7634 return 0;
7635 }
7636 return mWifiBatchedScanTimer[csphBin].getCountLocked(which);
7637 }
7638
7639 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007640 public long getWifiMulticastTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007641 if (mWifiMulticastTimer == null) {
7642 return 0;
7643 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007644 return mWifiMulticastTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007645 }
7646
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007647 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007648 public Timer getAudioTurnedOnTimer() {
7649 return mAudioTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007650 }
7651
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007652 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007653 public Timer getVideoTurnedOnTimer() {
7654 return mVideoTurnedOnTimer;
7655 }
7656
7657 @Override
7658 public Timer getFlashlightTurnedOnTimer() {
7659 return mFlashlightTurnedOnTimer;
7660 }
7661
7662 @Override
7663 public Timer getCameraTurnedOnTimer() {
7664 return mCameraTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007665 }
7666
Dianne Hackborn617f8772009-03-31 15:04:46 -07007667 @Override
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007668 public Timer getForegroundActivityTimer() {
7669 return mForegroundActivityTimer;
7670 }
7671
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007672 @Override
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007673 public Timer getForegroundServiceTimer() {
7674 return mForegroundServiceTimer;
7675 }
7676
7677 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007678 public Timer getBluetoothScanTimer() {
Bookatzaa4594a2017-03-24 12:39:56 -07007679 return mBluetoothScanTimer;
Bookatz867c0d72017-03-07 18:23:42 -08007680 }
7681
7682 @Override
7683 public Timer getBluetoothScanBackgroundTimer() {
7684 if (mBluetoothScanTimer == null) {
7685 return null;
7686 }
7687 return mBluetoothScanTimer.getSubTimer();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007688 }
7689
Bookatz956f36bf2017-04-28 09:48:17 -07007690 @Override
Bookatzb1f04f32017-05-19 13:57:32 -07007691 public Timer getBluetoothUnoptimizedScanTimer() {
7692 return mBluetoothUnoptimizedScanTimer;
7693 }
7694
7695 @Override
7696 public Timer getBluetoothUnoptimizedScanBackgroundTimer() {
7697 if (mBluetoothUnoptimizedScanTimer == null) {
7698 return null;
7699 }
7700 return mBluetoothUnoptimizedScanTimer.getSubTimer();
7701 }
7702
7703 @Override
Bookatz956f36bf2017-04-28 09:48:17 -07007704 public Counter getBluetoothScanResultCounter() {
7705 return mBluetoothScanResultCounter;
7706 }
7707
Bookatzb1f04f32017-05-19 13:57:32 -07007708 @Override
7709 public Counter getBluetoothScanResultBgCounter() {
7710 return mBluetoothScanResultBgCounter;
7711 }
7712
Dianne Hackborn61659e52014-07-09 16:13:01 -07007713 void makeProcessState(int i, Parcel in) {
7714 if (i < 0 || i >= NUM_PROCESS_STATE) return;
7715
7716 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007717 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
7718 mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007719 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08007720 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
7721 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007722 }
7723 }
7724
7725 @Override
7726 public long getProcessStateTime(int state, long elapsedRealtimeUs, int which) {
7727 if (state < 0 || state >= NUM_PROCESS_STATE) return 0;
7728 if (mProcessStateTimer[state] == null) {
7729 return 0;
7730 }
7731 return mProcessStateTimer[state].getTotalTimeLocked(elapsedRealtimeUs, which);
7732 }
7733
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007734 @Override
Joe Onorato713fec82016-03-04 10:34:02 -08007735 public Timer getProcessStateTimer(int state) {
7736 if (state < 0 || state >= NUM_PROCESS_STATE) return null;
7737 return mProcessStateTimer[state];
7738 }
7739
7740 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007741 public Timer getVibratorOnTimer() {
7742 return mVibratorOnTimer;
7743 }
7744
7745 @Override
Dianne Hackborn617f8772009-03-31 15:04:46 -07007746 public void noteUserActivityLocked(int type) {
7747 if (mUserActivityCounters == null) {
7748 initUserActivityLocked();
7749 }
Jeff Browndf693de2012-07-27 12:03:38 -07007750 if (type >= 0 && type < NUM_USER_ACTIVITY_TYPES) {
7751 mUserActivityCounters[type].stepAtomic();
7752 } else {
7753 Slog.w(TAG, "Unknown user activity type " + type + " was specified.",
7754 new Throwable());
7755 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07007756 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007757
Dianne Hackborn617f8772009-03-31 15:04:46 -07007758 @Override
7759 public boolean hasUserActivity() {
7760 return mUserActivityCounters != null;
7761 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007762
Dianne Hackborn617f8772009-03-31 15:04:46 -07007763 @Override
7764 public int getUserActivityCount(int type, int which) {
7765 if (mUserActivityCounters == null) {
7766 return 0;
7767 }
Evan Millarc64edde2009-04-18 12:26:32 -07007768 return mUserActivityCounters[type].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007769 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007770
Robert Greenwalta029ea12013-09-25 16:38:12 -07007771 void makeWifiBatchedScanBin(int i, Parcel in) {
7772 if (i < 0 || i >= NUM_WIFI_BATCHED_SCAN_BINS) return;
7773
Joe Onoratoabded112016-02-08 16:49:39 -08007774 ArrayList<StopwatchTimer> collected = mBsi.mWifiBatchedScanTimers.get(i);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007775 if (collected == null) {
7776 collected = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08007777 mBsi.mWifiBatchedScanTimers.put(i, collected);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007778 }
7779 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007780 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
7781 collected, mBsi.mOnBatteryTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007782 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08007783 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
7784 collected, mBsi.mOnBatteryTimeBase, in);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007785 }
7786 }
7787
7788
Dianne Hackborn617f8772009-03-31 15:04:46 -07007789 void initUserActivityLocked() {
7790 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
7791 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007792 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007793 }
7794 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007795
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007796 void noteNetworkActivityLocked(int type, long deltaBytes, long deltaPackets) {
7797 if (mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007798 initNetworkActivityLocked();
7799 }
7800 if (type >= 0 && type < NUM_NETWORK_ACTIVITY_TYPES) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007801 mNetworkByteActivityCounters[type].addCountLocked(deltaBytes);
7802 mNetworkPacketActivityCounters[type].addCountLocked(deltaPackets);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007803 } else {
7804 Slog.w(TAG, "Unknown network activity type " + type + " was specified.",
7805 new Throwable());
7806 }
7807 }
7808
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007809 void noteMobileRadioActiveTimeLocked(long batteryUptime) {
7810 if (mNetworkByteActivityCounters == null) {
7811 initNetworkActivityLocked();
7812 }
7813 mMobileRadioActiveTime.addCountLocked(batteryUptime);
7814 mMobileRadioActiveCount.addCountLocked(1);
7815 }
7816
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007817 @Override
7818 public boolean hasNetworkActivity() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007819 return mNetworkByteActivityCounters != null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007820 }
7821
7822 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007823 public long getNetworkActivityBytes(int type, int which) {
7824 if (mNetworkByteActivityCounters != null && type >= 0
7825 && type < mNetworkByteActivityCounters.length) {
7826 return mNetworkByteActivityCounters[type].getCountLocked(which);
7827 } else {
7828 return 0;
7829 }
7830 }
7831
7832 @Override
7833 public long getNetworkActivityPackets(int type, int which) {
7834 if (mNetworkPacketActivityCounters != null && type >= 0
7835 && type < mNetworkPacketActivityCounters.length) {
7836 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007837 } else {
7838 return 0;
7839 }
7840 }
7841
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007842 @Override
7843 public long getMobileRadioActiveTime(int which) {
7844 return mMobileRadioActiveTime != null
7845 ? mMobileRadioActiveTime.getCountLocked(which) : 0;
7846 }
7847
7848 @Override
7849 public int getMobileRadioActiveCount(int which) {
7850 return mMobileRadioActiveCount != null
7851 ? (int)mMobileRadioActiveCount.getCountLocked(which) : 0;
7852 }
7853
Adam Lesinskie08af192015-03-25 16:42:59 -07007854 @Override
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007855 public long getUserCpuTimeUs(int which) {
7856 return mUserCpuTime.getCountLocked(which);
7857 }
7858
7859 @Override
7860 public long getSystemCpuTimeUs(int which) {
7861 return mSystemCpuTime.getCountLocked(which);
7862 }
7863
7864 @Override
Adam Lesinski6832f392015-09-05 18:05:40 -07007865 public long getTimeAtCpuSpeed(int cluster, int step, int which) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07007866 if (mCpuClusterSpeedTimesUs != null) {
7867 if (cluster >= 0 && cluster < mCpuClusterSpeedTimesUs.length) {
7868 final LongSamplingCounter[] cpuSpeedTimesUs = mCpuClusterSpeedTimesUs[cluster];
7869 if (cpuSpeedTimesUs != null) {
7870 if (step >= 0 && step < cpuSpeedTimesUs.length) {
7871 final LongSamplingCounter c = cpuSpeedTimesUs[step];
Adam Lesinski6832f392015-09-05 18:05:40 -07007872 if (c != null) {
7873 return c.getCountLocked(which);
7874 }
7875 }
7876 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007877 }
7878 }
7879 return 0;
7880 }
7881
Adam Lesinski5f056f62016-07-14 16:56:08 -07007882 public void noteMobileRadioApWakeupLocked() {
7883 if (mMobileRadioApWakeupCount == null) {
7884 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7885 }
7886 mMobileRadioApWakeupCount.addCountLocked(1);
7887 }
7888
7889 @Override
7890 public long getMobileRadioApWakeupCount(int which) {
7891 if (mMobileRadioApWakeupCount != null) {
7892 return mMobileRadioApWakeupCount.getCountLocked(which);
7893 }
7894 return 0;
7895 }
7896
7897 public void noteWifiRadioApWakeupLocked() {
7898 if (mWifiRadioApWakeupCount == null) {
7899 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7900 }
7901 mWifiRadioApWakeupCount.addCountLocked(1);
7902 }
7903
7904 @Override
7905 public long getWifiRadioApWakeupCount(int which) {
7906 if (mWifiRadioApWakeupCount != null) {
7907 return mWifiRadioApWakeupCount.getCountLocked(which);
7908 }
7909 return 0;
7910 }
7911
Amith Yamasani977e11f2018-02-16 11:29:54 -08007912 @Override
7913 public void getDeferredJobsCheckinLineLocked(StringBuilder sb, int which) {
7914 sb.setLength(0);
7915 final int deferredEventCount = mJobsDeferredEventCount.getCountLocked(which);
7916 if (deferredEventCount == 0) {
7917 return;
7918 }
7919 final int deferredCount = mJobsDeferredCount.getCountLocked(which);
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007920 final long totalLatency = mJobsFreshnessTimeMs.getCountLocked(which);
Amith Yamasani977e11f2018-02-16 11:29:54 -08007921 sb.append(deferredEventCount); sb.append(',');
7922 sb.append(deferredCount); sb.append(',');
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007923 sb.append(totalLatency);
Amith Yamasani977e11f2018-02-16 11:29:54 -08007924 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
7925 if (mJobsFreshnessBuckets[i] == null) {
7926 sb.append(",0");
7927 } else {
7928 sb.append(",");
7929 sb.append(mJobsFreshnessBuckets[i].getCountLocked(which));
7930 }
7931 }
7932 }
7933
7934 @Override
7935 public void getDeferredJobsLineLocked(StringBuilder sb, int which) {
7936 sb.setLength(0);
7937 final int deferredEventCount = mJobsDeferredEventCount.getCountLocked(which);
7938 if (deferredEventCount == 0) {
7939 return;
7940 }
7941 final int deferredCount = mJobsDeferredCount.getCountLocked(which);
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007942 final long totalLatency = mJobsFreshnessTimeMs.getCountLocked(which);
Amith Yamasani977e11f2018-02-16 11:29:54 -08007943 sb.append("times="); sb.append(deferredEventCount); sb.append(", ");
7944 sb.append("count="); sb.append(deferredCount); sb.append(", ");
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007945 sb.append("totalLatencyMs="); sb.append(totalLatency); sb.append(", ");
Amith Yamasani977e11f2018-02-16 11:29:54 -08007946 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
7947 sb.append("<"); sb.append(JOB_FRESHNESS_BUCKETS[i]); sb.append("ms=");
7948 if (mJobsFreshnessBuckets[i] == null) {
7949 sb.append("0");
7950 } else {
7951 sb.append(mJobsFreshnessBuckets[i].getCountLocked(which));
7952 }
7953 sb.append(" ");
7954 }
7955 }
7956
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007957 void initNetworkActivityLocked() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007958 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
7959 mNetworkPacketActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007960 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007961 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7962 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007963 }
Joe Onoratoabded112016-02-08 16:49:39 -08007964 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7965 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007966 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07007967
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007968 /**
7969 * Clear all stats for this uid. Returns true if the uid is completely
7970 * inactive so can be dropped.
7971 */
Adam Lesinski5f212c82017-03-13 12:25:13 -07007972 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
Bookatz993a0be2017-07-21 09:03:23 -07007973 public boolean reset(long uptime, long realtime) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007974 boolean active = false;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007975
Bookatz993a0be2017-07-21 09:03:23 -07007976 mOnBatteryBackgroundTimeBase.init(uptime, realtime);
7977 mOnBatteryScreenOffBackgroundTimeBase.init(uptime, realtime);
7978
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007979 if (mWifiRunningTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007980 active |= !mWifiRunningTimer.reset(false);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007981 active |= mWifiRunning;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007982 }
7983 if (mFullWifiLockTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007984 active |= !mFullWifiLockTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007985 active |= mFullWifiLockOut;
7986 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07007987 if (mWifiScanTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007988 active |= !mWifiScanTimer.reset(false);
Nick Pelly6ccaa542012-06-15 15:22:47 -07007989 active |= mWifiScanStarted;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007990 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07007991 if (mWifiBatchedScanTimer != null) {
7992 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
7993 if (mWifiBatchedScanTimer[i] != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007994 active |= !mWifiBatchedScanTimer[i].reset(false);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007995 }
7996 }
7997 active |= (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED);
7998 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007999 if (mWifiMulticastTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008000 active |= !mWifiMulticastTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008001 active |= mWifiMulticastEnabled;
8002 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008003
8004 active |= !resetTimerIfNotNull(mAudioTurnedOnTimer, false);
8005 active |= !resetTimerIfNotNull(mVideoTurnedOnTimer, false);
8006 active |= !resetTimerIfNotNull(mFlashlightTurnedOnTimer, false);
8007 active |= !resetTimerIfNotNull(mCameraTurnedOnTimer, false);
8008 active |= !resetTimerIfNotNull(mForegroundActivityTimer, false);
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008009 active |= !resetTimerIfNotNull(mForegroundServiceTimer, false);
Bookatzc8c44962017-05-11 12:12:54 -07008010 active |= !resetTimerIfNotNull(mAggregatedPartialWakelockTimer, false);
Adam Lesinski5f056f62016-07-14 16:56:08 -07008011 active |= !resetTimerIfNotNull(mBluetoothScanTimer, false);
Bookatzb1f04f32017-05-19 13:57:32 -07008012 active |= !resetTimerIfNotNull(mBluetoothUnoptimizedScanTimer, false);
Bookatz956f36bf2017-04-28 09:48:17 -07008013 if (mBluetoothScanResultCounter != null) {
8014 mBluetoothScanResultCounter.reset(false);
8015 }
Bookatzb1f04f32017-05-19 13:57:32 -07008016 if (mBluetoothScanResultBgCounter != null) {
8017 mBluetoothScanResultBgCounter.reset(false);
8018 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008019
Dianne Hackborn61659e52014-07-09 16:13:01 -07008020 if (mProcessStateTimer != null) {
8021 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8022 if (mProcessStateTimer[i] != null) {
8023 active |= !mProcessStateTimer[i].reset(false);
8024 }
8025 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08008026 active |= (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT);
Dianne Hackborn61659e52014-07-09 16:13:01 -07008027 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008028 if (mVibratorOnTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008029 if (mVibratorOnTimer.reset(false)) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008030 mVibratorOnTimer.detach();
8031 mVibratorOnTimer = null;
8032 } else {
8033 active = true;
8034 }
8035 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008036
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008037 if (mUserActivityCounters != null) {
8038 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
8039 mUserActivityCounters[i].reset(false);
8040 }
8041 }
8042
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008043 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008044 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008045 mNetworkByteActivityCounters[i].reset(false);
8046 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008047 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08008048 mMobileRadioActiveTime.reset(false);
8049 mMobileRadioActiveCount.reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008050 }
8051
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008052 if (mWifiControllerActivity != null) {
8053 mWifiControllerActivity.reset(false);
8054 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008055
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07008056 if (mBluetoothControllerActivity != null) {
8057 mBluetoothControllerActivity.reset(false);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008058 }
8059
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07008060 if (mModemControllerActivity != null) {
8061 mModemControllerActivity.reset(false);
Adam Lesinskie08af192015-03-25 16:42:59 -07008062 }
8063
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008064 mUserCpuTime.reset(false);
8065 mSystemCpuTime.reset(false);
Adam Lesinski6832f392015-09-05 18:05:40 -07008066
Sudheer Shankaaf857412017-07-21 00:14:24 -07008067 if (mCpuClusterSpeedTimesUs != null) {
8068 for (LongSamplingCounter[] speeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008069 if (speeds != null) {
8070 for (LongSamplingCounter speed : speeds) {
8071 if (speed != null) {
8072 speed.reset(false);
8073 }
8074 }
8075 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008076 }
8077 }
8078
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008079 if (mCpuFreqTimeMs != null) {
8080 mCpuFreqTimeMs.reset(false);
8081 }
8082 if (mScreenOffCpuFreqTimeMs != null) {
8083 mScreenOffCpuFreqTimeMs.reset(false);
8084 }
8085
Mike Ma3d422c32017-10-25 11:08:57 -07008086 mCpuActiveTimeMs.reset(false);
8087 mCpuClusterTimesMs.reset(false);
8088
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008089 if (mProcStateTimeMs != null) {
8090 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8091 if (counters != null) {
8092 counters.reset(false);
8093 }
8094 }
8095 }
8096 if (mProcStateScreenOffTimeMs != null) {
8097 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8098 if (counters != null) {
8099 counters.reset(false);
8100 }
8101 }
8102 }
8103
Adam Lesinski5f056f62016-07-14 16:56:08 -07008104 resetLongCounterIfNotNull(mMobileRadioApWakeupCount, false);
8105 resetLongCounterIfNotNull(mWifiRadioApWakeupCount, false);
8106
Dianne Hackbornd953c532014-08-16 18:17:38 -07008107 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
8108 for (int iw=wakeStats.size()-1; iw>=0; iw--) {
8109 Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07008110 if (wl.reset()) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008111 wakeStats.removeAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07008112 } else {
8113 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008114 }
8115 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07008116 mWakelockStats.cleanup();
Bookatz2bffb5b2017-04-13 11:59:33 -07008117 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008118 for (int is=syncStats.size()-1; is>=0; is--) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008119 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008120 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008121 syncStats.removeAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008122 timer.detach();
8123 } else {
8124 active = true;
8125 }
8126 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07008127 mSyncStats.cleanup();
Bookatzaa4594a2017-03-24 12:39:56 -07008128 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008129 for (int ij=jobStats.size()-1; ij>=0; ij--) {
Bookatzaa4594a2017-03-24 12:39:56 -07008130 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008131 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008132 jobStats.removeAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008133 timer.detach();
8134 } else {
8135 active = true;
8136 }
8137 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07008138 mJobStats.cleanup();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008139 mJobCompletions.clear();
Amith Yamasani977e11f2018-02-16 11:29:54 -08008140
8141 mJobsDeferredEventCount.reset(false);
8142 mJobsDeferredCount.reset(false);
8143 mJobsFreshnessTimeMs.reset(false);
8144 for (int ij = 0; ij < JOB_FRESHNESS_BUCKETS.length; ij++) {
8145 if (mJobsFreshnessBuckets[ij] != null) {
8146 mJobsFreshnessBuckets[ij].reset(false);
8147 }
8148 }
8149
Dianne Hackborn61659e52014-07-09 16:13:01 -07008150 for (int ise=mSensorStats.size()-1; ise>=0; ise--) {
8151 Sensor s = mSensorStats.valueAt(ise);
8152 if (s.reset()) {
8153 mSensorStats.removeAt(ise);
8154 } else {
8155 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008156 }
8157 }
Amith Yamasani977e11f2018-02-16 11:29:54 -08008158
Dianne Hackborn61659e52014-07-09 16:13:01 -07008159 for (int ip=mProcessStats.size()-1; ip>=0; ip--) {
8160 Proc proc = mProcessStats.valueAt(ip);
Dianne Hackborna8d10942015-11-19 17:55:19 -08008161 proc.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008162 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08008163 mProcessStats.clear();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008164 if (mPids.size() > 0) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008165 for (int i=mPids.size()-1; i>=0; i--) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008166 Pid pid = mPids.valueAt(i);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008167 if (pid.mWakeNesting > 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008168 active = true;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008169 } else {
8170 mPids.removeAt(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008171 }
8172 }
8173 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008174 if (mPackageStats.size() > 0) {
8175 Iterator<Map.Entry<String, Pkg>> it = mPackageStats.entrySet().iterator();
8176 while (it.hasNext()) {
8177 Map.Entry<String, Pkg> pkgEntry = it.next();
8178 Pkg p = pkgEntry.getValue();
8179 p.detach();
8180 if (p.mServiceStats.size() > 0) {
8181 Iterator<Map.Entry<String, Pkg.Serv>> it2
8182 = p.mServiceStats.entrySet().iterator();
8183 while (it2.hasNext()) {
8184 Map.Entry<String, Pkg.Serv> servEntry = it2.next();
8185 servEntry.getValue().detach();
8186 }
8187 }
8188 }
8189 mPackageStats.clear();
8190 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008191
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08008192 mLastStepUserTime = mLastStepSystemTime = 0;
8193 mCurStepUserTime = mCurStepSystemTime = 0;
8194
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008195 if (!active) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008196 if (mWifiRunningTimer != null) {
8197 mWifiRunningTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008198 }
8199 if (mFullWifiLockTimer != null) {
8200 mFullWifiLockTimer.detach();
8201 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008202 if (mWifiScanTimer != null) {
8203 mWifiScanTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008204 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008205 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8206 if (mWifiBatchedScanTimer[i] != null) {
8207 mWifiBatchedScanTimer[i].detach();
8208 }
8209 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008210 if (mWifiMulticastTimer != null) {
8211 mWifiMulticastTimer.detach();
8212 }
8213 if (mAudioTurnedOnTimer != null) {
8214 mAudioTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008215 mAudioTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008216 }
8217 if (mVideoTurnedOnTimer != null) {
8218 mVideoTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008219 mVideoTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008220 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008221 if (mFlashlightTurnedOnTimer != null) {
8222 mFlashlightTurnedOnTimer.detach();
8223 mFlashlightTurnedOnTimer = null;
8224 }
8225 if (mCameraTurnedOnTimer != null) {
8226 mCameraTurnedOnTimer.detach();
8227 mCameraTurnedOnTimer = null;
8228 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008229 if (mForegroundActivityTimer != null) {
8230 mForegroundActivityTimer.detach();
8231 mForegroundActivityTimer = null;
8232 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008233 if (mForegroundServiceTimer != null) {
8234 mForegroundServiceTimer.detach();
8235 mForegroundServiceTimer = null;
8236 }
Bookatzc8c44962017-05-11 12:12:54 -07008237 if (mAggregatedPartialWakelockTimer != null) {
8238 mAggregatedPartialWakelockTimer.detach();
8239 mAggregatedPartialWakelockTimer = null;
8240 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008241 if (mBluetoothScanTimer != null) {
8242 mBluetoothScanTimer.detach();
8243 mBluetoothScanTimer = null;
8244 }
Bookatzb1f04f32017-05-19 13:57:32 -07008245 if (mBluetoothUnoptimizedScanTimer != null) {
8246 mBluetoothUnoptimizedScanTimer.detach();
8247 mBluetoothUnoptimizedScanTimer = null;
8248 }
Bookatz956f36bf2017-04-28 09:48:17 -07008249 if (mBluetoothScanResultCounter != null) {
8250 mBluetoothScanResultCounter.detach();
8251 mBluetoothScanResultCounter = null;
8252 }
Bookatzb1f04f32017-05-19 13:57:32 -07008253 if (mBluetoothScanResultBgCounter != null) {
8254 mBluetoothScanResultBgCounter.detach();
8255 mBluetoothScanResultBgCounter = null;
8256 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008257 if (mUserActivityCounters != null) {
8258 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
8259 mUserActivityCounters[i].detach();
8260 }
8261 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008262 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008263 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008264 mNetworkByteActivityCounters[i].detach();
8265 mNetworkPacketActivityCounters[i].detach();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008266 }
8267 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008268
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008269 if (mWifiControllerActivity != null) {
8270 mWifiControllerActivity.detach();
Adam Lesinskie08af192015-03-25 16:42:59 -07008271 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008272
8273 if (mBluetoothControllerActivity != null) {
8274 mBluetoothControllerActivity.detach();
8275 }
8276
8277 if (mModemControllerActivity != null) {
8278 mModemControllerActivity.detach();
8279 }
8280
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008281 mPids.clear();
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008282
8283 mUserCpuTime.detach();
8284 mSystemCpuTime.detach();
Adam Lesinski6832f392015-09-05 18:05:40 -07008285
Sudheer Shankaaf857412017-07-21 00:14:24 -07008286 if (mCpuClusterSpeedTimesUs != null) {
8287 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008288 if (cpuSpeeds != null) {
8289 for (LongSamplingCounter c : cpuSpeeds) {
8290 if (c != null) {
8291 c.detach();
8292 }
8293 }
8294 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008295 }
8296 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008297
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008298 if (mCpuFreqTimeMs != null) {
8299 mCpuFreqTimeMs.detach();
8300 }
8301 if (mScreenOffCpuFreqTimeMs != null) {
8302 mScreenOffCpuFreqTimeMs.detach();
8303 }
Mike Ma3d422c32017-10-25 11:08:57 -07008304 mCpuActiveTimeMs.detach();
8305 mCpuClusterTimesMs.detach();
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008306
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008307 if (mProcStateTimeMs != null) {
8308 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8309 if (counters != null) {
8310 counters.detach();
8311 }
8312 }
8313 }
8314 if (mProcStateScreenOffTimeMs != null) {
8315 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8316 if (counters != null) {
8317 counters.detach();
8318 }
8319 }
8320 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008321 detachLongCounterIfNotNull(mMobileRadioApWakeupCount);
8322 detachLongCounterIfNotNull(mWifiRadioApWakeupCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008323 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008324
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008325 return !active;
8326 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008327
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008328 void writeJobCompletionsToParcelLocked(Parcel out) {
8329 int NJC = mJobCompletions.size();
8330 out.writeInt(NJC);
8331 for (int ijc=0; ijc<NJC; ijc++) {
8332 out.writeString(mJobCompletions.keyAt(ijc));
8333 SparseIntArray types = mJobCompletions.valueAt(ijc);
8334 int NT = types.size();
8335 out.writeInt(NT);
8336 for (int it=0; it<NT; it++) {
8337 out.writeInt(types.keyAt(it));
8338 out.writeInt(types.valueAt(it));
8339 }
8340 }
8341 }
8342
Bookatz867c0d72017-03-07 18:23:42 -08008343 void writeToParcelLocked(Parcel out, long uptimeUs, long elapsedRealtimeUs) {
8344 mOnBatteryBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatzc8c44962017-05-11 12:12:54 -07008345 mOnBatteryScreenOffBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08008346
Dianne Hackbornd953c532014-08-16 18:17:38 -07008347 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
8348 int NW = wakeStats.size();
Dianne Hackborn61659e52014-07-09 16:13:01 -07008349 out.writeInt(NW);
8350 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008351 out.writeString(wakeStats.keyAt(iw));
8352 Uid.Wakelock wakelock = wakeStats.valueAt(iw);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008353 wakelock.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008354 }
8355
Bookatz2bffb5b2017-04-13 11:59:33 -07008356 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008357 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008358 out.writeInt(NS);
8359 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008360 out.writeString(syncStats.keyAt(is));
Bookatz2bffb5b2017-04-13 11:59:33 -07008361 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008362 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
8363 }
8364
Bookatzaa4594a2017-03-24 12:39:56 -07008365 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008366 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008367 out.writeInt(NJ);
8368 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008369 out.writeString(jobStats.keyAt(ij));
Bookatzaa4594a2017-03-24 12:39:56 -07008370 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008371 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
8372 }
8373
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008374 writeJobCompletionsToParcelLocked(out);
8375
Amith Yamasani977e11f2018-02-16 11:29:54 -08008376 mJobsDeferredEventCount.writeToParcel(out);
8377 mJobsDeferredCount.writeToParcel(out);
8378 mJobsFreshnessTimeMs.writeToParcel(out);
8379 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
8380 Counter.writeCounterToParcel(out, mJobsFreshnessBuckets[i]);
8381 }
8382
Dianne Hackborn61659e52014-07-09 16:13:01 -07008383 int NSE = mSensorStats.size();
8384 out.writeInt(NSE);
8385 for (int ise=0; ise<NSE; ise++) {
8386 out.writeInt(mSensorStats.keyAt(ise));
8387 Uid.Sensor sensor = mSensorStats.valueAt(ise);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008388 sensor.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008389 }
8390
Dianne Hackborn61659e52014-07-09 16:13:01 -07008391 int NP = mProcessStats.size();
8392 out.writeInt(NP);
8393 for (int ip=0; ip<NP; ip++) {
8394 out.writeString(mProcessStats.keyAt(ip));
8395 Uid.Proc proc = mProcessStats.valueAt(ip);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008396 proc.writeToParcelLocked(out);
8397 }
8398
8399 out.writeInt(mPackageStats.size());
8400 for (Map.Entry<String, Uid.Pkg> pkgEntry : mPackageStats.entrySet()) {
8401 out.writeString(pkgEntry.getKey());
8402 Uid.Pkg pkg = pkgEntry.getValue();
8403 pkg.writeToParcelLocked(out);
8404 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008405
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008406 if (mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008407 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008408 mWifiRunningTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008409 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008410 out.writeInt(0);
8411 }
8412 if (mFullWifiLockTimer != null) {
8413 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008414 mFullWifiLockTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008415 } else {
8416 out.writeInt(0);
8417 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008418 if (mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008419 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008420 mWifiScanTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008421 } else {
8422 out.writeInt(0);
8423 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008424 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8425 if (mWifiBatchedScanTimer[i] != null) {
8426 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008427 mWifiBatchedScanTimer[i].writeToParcel(out, elapsedRealtimeUs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07008428 } else {
8429 out.writeInt(0);
8430 }
8431 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008432 if (mWifiMulticastTimer != null) {
8433 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008434 mWifiMulticastTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008435 } else {
8436 out.writeInt(0);
8437 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008438
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008439 if (mAudioTurnedOnTimer != null) {
8440 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008441 mAudioTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008442 } else {
8443 out.writeInt(0);
8444 }
8445 if (mVideoTurnedOnTimer != null) {
8446 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008447 mVideoTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008448 } else {
8449 out.writeInt(0);
8450 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008451 if (mFlashlightTurnedOnTimer != null) {
8452 out.writeInt(1);
8453 mFlashlightTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
8454 } else {
8455 out.writeInt(0);
8456 }
8457 if (mCameraTurnedOnTimer != null) {
8458 out.writeInt(1);
8459 mCameraTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
8460 } else {
8461 out.writeInt(0);
8462 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008463 if (mForegroundActivityTimer != null) {
8464 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008465 mForegroundActivityTimer.writeToParcel(out, elapsedRealtimeUs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008466 } else {
8467 out.writeInt(0);
8468 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008469 if (mForegroundServiceTimer != null) {
8470 out.writeInt(1);
8471 mForegroundServiceTimer.writeToParcel(out, elapsedRealtimeUs);
8472 } else {
8473 out.writeInt(0);
8474 }
Bookatzc8c44962017-05-11 12:12:54 -07008475 if (mAggregatedPartialWakelockTimer != null) {
8476 out.writeInt(1);
8477 mAggregatedPartialWakelockTimer.writeToParcel(out, elapsedRealtimeUs);
8478 } else {
8479 out.writeInt(0);
8480 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008481 if (mBluetoothScanTimer != null) {
8482 out.writeInt(1);
8483 mBluetoothScanTimer.writeToParcel(out, elapsedRealtimeUs);
8484 } else {
8485 out.writeInt(0);
8486 }
Bookatzb1f04f32017-05-19 13:57:32 -07008487 if (mBluetoothUnoptimizedScanTimer != null) {
8488 out.writeInt(1);
8489 mBluetoothUnoptimizedScanTimer.writeToParcel(out, elapsedRealtimeUs);
8490 } else {
8491 out.writeInt(0);
8492 }
Bookatz956f36bf2017-04-28 09:48:17 -07008493 if (mBluetoothScanResultCounter != null) {
8494 out.writeInt(1);
8495 mBluetoothScanResultCounter.writeToParcel(out);
8496 } else {
8497 out.writeInt(0);
8498 }
Bookatzb1f04f32017-05-19 13:57:32 -07008499 if (mBluetoothScanResultBgCounter != null) {
8500 out.writeInt(1);
8501 mBluetoothScanResultBgCounter.writeToParcel(out);
8502 } else {
8503 out.writeInt(0);
8504 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07008505 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8506 if (mProcessStateTimer[i] != null) {
8507 out.writeInt(1);
8508 mProcessStateTimer[i].writeToParcel(out, elapsedRealtimeUs);
8509 } else {
8510 out.writeInt(0);
8511 }
8512 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008513 if (mVibratorOnTimer != null) {
8514 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008515 mVibratorOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008516 } else {
8517 out.writeInt(0);
8518 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008519 if (mUserActivityCounters != null) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07008520 out.writeInt(1);
8521 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
8522 mUserActivityCounters[i].writeToParcel(out);
8523 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008524 } else {
8525 out.writeInt(0);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008526 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008527 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008528 out.writeInt(1);
8529 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008530 mNetworkByteActivityCounters[i].writeToParcel(out);
8531 mNetworkPacketActivityCounters[i].writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008532 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08008533 mMobileRadioActiveTime.writeToParcel(out);
8534 mMobileRadioActiveCount.writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008535 } else {
8536 out.writeInt(0);
8537 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008538
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008539 if (mWifiControllerActivity != null) {
8540 out.writeInt(1);
8541 mWifiControllerActivity.writeToParcel(out, 0);
8542 } else {
8543 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07008544 }
8545
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008546 if (mBluetoothControllerActivity != null) {
8547 out.writeInt(1);
8548 mBluetoothControllerActivity.writeToParcel(out, 0);
8549 } else {
8550 out.writeInt(0);
8551 }
8552
8553 if (mModemControllerActivity != null) {
8554 out.writeInt(1);
8555 mModemControllerActivity.writeToParcel(out, 0);
8556 } else {
8557 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07008558 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008559
8560 mUserCpuTime.writeToParcel(out);
8561 mSystemCpuTime.writeToParcel(out);
8562
Sudheer Shankaaf857412017-07-21 00:14:24 -07008563 if (mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008564 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -07008565 out.writeInt(mCpuClusterSpeedTimesUs.length);
8566 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008567 if (cpuSpeeds != null) {
8568 out.writeInt(1);
8569 out.writeInt(cpuSpeeds.length);
8570 for (LongSamplingCounter c : cpuSpeeds) {
8571 if (c != null) {
8572 out.writeInt(1);
8573 c.writeToParcel(out);
8574 } else {
8575 out.writeInt(0);
8576 }
8577 }
8578 } else {
8579 out.writeInt(0);
8580 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008581 }
Adam Lesinski6832f392015-09-05 18:05:40 -07008582 } else {
8583 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008584 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008585
Sudheer Shanka59f5c002017-05-15 10:57:15 -07008586 LongSamplingCounterArray.writeToParcel(out, mCpuFreqTimeMs);
8587 LongSamplingCounterArray.writeToParcel(out, mScreenOffCpuFreqTimeMs);
Mike Ma3d422c32017-10-25 11:08:57 -07008588
8589 mCpuActiveTimeMs.writeToParcel(out);
8590 mCpuClusterTimesMs.writeToParcel(out);
8591
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008592 if (mProcStateTimeMs != null) {
8593 out.writeInt(mProcStateTimeMs.length);
8594 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8595 LongSamplingCounterArray.writeToParcel(out, counters);
8596 }
8597 } else {
8598 out.writeInt(0);
8599 }
8600 if (mProcStateScreenOffTimeMs != null) {
8601 out.writeInt(mProcStateScreenOffTimeMs.length);
8602 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8603 LongSamplingCounterArray.writeToParcel(out, counters);
8604 }
8605 } else {
8606 out.writeInt(0);
8607 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008608
Adam Lesinski5f056f62016-07-14 16:56:08 -07008609 if (mMobileRadioApWakeupCount != null) {
8610 out.writeInt(1);
8611 mMobileRadioApWakeupCount.writeToParcel(out);
8612 } else {
8613 out.writeInt(0);
8614 }
8615
8616 if (mWifiRadioApWakeupCount != null) {
8617 out.writeInt(1);
8618 mWifiRadioApWakeupCount.writeToParcel(out);
8619 } else {
8620 out.writeInt(0);
8621 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008622 }
8623
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008624 void readJobCompletionsFromParcelLocked(Parcel in) {
8625 int numJobCompletions = in.readInt();
8626 mJobCompletions.clear();
8627 for (int j = 0; j < numJobCompletions; j++) {
8628 String jobName = in.readString();
8629 int numTypes = in.readInt();
8630 if (numTypes > 0) {
8631 SparseIntArray types = new SparseIntArray();
8632 for (int k = 0; k < numTypes; k++) {
8633 int type = in.readInt();
8634 int count = in.readInt();
8635 types.put(type, count);
8636 }
8637 mJobCompletions.put(jobName, types);
8638 }
8639 }
8640 }
8641
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008642 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase, Parcel in) {
Bookatz867c0d72017-03-07 18:23:42 -08008643 mOnBatteryBackgroundTimeBase.readFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -07008644 mOnBatteryScreenOffBackgroundTimeBase.readFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -08008645
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008646 int numWakelocks = in.readInt();
8647 mWakelockStats.clear();
8648 for (int j = 0; j < numWakelocks; j++) {
8649 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008650 Uid.Wakelock wakelock = new Wakelock(mBsi, this);
Bookatz5b5ec322017-05-26 09:40:38 -07008651 wakelock.readFromParcelLocked(
8652 timeBase, screenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase, in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07008653 mWakelockStats.add(wakelockName, wakelock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008654 }
8655
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008656 int numSyncs = in.readInt();
8657 mSyncStats.clear();
8658 for (int j = 0; j < numSyncs; j++) {
8659 String syncName = in.readString();
8660 if (in.readInt() != 0) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008661 mSyncStats.add(syncName, new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
8662 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008663 }
8664 }
8665
8666 int numJobs = in.readInt();
8667 mJobStats.clear();
8668 for (int j = 0; j < numJobs; j++) {
8669 String jobName = in.readString();
8670 if (in.readInt() != 0) {
Bookatzaa4594a2017-03-24 12:39:56 -07008671 mJobStats.add(jobName, new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
8672 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008673 }
8674 }
8675
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008676 readJobCompletionsFromParcelLocked(in);
8677
Amith Yamasani977e11f2018-02-16 11:29:54 -08008678 mJobsDeferredEventCount = new Counter(mBsi.mOnBatteryTimeBase, in);
8679 mJobsDeferredCount = new Counter(mBsi.mOnBatteryTimeBase, in);
8680 mJobsFreshnessTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8681 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
8682 mJobsFreshnessBuckets[i] = Counter.readCounterFromParcel(mBsi.mOnBatteryTimeBase,
8683 in);
8684 }
8685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008686 int numSensors = in.readInt();
8687 mSensorStats.clear();
8688 for (int k = 0; k < numSensors; k++) {
8689 int sensorNumber = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008690 Uid.Sensor sensor = new Sensor(mBsi, this, sensorNumber);
Bookatz867c0d72017-03-07 18:23:42 -08008691 sensor.readFromParcelLocked(mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
8692 in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008693 mSensorStats.put(sensorNumber, sensor);
8694 }
8695
8696 int numProcs = in.readInt();
8697 mProcessStats.clear();
8698 for (int k = 0; k < numProcs; k++) {
8699 String processName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008700 Uid.Proc proc = new Proc(mBsi, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008701 proc.readFromParcelLocked(in);
8702 mProcessStats.put(processName, proc);
8703 }
8704
8705 int numPkgs = in.readInt();
8706 mPackageStats.clear();
8707 for (int l = 0; l < numPkgs; l++) {
8708 String packageName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008709 Uid.Pkg pkg = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008710 pkg.readFromParcelLocked(in);
8711 mPackageStats.put(packageName, pkg);
8712 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008713
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008714 mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008715 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008716 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
8717 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008718 } else {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008719 mWifiRunningTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008720 }
8721 mFullWifiLockOut = false;
8722 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008723 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
8724 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008725 } else {
8726 mFullWifiLockTimer = null;
8727 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008728 mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008729 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08008730 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
8731 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
8732 in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008733 } else {
Nick Pelly6ccaa542012-06-15 15:22:47 -07008734 mWifiScanTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008735 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008736 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
8737 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8738 if (in.readInt() != 0) {
8739 makeWifiBatchedScanBin(i, in);
8740 } else {
8741 mWifiBatchedScanTimer[i] = null;
8742 }
8743 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008744 mWifiMulticastEnabled = false;
8745 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008746 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_MULTICAST_ENABLED,
8747 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008748 } else {
8749 mWifiMulticastTimer = null;
8750 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008751 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008752 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
8753 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008754 } else {
8755 mAudioTurnedOnTimer = null;
8756 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008757 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008758 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
8759 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008760 } else {
8761 mVideoTurnedOnTimer = null;
8762 }
8763 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008764 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8765 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008766 } else {
8767 mFlashlightTurnedOnTimer = null;
8768 }
8769 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008770 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
8771 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008772 } else {
8773 mCameraTurnedOnTimer = null;
8774 }
8775 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008776 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8777 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008778 } else {
8779 mForegroundActivityTimer = null;
8780 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008781 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008782 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8783 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase, in);
8784 } else {
8785 mForegroundServiceTimer = null;
8786 }
8787 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -07008788 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
8789 AGGREGATED_WAKE_TYPE_PARTIAL, null,
8790 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase,
8791 in);
8792 } else {
8793 mAggregatedPartialWakelockTimer = null;
8794 }
8795 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08008796 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
8797 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
8798 mOnBatteryBackgroundTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008799 } else {
8800 mBluetoothScanTimer = null;
8801 }
Bookatz956f36bf2017-04-28 09:48:17 -07008802 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -07008803 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
8804 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
8805 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in);
8806 } else {
8807 mBluetoothUnoptimizedScanTimer = null;
8808 }
8809 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -07008810 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase, in);
8811 } else {
8812 mBluetoothScanResultCounter = null;
8813 }
Bookatzb1f04f32017-05-19 13:57:32 -07008814 if (in.readInt() != 0) {
8815 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase, in);
8816 } else {
8817 mBluetoothScanResultBgCounter = null;
8818 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08008819 mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07008820 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8821 if (in.readInt() != 0) {
8822 makeProcessState(i, in);
8823 } else {
8824 mProcessStateTimer[i] = null;
8825 }
8826 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008827 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008828 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
8829 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008830 } else {
8831 mVibratorOnTimer = null;
8832 }
8833 if (in.readInt() != 0) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07008834 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
8835 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08008836 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008837 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008838 } else {
8839 mUserActivityCounters = null;
Dianne Hackborn617f8772009-03-31 15:04:46 -07008840 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008841 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008842 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
8843 mNetworkPacketActivityCounters
8844 = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008845 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008846 mNetworkByteActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08008847 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008848 mNetworkPacketActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08008849 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008850 }
Joe Onoratoabded112016-02-08 16:49:39 -08008851 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8852 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008853 } else {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008854 mNetworkByteActivityCounters = null;
8855 mNetworkPacketActivityCounters = null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008856 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008857
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008858 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008859 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008860 NUM_WIFI_TX_LEVELS, in);
8861 } else {
8862 mWifiControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07008863 }
8864
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008865 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008866 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008867 NUM_BT_TX_LEVELS, in);
8868 } else {
8869 mBluetoothControllerActivity = null;
8870 }
8871
8872 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008873 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008874 ModemActivityInfo.TX_POWER_LEVELS, in);
8875 } else {
8876 mModemControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07008877 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008878
Joe Onoratoabded112016-02-08 16:49:39 -08008879 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8880 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008881
Adam Lesinski6832f392015-09-05 18:05:40 -07008882 if (in.readInt() != 0) {
8883 int numCpuClusters = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008884 if (mBsi.mPowerProfile != null && mBsi.mPowerProfile.getNumCpuClusters() != numCpuClusters) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008885 throw new ParcelFormatException("Incompatible number of cpu clusters");
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008886 }
Adam Lesinski6832f392015-09-05 18:05:40 -07008887
Sudheer Shankaaf857412017-07-21 00:14:24 -07008888 mCpuClusterSpeedTimesUs = new LongSamplingCounter[numCpuClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -07008889 for (int cluster = 0; cluster < numCpuClusters; cluster++) {
8890 if (in.readInt() != 0) {
8891 int numSpeeds = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008892 if (mBsi.mPowerProfile != null &&
8893 mBsi.mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != numSpeeds) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008894 throw new ParcelFormatException("Incompatible number of cpu speeds");
8895 }
8896
8897 final LongSamplingCounter[] cpuSpeeds = new LongSamplingCounter[numSpeeds];
Sudheer Shankaaf857412017-07-21 00:14:24 -07008898 mCpuClusterSpeedTimesUs[cluster] = cpuSpeeds;
Adam Lesinski6832f392015-09-05 18:05:40 -07008899 for (int speed = 0; speed < numSpeeds; speed++) {
8900 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008901 cpuSpeeds[speed] = new LongSamplingCounter(
8902 mBsi.mOnBatteryTimeBase, in);
Adam Lesinski6832f392015-09-05 18:05:40 -07008903 }
8904 }
Adam Lesinskia57a5402015-09-28 10:21:33 -07008905 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008906 mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -07008907 }
8908 }
8909 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008910 mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008911 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008912
Sudheer Shanka59f5c002017-05-15 10:57:15 -07008913 mCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(in, mBsi.mOnBatteryTimeBase);
8914 mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(
8915 in, mBsi.mOnBatteryScreenOffTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008916
Mike Ma3d422c32017-10-25 11:08:57 -07008917 mCpuActiveTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8918 mCpuClusterTimesMs = new LongSamplingCounterArray(mBsi.mOnBatteryTimeBase, in);
8919
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008920 int length = in.readInt();
8921 if (length == NUM_PROCESS_STATE) {
8922 mProcStateTimeMs = new LongSamplingCounterArray[length];
8923 for (int procState = 0; procState < length; ++procState) {
8924 mProcStateTimeMs[procState] = LongSamplingCounterArray.readFromParcel(
8925 in, mBsi.mOnBatteryTimeBase);
8926 }
8927 } else {
8928 mProcStateTimeMs = null;
8929 }
8930 length = in.readInt();
8931 if (length == NUM_PROCESS_STATE) {
8932 mProcStateScreenOffTimeMs = new LongSamplingCounterArray[length];
8933 for (int procState = 0; procState < length; ++procState) {
8934 mProcStateScreenOffTimeMs[procState] = LongSamplingCounterArray.readFromParcel(
8935 in, mBsi.mOnBatteryScreenOffTimeBase);
8936 }
8937 } else {
8938 mProcStateScreenOffTimeMs = null;
8939 }
8940
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008941 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07008942 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8943 } else {
8944 mMobileRadioApWakeupCount = null;
8945 }
8946
8947 if (in.readInt() != 0) {
8948 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8949 } else {
8950 mWifiRadioApWakeupCount = null;
8951 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008952 }
8953
Amith Yamasani977e11f2018-02-16 11:29:54 -08008954 public void noteJobsDeferredLocked(int numDeferred, long sinceLast) {
8955 mJobsDeferredEventCount.addAtomic(1);
8956 mJobsDeferredCount.addAtomic(numDeferred);
8957 if (sinceLast != 0) {
8958 // Add the total time, which can be divided by the event count to get an average
8959 mJobsFreshnessTimeMs.addCountLocked(sinceLast);
8960 // Also keep track of how many times there were in these different buckets.
8961 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
8962 if (sinceLast < JOB_FRESHNESS_BUCKETS[i]) {
8963 if (mJobsFreshnessBuckets[i] == null) {
8964 mJobsFreshnessBuckets[i] = new Counter(
8965 mBsi.mOnBatteryTimeBase);
8966 }
8967 mJobsFreshnessBuckets[i].addAtomic(1);
8968 break;
8969 }
8970 }
8971 }
8972 }
8973
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008974 /**
8975 * The statistics associated with a particular wake lock.
8976 */
Joe Onoratoabded112016-02-08 16:49:39 -08008977 public static class Wakelock extends BatteryStats.Uid.Wakelock {
8978 /**
8979 * BatteryStatsImpl that we are associated with.
8980 */
8981 protected BatteryStatsImpl mBsi;
8982
8983 /**
8984 * BatteryStatsImpl that we are associated with.
8985 */
8986 protected Uid mUid;
8987
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008988 /**
8989 * How long (in ms) this uid has been keeping the device partially awake.
Bookatz5b5ec322017-05-26 09:40:38 -07008990 * 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 -08008991 */
Bookatz5b5ec322017-05-26 09:40:38 -07008992 DualTimer mTimerPartial;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008993
8994 /**
8995 * How long (in ms) this uid has been keeping the device fully awake.
8996 */
Evan Millarc64edde2009-04-18 12:26:32 -07008997 StopwatchTimer mTimerFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008998
8999 /**
9000 * How long (in ms) this uid has had a window keeping the device awake.
9001 */
Evan Millarc64edde2009-04-18 12:26:32 -07009002 StopwatchTimer mTimerWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009003
9004 /**
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07009005 * How long (in ms) this uid has had a draw wake lock.
Adam Lesinski9425fe22015-06-19 12:02:13 -07009006 */
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07009007 StopwatchTimer mTimerDraw;
Adam Lesinski9425fe22015-06-19 12:02:13 -07009008
Joe Onoratoabded112016-02-08 16:49:39 -08009009 public Wakelock(BatteryStatsImpl bsi, Uid uid) {
9010 mBsi = bsi;
9011 mUid = uid;
9012 }
9013
Adam Lesinski9425fe22015-06-19 12:02:13 -07009014 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009015 * Reads a possibly null Timer from a Parcel. The timer is associated with the
9016 * proper timer pool from the given BatteryStatsImpl object.
9017 *
9018 * @param in the Parcel to be read from.
9019 * return a new Timer, or null.
9020 */
Joe Onorato92fd23f2016-07-25 11:18:42 -07009021 private StopwatchTimer readStopwatchTimerFromParcel(int type,
9022 ArrayList<StopwatchTimer> pool, TimeBase timeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009023 if (in.readInt() == 0) {
9024 return null;
9025 }
9026
Joe Onoratoabded112016-02-08 16:49:39 -08009027 return new StopwatchTimer(mBsi.mClocks, mUid, type, pool, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009028 }
9029
Joe Onorato92fd23f2016-07-25 11:18:42 -07009030 /**
9031 * Reads a possibly null Timer from a Parcel. The timer is associated with the
9032 * proper timer pool from the given BatteryStatsImpl object.
9033 *
9034 * @param in the Parcel to be read from.
9035 * return a new Timer, or null.
9036 */
Bookatz5b5ec322017-05-26 09:40:38 -07009037 private DualTimer readDualTimerFromParcel(int type, ArrayList<StopwatchTimer> pool,
9038 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07009039 if (in.readInt() == 0) {
9040 return null;
9041 }
9042
Bookatz5b5ec322017-05-26 09:40:38 -07009043 return new DualTimer(mBsi.mClocks, mUid, type, pool, timeBase, bgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07009044 }
9045
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009046 boolean reset() {
9047 boolean wlactive = false;
9048 if (mTimerFull != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009049 wlactive |= !mTimerFull.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009050 }
9051 if (mTimerPartial != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009052 wlactive |= !mTimerPartial.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009053 }
9054 if (mTimerWindow != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009055 wlactive |= !mTimerWindow.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009056 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07009057 if (mTimerDraw != null) {
9058 wlactive |= !mTimerDraw.reset(false);
Adam Lesinski9425fe22015-06-19 12:02:13 -07009059 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009060 if (!wlactive) {
9061 if (mTimerFull != null) {
9062 mTimerFull.detach();
9063 mTimerFull = null;
9064 }
9065 if (mTimerPartial != null) {
9066 mTimerPartial.detach();
9067 mTimerPartial = null;
9068 }
9069 if (mTimerWindow != null) {
9070 mTimerWindow.detach();
9071 mTimerWindow = null;
9072 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07009073 if (mTimerDraw != null) {
9074 mTimerDraw.detach();
9075 mTimerDraw = null;
Adam Lesinski9425fe22015-06-19 12:02:13 -07009076 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009077 }
9078 return !wlactive;
9079 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009080
Bookatz5b5ec322017-05-26 09:40:38 -07009081 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase,
9082 TimeBase screenOffBgTimeBase, Parcel in) {
9083 mTimerPartial = readDualTimerFromParcel(WAKE_TYPE_PARTIAL,
9084 mBsi.mPartialTimers, screenOffTimeBase, screenOffBgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07009085 mTimerFull = readStopwatchTimerFromParcel(WAKE_TYPE_FULL,
9086 mBsi.mFullTimers, timeBase, in);
9087 mTimerWindow = readStopwatchTimerFromParcel(WAKE_TYPE_WINDOW,
9088 mBsi.mWindowTimers, timeBase, in);
9089 mTimerDraw = readStopwatchTimerFromParcel(WAKE_TYPE_DRAW,
9090 mBsi.mDrawTimers, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009091 }
9092
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009093 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
9094 Timer.writeTimerToParcel(out, mTimerPartial, elapsedRealtimeUs);
9095 Timer.writeTimerToParcel(out, mTimerFull, elapsedRealtimeUs);
9096 Timer.writeTimerToParcel(out, mTimerWindow, elapsedRealtimeUs);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07009097 Timer.writeTimerToParcel(out, mTimerDraw, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009098 }
9099
9100 @Override
9101 public Timer getWakeTime(int type) {
9102 switch (type) {
9103 case WAKE_TYPE_FULL: return mTimerFull;
9104 case WAKE_TYPE_PARTIAL: return mTimerPartial;
9105 case WAKE_TYPE_WINDOW: return mTimerWindow;
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07009106 case WAKE_TYPE_DRAW: return mTimerDraw;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009107 default: throw new IllegalArgumentException("type = " + type);
9108 }
9109 }
9110 }
9111
Joe Onoratoabded112016-02-08 16:49:39 -08009112 public static class Sensor extends BatteryStats.Uid.Sensor {
9113 /**
9114 * BatteryStatsImpl that we are associated with.
9115 */
9116 protected BatteryStatsImpl mBsi;
9117
9118 /**
Bookatz867c0d72017-03-07 18:23:42 -08009119 * Uid that we are associated with.
Joe Onoratoabded112016-02-08 16:49:39 -08009120 */
9121 protected Uid mUid;
9122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009123 final int mHandle;
Bookatz867c0d72017-03-07 18:23:42 -08009124 DualTimer mTimer;
Amith Yamasaniab9ad192016-12-06 12:46:59 -08009125
Joe Onoratoabded112016-02-08 16:49:39 -08009126 public Sensor(BatteryStatsImpl bsi, Uid uid, int handle) {
9127 mBsi = bsi;
9128 mUid = uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009129 mHandle = handle;
9130 }
9131
Bookatz867c0d72017-03-07 18:23:42 -08009132 private DualTimer readTimersFromParcel(
9133 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009134 if (in.readInt() == 0) {
9135 return null;
9136 }
9137
Joe Onoratoabded112016-02-08 16:49:39 -08009138 ArrayList<StopwatchTimer> pool = mBsi.mSensorTimers.get(mHandle);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009139 if (pool == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07009140 pool = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08009141 mBsi.mSensorTimers.put(mHandle, pool);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009142 }
Bookatz867c0d72017-03-07 18:23:42 -08009143 return new DualTimer(mBsi.mClocks, mUid, 0, pool, timeBase, bgTimeBase, in);
Amith Yamasaniab9ad192016-12-06 12:46:59 -08009144 }
9145
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009146 boolean reset() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009147 if (mTimer.reset(true)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009148 mTimer = null;
9149 return true;
9150 }
9151 return false;
9152 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009153
Bookatz867c0d72017-03-07 18:23:42 -08009154 void readFromParcelLocked(TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
9155 mTimer = readTimersFromParcel(timeBase, bgTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009156 }
9157
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009158 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07009159 Timer.writeTimerToParcel(out, mTimer, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009160 }
9161
9162 @Override
9163 public Timer getSensorTime() {
Bookatzaa4594a2017-03-24 12:39:56 -07009164 return mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009165 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009166
9167 @Override
Bookatz867c0d72017-03-07 18:23:42 -08009168 public Timer getSensorBackgroundTime() {
9169 if (mTimer == null) {
9170 return null;
9171 }
9172 return mTimer.getSubTimer();
Amith Yamasaniab9ad192016-12-06 12:46:59 -08009173 }
9174
9175 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009176 public int getHandle() {
9177 return mHandle;
9178 }
9179 }
9180
9181 /**
9182 * The statistics associated with a particular process.
9183 */
Joe Onoratoabded112016-02-08 16:49:39 -08009184 public static class Proc extends BatteryStats.Uid.Proc implements TimeBaseObs {
9185 /**
9186 * BatteryStatsImpl that we are associated with.
9187 */
9188 protected BatteryStatsImpl mBsi;
9189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009190 /**
Dianne Hackborncd0e3352014-08-07 17:08:09 -07009191 * The name of this process.
9192 */
9193 final String mName;
9194
9195 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -08009196 * Remains true until removed from the stats.
9197 */
9198 boolean mActive = true;
9199
9200 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07009201 * Total time (in ms) spent executing in user code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009202 */
9203 long mUserTime;
9204
9205 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07009206 * Total time (in ms) spent executing in kernel code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009207 */
9208 long mSystemTime;
9209
9210 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07009211 * Amount of time (in ms) the process was running in the foreground.
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009212 */
9213 long mForegroundTime;
9214
9215 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009216 * Number of times the process has been started.
9217 */
9218 int mStarts;
9219
9220 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009221 * Number of times the process has crashed.
9222 */
9223 int mNumCrashes;
9224
9225 /**
9226 * Number of times the process has had an ANR.
9227 */
9228 int mNumAnrs;
9229
9230 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009231 * The amount of user time loaded from a previous save.
9232 */
9233 long mLoadedUserTime;
9234
9235 /**
9236 * The amount of system time loaded from a previous save.
9237 */
9238 long mLoadedSystemTime;
9239
9240 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009241 * The amount of foreground time loaded from a previous save.
9242 */
9243 long mLoadedForegroundTime;
9244
9245 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009246 * The number of times the process has started from a previous save.
9247 */
9248 int mLoadedStarts;
9249
9250 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009251 * Number of times the process has crashed from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009252 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009253 int mLoadedNumCrashes;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009254
9255 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009256 * Number of times the process has had an ANR from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009257 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009258 int mLoadedNumAnrs;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009259
9260 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009261 * The amount of user time when last unplugged.
9262 */
9263 long mUnpluggedUserTime;
9264
9265 /**
9266 * The amount of system time when last unplugged.
9267 */
9268 long mUnpluggedSystemTime;
9269
9270 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009271 * The amount of foreground time since unplugged.
9272 */
9273 long mUnpluggedForegroundTime;
9274
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009275 /**
9276 * The number of times the process has started before unplugged.
9277 */
9278 int mUnpluggedStarts;
9279
Dianne Hackborn61659e52014-07-09 16:13:01 -07009280 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009281 * Number of times the process has crashed before unplugged.
9282 */
9283 int mUnpluggedNumCrashes;
9284
9285 /**
9286 * Number of times the process has had an ANR before unplugged.
9287 */
9288 int mUnpluggedNumAnrs;
9289
Dianne Hackborn287952c2010-09-22 22:34:31 -07009290 ArrayList<ExcessivePower> mExcessivePower;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009291
Joe Onoratoabded112016-02-08 16:49:39 -08009292 public Proc(BatteryStatsImpl bsi, String name) {
9293 mBsi = bsi;
Dianne Hackborncd0e3352014-08-07 17:08:09 -07009294 mName = name;
Joe Onoratoabded112016-02-08 16:49:39 -08009295 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009296 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07009297
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009298 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009299 mUnpluggedUserTime = mUserTime;
9300 mUnpluggedSystemTime = mSystemTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009301 mUnpluggedForegroundTime = mForegroundTime;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009302 mUnpluggedStarts = mStarts;
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009303 mUnpluggedNumCrashes = mNumCrashes;
9304 mUnpluggedNumAnrs = mNumAnrs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009305 }
9306
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009307 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009308 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009309
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009310 void detach() {
Dianne Hackborn099bc622014-01-22 13:39:16 -08009311 mActive = false;
Joe Onoratoabded112016-02-08 16:49:39 -08009312 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009313 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009314
Dianne Hackborn287952c2010-09-22 22:34:31 -07009315 public int countExcessivePowers() {
9316 return mExcessivePower != null ? mExcessivePower.size() : 0;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009317 }
9318
Dianne Hackborn287952c2010-09-22 22:34:31 -07009319 public ExcessivePower getExcessivePower(int i) {
9320 if (mExcessivePower != null) {
9321 return mExcessivePower.get(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009322 }
9323 return null;
9324 }
9325
Dianne Hackborn287952c2010-09-22 22:34:31 -07009326 public void addExcessiveCpu(long overTime, long usedTime) {
9327 if (mExcessivePower == null) {
9328 mExcessivePower = new ArrayList<ExcessivePower>();
9329 }
9330 ExcessivePower ew = new ExcessivePower();
9331 ew.type = ExcessivePower.TYPE_CPU;
9332 ew.overTime = overTime;
9333 ew.usedTime = usedTime;
9334 mExcessivePower.add(ew);
9335 }
9336
9337 void writeExcessivePowerToParcelLocked(Parcel out) {
9338 if (mExcessivePower == null) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009339 out.writeInt(0);
9340 return;
9341 }
9342
Dianne Hackborn287952c2010-09-22 22:34:31 -07009343 final int N = mExcessivePower.size();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009344 out.writeInt(N);
9345 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009346 ExcessivePower ew = mExcessivePower.get(i);
9347 out.writeInt(ew.type);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009348 out.writeLong(ew.overTime);
9349 out.writeLong(ew.usedTime);
9350 }
9351 }
9352
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009353 void readExcessivePowerFromParcelLocked(Parcel in) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009354 final int N = in.readInt();
9355 if (N == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009356 mExcessivePower = null;
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009357 return;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009358 }
9359
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08009360 if (N > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009361 throw new ParcelFormatException(
9362 "File corrupt: too many excessive power entries " + N);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08009363 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009364
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009365 mExcessivePower = new ArrayList<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009366 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009367 ExcessivePower ew = new ExcessivePower();
9368 ew.type = in.readInt();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009369 ew.overTime = in.readLong();
9370 ew.usedTime = in.readLong();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009371 mExcessivePower.add(ew);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009372 }
9373 }
9374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009375 void writeToParcelLocked(Parcel out) {
9376 out.writeLong(mUserTime);
9377 out.writeLong(mSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009378 out.writeLong(mForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009379 out.writeInt(mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009380 out.writeInt(mNumCrashes);
9381 out.writeInt(mNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009382 out.writeLong(mLoadedUserTime);
9383 out.writeLong(mLoadedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009384 out.writeLong(mLoadedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009385 out.writeInt(mLoadedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009386 out.writeInt(mLoadedNumCrashes);
9387 out.writeInt(mLoadedNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009388 out.writeLong(mUnpluggedUserTime);
9389 out.writeLong(mUnpluggedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009390 out.writeLong(mUnpluggedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009391 out.writeInt(mUnpluggedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009392 out.writeInt(mUnpluggedNumCrashes);
9393 out.writeInt(mUnpluggedNumAnrs);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009394 writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009395 }
9396
9397 void readFromParcelLocked(Parcel in) {
9398 mUserTime = in.readLong();
9399 mSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009400 mForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009401 mStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009402 mNumCrashes = in.readInt();
9403 mNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009404 mLoadedUserTime = in.readLong();
9405 mLoadedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009406 mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009407 mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009408 mLoadedNumCrashes = in.readInt();
9409 mLoadedNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009410 mUnpluggedUserTime = in.readLong();
9411 mUnpluggedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009412 mUnpluggedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009413 mUnpluggedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009414 mUnpluggedNumCrashes = in.readInt();
9415 mUnpluggedNumAnrs = in.readInt();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009416 readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009417 }
9418
Adam Lesinski06af1fa2015-05-05 17:35:35 -07009419 public void addCpuTimeLocked(int utime, int stime) {
Sudheer Shankac57729a2018-02-09 15:44:42 -08009420 addCpuTimeLocked(utime, stime, mBsi.mOnBatteryTimeBase.isRunning());
9421 }
9422
9423 public void addCpuTimeLocked(int utime, int stime, boolean isRunning) {
9424 if (isRunning) {
9425 mUserTime += utime;
9426 mSystemTime += stime;
9427 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009428 }
9429
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009430 public void addForegroundTimeLocked(long ttime) {
9431 mForegroundTime += ttime;
9432 }
9433
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009434 public void incStartsLocked() {
9435 mStarts++;
9436 }
9437
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009438 public void incNumCrashesLocked() {
9439 mNumCrashes++;
9440 }
9441
9442 public void incNumAnrsLocked() {
9443 mNumAnrs++;
9444 }
9445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009446 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -08009447 public boolean isActive() {
9448 return mActive;
9449 }
9450
9451 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009452 public long getUserTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009453 long val = mUserTime;
9454 if (which == STATS_CURRENT) {
9455 val -= mLoadedUserTime;
9456 } else if (which == STATS_SINCE_UNPLUGGED) {
9457 val -= mUnpluggedUserTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009458 }
9459 return val;
9460 }
9461
9462 @Override
9463 public long getSystemTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009464 long val = mSystemTime;
9465 if (which == STATS_CURRENT) {
9466 val -= mLoadedSystemTime;
9467 } else if (which == STATS_SINCE_UNPLUGGED) {
9468 val -= mUnpluggedSystemTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009469 }
9470 return val;
9471 }
9472
9473 @Override
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009474 public long getForegroundTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009475 long val = mForegroundTime;
9476 if (which == STATS_CURRENT) {
9477 val -= mLoadedForegroundTime;
9478 } else if (which == STATS_SINCE_UNPLUGGED) {
9479 val -= mUnpluggedForegroundTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009480 }
9481 return val;
9482 }
9483
9484 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009485 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009486 int val = mStarts;
9487 if (which == STATS_CURRENT) {
9488 val -= mLoadedStarts;
9489 } else if (which == STATS_SINCE_UNPLUGGED) {
9490 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009491 }
9492 return val;
9493 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07009494
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009495 @Override
9496 public int getNumCrashes(int which) {
9497 int val = mNumCrashes;
9498 if (which == STATS_CURRENT) {
9499 val -= mLoadedNumCrashes;
9500 } else if (which == STATS_SINCE_UNPLUGGED) {
9501 val -= mUnpluggedNumCrashes;
9502 }
9503 return val;
9504 }
9505
9506 @Override
9507 public int getNumAnrs(int which) {
9508 int val = mNumAnrs;
9509 if (which == STATS_CURRENT) {
9510 val -= mLoadedNumAnrs;
9511 } else if (which == STATS_SINCE_UNPLUGGED) {
9512 val -= mUnpluggedNumAnrs;
9513 }
9514 return val;
9515 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009516 }
9517
9518 /**
9519 * The statistics associated with a particular package.
9520 */
Joe Onoratoabded112016-02-08 16:49:39 -08009521 public static class Pkg extends BatteryStats.Uid.Pkg implements TimeBaseObs {
9522 /**
9523 * BatteryStatsImpl that we are associated with.
9524 */
9525 protected BatteryStatsImpl mBsi;
9526
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009527 /**
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009528 * Number of times wakeup alarms have occurred for this app.
Bookatz98d4d5c2017-08-01 19:07:54 -07009529 * On screen-off timebase starting in report v25.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009530 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009531 ArrayMap<String, Counter> mWakeupAlarms = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009532
9533 /**
9534 * The statics we have collected for this package's services.
9535 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009536 final ArrayMap<String, Serv> mServiceStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009537
Joe Onoratoabded112016-02-08 16:49:39 -08009538 public Pkg(BatteryStatsImpl bsi) {
9539 mBsi = bsi;
9540 mBsi.mOnBatteryScreenOffTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009541 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009542
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009543 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009544 }
9545
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009546 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009547 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009548
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009549 void detach() {
Joe Onoratoabded112016-02-08 16:49:39 -08009550 mBsi.mOnBatteryScreenOffTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009551 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009552
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009553 void readFromParcelLocked(Parcel in) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009554 int numWA = in.readInt();
9555 mWakeupAlarms.clear();
9556 for (int i=0; i<numWA; i++) {
9557 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -07009558 mWakeupAlarms.put(tag, new Counter(mBsi.mOnBatteryScreenOffTimeBase, in));
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009559 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009560
9561 int numServs = in.readInt();
9562 mServiceStats.clear();
9563 for (int m = 0; m < numServs; m++) {
9564 String serviceName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08009565 Uid.Pkg.Serv serv = new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009566 mServiceStats.put(serviceName, serv);
9567
9568 serv.readFromParcelLocked(in);
9569 }
9570 }
9571
9572 void writeToParcelLocked(Parcel out) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009573 int numWA = mWakeupAlarms.size();
9574 out.writeInt(numWA);
9575 for (int i=0; i<numWA; i++) {
9576 out.writeString(mWakeupAlarms.keyAt(i));
9577 mWakeupAlarms.valueAt(i).writeToParcel(out);
9578 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009579
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009580 final int NS = mServiceStats.size();
9581 out.writeInt(NS);
9582 for (int i=0; i<NS; i++) {
9583 out.writeString(mServiceStats.keyAt(i));
9584 Uid.Pkg.Serv serv = mServiceStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009585 serv.writeToParcelLocked(out);
9586 }
9587 }
9588
9589 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009590 public ArrayMap<String, ? extends BatteryStats.Counter> getWakeupAlarmStats() {
9591 return mWakeupAlarms;
9592 }
9593
9594 public void noteWakeupAlarmLocked(String tag) {
9595 Counter c = mWakeupAlarms.get(tag);
9596 if (c == null) {
Bookatz98d4d5c2017-08-01 19:07:54 -07009597 c = new Counter(mBsi.mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009598 mWakeupAlarms.put(tag, c);
9599 }
9600 c.stepAtomic();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009601 }
9602
9603 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009604 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg.Serv> getServiceStats() {
9605 return mServiceStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009606 }
9607
9608 /**
9609 * The statistics associated with a particular service.
9610 */
Joe Onoratoabded112016-02-08 16:49:39 -08009611 public static class Serv extends BatteryStats.Uid.Pkg.Serv implements TimeBaseObs {
9612 /**
9613 * BatteryStatsImpl that we are associated with.
9614 */
9615 protected BatteryStatsImpl mBsi;
9616
9617 /**
9618 * The android package in which this service resides.
9619 */
9620 protected Pkg mPkg;
9621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009622 /**
9623 * Total time (ms in battery uptime) the service has been left started.
9624 */
Joe Onoratoabded112016-02-08 16:49:39 -08009625 protected long mStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009626
9627 /**
9628 * If service has been started and not yet stopped, this is
9629 * when it was started.
9630 */
Joe Onoratoabded112016-02-08 16:49:39 -08009631 protected long mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009632
9633 /**
9634 * True if we are currently running.
9635 */
Joe Onoratoabded112016-02-08 16:49:39 -08009636 protected boolean mRunning;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009637
9638 /**
9639 * Total number of times startService() has been called.
9640 */
Joe Onoratoabded112016-02-08 16:49:39 -08009641 protected int mStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009642
9643 /**
9644 * Total time (ms in battery uptime) the service has been left launched.
9645 */
Joe Onoratoabded112016-02-08 16:49:39 -08009646 protected long mLaunchedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009647
9648 /**
9649 * If service has been launched and not yet exited, this is
9650 * when it was launched (ms in battery uptime).
9651 */
Joe Onoratoabded112016-02-08 16:49:39 -08009652 protected long mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009653
9654 /**
9655 * True if we are currently launched.
9656 */
Joe Onoratoabded112016-02-08 16:49:39 -08009657 protected boolean mLaunched;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009658
9659 /**
9660 * Total number times the service has been launched.
9661 */
Joe Onoratoabded112016-02-08 16:49:39 -08009662 protected int mLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009663
9664 /**
9665 * The amount of time spent started loaded from a previous save
9666 * (ms in battery uptime).
9667 */
Joe Onoratoabded112016-02-08 16:49:39 -08009668 protected long mLoadedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009669
9670 /**
9671 * The number of starts loaded from a previous save.
9672 */
Joe Onoratoabded112016-02-08 16:49:39 -08009673 protected int mLoadedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009674
9675 /**
9676 * The number of launches loaded from a previous save.
9677 */
Joe Onoratoabded112016-02-08 16:49:39 -08009678 protected int mLoadedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009679
9680 /**
9681 * The amount of time spent started as of the last run (ms
9682 * in battery uptime).
9683 */
Joe Onoratoabded112016-02-08 16:49:39 -08009684 protected long mLastStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009685
9686 /**
9687 * The number of starts as of the last run.
9688 */
Joe Onoratoabded112016-02-08 16:49:39 -08009689 protected int mLastStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009690
9691 /**
9692 * The number of launches as of the last run.
9693 */
Joe Onoratoabded112016-02-08 16:49:39 -08009694 protected int mLastLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009695
9696 /**
9697 * The amount of time spent started when last unplugged (ms
9698 * in battery uptime).
9699 */
Joe Onoratoabded112016-02-08 16:49:39 -08009700 protected long mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009701
9702 /**
9703 * The number of starts when last unplugged.
9704 */
Joe Onoratoabded112016-02-08 16:49:39 -08009705 protected int mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009706
9707 /**
9708 * The number of launches when last unplugged.
9709 */
Joe Onoratoabded112016-02-08 16:49:39 -08009710 protected int mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009711
Joe Onoratoabded112016-02-08 16:49:39 -08009712 /**
9713 * Construct a Serv. Also adds it to the on-battery time base as a listener.
9714 */
9715 public Serv(BatteryStatsImpl bsi) {
9716 mBsi = bsi;
9717 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009718 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009719
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009720 public void onTimeStarted(long elapsedRealtime, long baseUptime,
9721 long baseRealtime) {
9722 mUnpluggedStartTime = getStartTimeToNowLocked(baseUptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009723 mUnpluggedStarts = mStarts;
9724 mUnpluggedLaunches = mLaunches;
9725 }
9726
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009727 public void onTimeStopped(long elapsedRealtime, long baseUptime,
9728 long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009729 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009730
Joe Onoratoabded112016-02-08 16:49:39 -08009731 /**
9732 * Remove this Serv as a listener from the time base.
9733 */
9734 public void detach() {
9735 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009736 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009737
Joe Onoratoabded112016-02-08 16:49:39 -08009738 public void readFromParcelLocked(Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009739 mStartTime = in.readLong();
9740 mRunningSince = in.readLong();
9741 mRunning = in.readInt() != 0;
9742 mStarts = in.readInt();
9743 mLaunchedTime = in.readLong();
9744 mLaunchedSince = in.readLong();
9745 mLaunched = in.readInt() != 0;
9746 mLaunches = in.readInt();
9747 mLoadedStartTime = in.readLong();
9748 mLoadedStarts = in.readInt();
9749 mLoadedLaunches = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07009750 mLastStartTime = 0;
9751 mLastStarts = 0;
9752 mLastLaunches = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009753 mUnpluggedStartTime = in.readLong();
9754 mUnpluggedStarts = in.readInt();
9755 mUnpluggedLaunches = in.readInt();
9756 }
9757
Joe Onoratoabded112016-02-08 16:49:39 -08009758 public void writeToParcelLocked(Parcel out) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009759 out.writeLong(mStartTime);
9760 out.writeLong(mRunningSince);
9761 out.writeInt(mRunning ? 1 : 0);
9762 out.writeInt(mStarts);
9763 out.writeLong(mLaunchedTime);
9764 out.writeLong(mLaunchedSince);
9765 out.writeInt(mLaunched ? 1 : 0);
9766 out.writeInt(mLaunches);
9767 out.writeLong(mLoadedStartTime);
9768 out.writeInt(mLoadedStarts);
9769 out.writeInt(mLoadedLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009770 out.writeLong(mUnpluggedStartTime);
9771 out.writeInt(mUnpluggedStarts);
9772 out.writeInt(mUnpluggedLaunches);
9773 }
9774
Joe Onoratoabded112016-02-08 16:49:39 -08009775 public long getLaunchTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009776 if (!mLaunched) return mLaunchedTime;
9777 return mLaunchedTime + batteryUptime - mLaunchedSince;
9778 }
9779
Joe Onoratoabded112016-02-08 16:49:39 -08009780 public long getStartTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009781 if (!mRunning) return mStartTime;
9782 return mStartTime + batteryUptime - mRunningSince;
9783 }
9784
9785 public void startLaunchedLocked() {
9786 if (!mLaunched) {
9787 mLaunches++;
Joe Onoratoabded112016-02-08 16:49:39 -08009788 mLaunchedSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009789 mLaunched = true;
9790 }
9791 }
9792
9793 public void stopLaunchedLocked() {
9794 if (mLaunched) {
Joe Onoratoabded112016-02-08 16:49:39 -08009795 long time = mBsi.getBatteryUptimeLocked() - mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009796 if (time > 0) {
9797 mLaunchedTime += time;
9798 } else {
9799 mLaunches--;
9800 }
9801 mLaunched = false;
9802 }
9803 }
9804
9805 public void startRunningLocked() {
9806 if (!mRunning) {
9807 mStarts++;
Joe Onoratoabded112016-02-08 16:49:39 -08009808 mRunningSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009809 mRunning = true;
9810 }
9811 }
9812
9813 public void stopRunningLocked() {
9814 if (mRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08009815 long time = mBsi.getBatteryUptimeLocked() - mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009816 if (time > 0) {
9817 mStartTime += time;
9818 } else {
9819 mStarts--;
9820 }
9821 mRunning = false;
9822 }
9823 }
9824
9825 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -08009826 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009827 }
9828
9829 @Override
9830 public int getLaunches(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009831 int val = mLaunches;
9832 if (which == STATS_CURRENT) {
9833 val -= mLoadedLaunches;
9834 } else if (which == STATS_SINCE_UNPLUGGED) {
9835 val -= mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009836 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009837 return val;
9838 }
9839
9840 @Override
9841 public long getStartTime(long now, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009842 long val = getStartTimeToNowLocked(now);
9843 if (which == STATS_CURRENT) {
9844 val -= mLoadedStartTime;
9845 } else if (which == STATS_SINCE_UNPLUGGED) {
9846 val -= mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009847 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009848 return val;
9849 }
9850
9851 @Override
9852 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009853 int val = mStarts;
9854 if (which == STATS_CURRENT) {
9855 val -= mLoadedStarts;
9856 } else if (which == STATS_SINCE_UNPLUGGED) {
9857 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009858 }
9859
9860 return val;
9861 }
9862 }
9863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009864 final Serv newServiceStatsLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08009865 return new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009866 }
9867 }
9868
9869 /**
9870 * Retrieve the statistics object for a particular process, creating
9871 * if needed.
9872 */
9873 public Proc getProcessStatsLocked(String name) {
9874 Proc ps = mProcessStats.get(name);
9875 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08009876 ps = new Proc(mBsi, name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009877 mProcessStats.put(name, ps);
9878 }
9879
9880 return ps;
9881 }
9882
Andreas Gampe3f24e692018-02-05 13:24:28 -08009883 @GuardedBy("mBsi")
Dianne Hackborna8d10942015-11-19 17:55:19 -08009884 public void updateUidProcessStateLocked(int procState) {
9885 int uidRunningState;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009886 // Make special note of Foreground Services
9887 final boolean userAwareService =
9888 (procState == ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009889 uidRunningState = BatteryStats.mapToInternalProcessState(procState);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009890
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009891 if (mProcessState == uidRunningState && userAwareService == mInForegroundService) {
9892 return;
9893 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08009894
Bookatz867c0d72017-03-07 18:23:42 -08009895 final long elapsedRealtimeMs = mBsi.mClocks.elapsedRealtime();
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009896 if (mProcessState != uidRunningState) {
9897 final long uptimeMs = mBsi.mClocks.uptimeMillis();
Dianne Hackborna8d10942015-11-19 17:55:19 -08009898
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009899 if (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
9900 mProcessStateTimer[mProcessState].stopRunningLocked(elapsedRealtimeMs);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009901
Sudheer Shanka5c19b892018-01-05 17:25:46 -08009902 if (mBsi.trackPerProcStateCpuTimes()) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009903 if (mBsi.mPendingUids.size() == 0) {
Sudheer Shankae544d162017-12-28 17:06:20 -08009904 mBsi.mExternalSync.scheduleReadProcStateCpuTimes(
9905 mBsi.mOnBatteryTimeBase.isRunning(),
Sudheer Shankac20379e2018-02-15 00:06:21 -08009906 mBsi.mOnBatteryScreenOffTimeBase.isRunning(),
9907 mBsi.mConstants.PROC_STATE_CPU_TIMES_READ_DELAY_MS);
Mike Ma234d1822018-03-13 18:53:21 -07009908 mBsi.mNumSingleUidCpuTimeReads++;
Sudheer Shankac20379e2018-02-15 00:06:21 -08009909 } else {
Mike Ma234d1822018-03-13 18:53:21 -07009910 mBsi.mNumBatchedSingleUidCpuTimeReads++;
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009911 }
9912 if (mBsi.mPendingUids.indexOfKey(mUid) < 0
9913 || ArrayUtils.contains(CRITICAL_PROC_STATES, mProcessState)) {
9914 mBsi.mPendingUids.put(mUid, mProcessState);
9915 }
9916 } else {
9917 mBsi.mPendingUids.clear();
9918 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07009919 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009920 mProcessState = uidRunningState;
9921 if (uidRunningState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
9922 if (mProcessStateTimer[uidRunningState] == null) {
9923 makeProcessState(uidRunningState, null);
9924 }
9925 mProcessStateTimer[uidRunningState].startRunningLocked(elapsedRealtimeMs);
9926 }
9927
9928 updateOnBatteryBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
9929 updateOnBatteryScreenOffBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009930 }
Bookatz867c0d72017-03-07 18:23:42 -08009931
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009932 if (userAwareService != mInForegroundService) {
9933 if (userAwareService) {
9934 noteForegroundServiceResumedLocked(elapsedRealtimeMs);
9935 } else {
9936 noteForegroundServicePausedLocked(elapsedRealtimeMs);
9937 }
9938 mInForegroundService = userAwareService;
9939 }
Bookatz867c0d72017-03-07 18:23:42 -08009940 }
9941
Bookatzc8c44962017-05-11 12:12:54 -07009942 /** Whether to consider Uid to be in the background for background timebase purposes. */
9943 public boolean isInBackground() {
Bookatz867c0d72017-03-07 18:23:42 -08009944 // Note that PROCESS_STATE_CACHED and ActivityManager.PROCESS_STATE_NONEXISTENT is
9945 // also considered to be 'background' for our purposes, because it's not foreground.
Bookatzc8c44962017-05-11 12:12:54 -07009946 return mProcessState >= PROCESS_STATE_BACKGROUND;
9947 }
9948
9949 public boolean updateOnBatteryBgTimeBase(long uptimeUs, long realtimeUs) {
9950 boolean on = mBsi.mOnBatteryTimeBase.isRunning() && isInBackground();
9951 return mOnBatteryBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
9952 }
9953
9954 public boolean updateOnBatteryScreenOffBgTimeBase(long uptimeUs, long realtimeUs) {
9955 boolean on = mBsi.mOnBatteryScreenOffTimeBase.isRunning() && isInBackground();
9956 return mOnBatteryScreenOffBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009957 }
9958
Dianne Hackbornb5e31652010-09-07 12:13:55 -07009959 public SparseArray<? extends Pid> getPidStats() {
9960 return mPids;
9961 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009962
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009963 public Pid getPidStatsLocked(int pid) {
9964 Pid p = mPids.get(pid);
9965 if (p == null) {
9966 p = new Pid();
9967 mPids.put(pid, p);
9968 }
9969 return p;
9970 }
9971
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009972 /**
9973 * Retrieve the statistics object for a particular service, creating
9974 * if needed.
9975 */
9976 public Pkg getPackageStatsLocked(String name) {
9977 Pkg ps = mPackageStats.get(name);
9978 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08009979 ps = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009980 mPackageStats.put(name, ps);
9981 }
9982
9983 return ps;
9984 }
9985
9986 /**
9987 * Retrieve the statistics object for a particular service, creating
9988 * if needed.
9989 */
9990 public Pkg.Serv getServiceStatsLocked(String pkg, String serv) {
9991 Pkg ps = getPackageStatsLocked(pkg);
9992 Pkg.Serv ss = ps.mServiceStats.get(serv);
9993 if (ss == null) {
9994 ss = ps.newServiceStatsLocked();
9995 ps.mServiceStats.put(serv, ss);
9996 }
9997
9998 return ss;
9999 }
10000
Dianne Hackbornd953c532014-08-16 18:17:38 -070010001 public void readSyncSummaryFromParcelLocked(String name, Parcel in) {
Bookatz2bffb5b2017-04-13 11:59:33 -070010002 DualTimer timer = mSyncStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -070010003 timer.readSummaryFromParcelLocked(in);
10004 mSyncStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010005 }
10006
Dianne Hackbornd953c532014-08-16 18:17:38 -070010007 public void readJobSummaryFromParcelLocked(String name, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -070010008 DualTimer timer = mJobStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -070010009 timer.readSummaryFromParcelLocked(in);
10010 mJobStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010011 }
10012
Dianne Hackbornd953c532014-08-16 18:17:38 -070010013 public void readWakeSummaryFromParcelLocked(String wlName, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -080010014 Wakelock wl = new Wakelock(mBsi, this);
Dianne Hackbornd953c532014-08-16 18:17:38 -070010015 mWakelockStats.add(wlName, wl);
10016 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -070010017 getWakelockTimerLocked(wl, WAKE_TYPE_FULL).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010018 }
Dianne Hackbornd953c532014-08-16 18:17:38 -070010019 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -070010020 getWakelockTimerLocked(wl, WAKE_TYPE_PARTIAL).readSummaryFromParcelLocked(in);
Dianne Hackbornd953c532014-08-16 18:17:38 -070010021 }
10022 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -070010023 getWakelockTimerLocked(wl, WAKE_TYPE_WINDOW).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010024 }
Adam Lesinski9425fe22015-06-19 12:02:13 -070010025 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -070010026 getWakelockTimerLocked(wl, WAKE_TYPE_DRAW).readSummaryFromParcelLocked(in);
Adam Lesinski9425fe22015-06-19 12:02:13 -070010027 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010028 }
10029
Bookatz867c0d72017-03-07 18:23:42 -080010030 public DualTimer getSensorTimerLocked(int sensor, boolean create) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010031 Sensor se = mSensorStats.get(sensor);
10032 if (se == null) {
10033 if (!create) {
10034 return null;
10035 }
Joe Onoratoabded112016-02-08 16:49:39 -080010036 se = new Sensor(mBsi, this, sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010037 mSensorStats.put(sensor, se);
10038 }
Bookatz867c0d72017-03-07 18:23:42 -080010039 DualTimer t = se.mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010040 if (t != null) {
10041 return t;
10042 }
Joe Onoratoabded112016-02-08 16:49:39 -080010043 ArrayList<StopwatchTimer> timers = mBsi.mSensorTimers.get(sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010044 if (timers == null) {
Evan Millarc64edde2009-04-18 12:26:32 -070010045 timers = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -080010046 mBsi.mSensorTimers.put(sensor, timers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010047 }
Bookatz867c0d72017-03-07 18:23:42 -080010048 t = new DualTimer(mBsi.mClocks, this, BatteryStats.SENSOR, timers,
10049 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010050 se.mTimer = t;
10051 return t;
10052 }
10053
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010054 public void noteStartSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -070010055 DualTimer t = mSyncStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010056 if (t != null) {
10057 t.startRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -080010058 StatsLog.write_non_chained(StatsLog.SYNC_STATE_CHANGED, getUid(), null, name,
10059 StatsLog.SYNC_STATE_CHANGED__STATE__ON);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010060 }
10061 }
10062
10063 public void noteStopSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -070010064 DualTimer t = mSyncStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010065 if (t != null) {
10066 t.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -070010067 if (!t.isRunningLocked()) { // only tell statsd if truly stopped
Bookatz90867622018-01-31 15:05:57 -080010068 StatsLog.write_non_chained(StatsLog.SYNC_STATE_CHANGED, getUid(), null, name,
10069 StatsLog.SYNC_STATE_CHANGED__STATE__OFF);
Bookatzc1a050a2017-10-10 15:49:28 -070010070 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010071 }
10072 }
10073
10074 public void noteStartJobLocked(String name, long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -070010075 DualTimer t = mJobStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010076 if (t != null) {
10077 t.startRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -080010078 StatsLog.write_non_chained(StatsLog.SCHEDULED_JOB_STATE_CHANGED, getUid(), null,
Tej Singh33a412b2018-03-16 18:43:59 -070010079 name, StatsLog.SCHEDULED_JOB_STATE_CHANGED__STATE__STARTED,
10080 JobProtoEnums.STOP_REASON_CANCELLED);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010081 }
10082 }
10083
Dianne Hackborn94326cb2017-06-28 16:17:20 -070010084 public void noteStopJobLocked(String name, long elapsedRealtimeMs, int stopReason) {
Bookatzaa4594a2017-03-24 12:39:56 -070010085 DualTimer t = mJobStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010086 if (t != null) {
10087 t.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -070010088 if (!t.isRunningLocked()) { // only tell statsd if truly stopped
Yangster-mac2f5daec2018-01-16 10:23:15 -080010089 StatsLog.write_non_chained(StatsLog.SCHEDULED_JOB_STATE_CHANGED, getUid(), null,
Tej Singh33a412b2018-03-16 18:43:59 -070010090 name, StatsLog.SCHEDULED_JOB_STATE_CHANGED__STATE__FINISHED,
10091 stopReason);
Bookatzc1a050a2017-10-10 15:49:28 -070010092 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010093 }
Dianne Hackborn94326cb2017-06-28 16:17:20 -070010094 if (mBsi.mOnBatteryTimeBase.isRunning()) {
10095 SparseIntArray types = mJobCompletions.get(name);
10096 if (types == null) {
10097 types = new SparseIntArray();
10098 mJobCompletions.put(name, types);
10099 }
10100 int last = types.get(stopReason, 0);
10101 types.put(stopReason, last + 1);
10102 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010103 }
10104
Bookatz5b5ec322017-05-26 09:40:38 -070010105 public StopwatchTimer getWakelockTimerLocked(Wakelock wl, int type) {
10106 if (wl == null) {
10107 return null;
10108 }
10109 switch (type) {
10110 case WAKE_TYPE_PARTIAL: {
10111 DualTimer t = wl.mTimerPartial;
10112 if (t == null) {
10113 t = new DualTimer(mBsi.mClocks, this, WAKE_TYPE_PARTIAL,
10114 mBsi.mPartialTimers, mBsi.mOnBatteryScreenOffTimeBase,
10115 mOnBatteryScreenOffBackgroundTimeBase);
10116 wl.mTimerPartial = t;
10117 }
10118 return t;
10119 }
10120 case WAKE_TYPE_FULL: {
10121 StopwatchTimer t = wl.mTimerFull;
10122 if (t == null) {
10123 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_FULL,
10124 mBsi.mFullTimers, mBsi.mOnBatteryTimeBase);
10125 wl.mTimerFull = t;
10126 }
10127 return t;
10128 }
10129 case WAKE_TYPE_WINDOW: {
10130 StopwatchTimer t = wl.mTimerWindow;
10131 if (t == null) {
10132 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_WINDOW,
10133 mBsi.mWindowTimers, mBsi.mOnBatteryTimeBase);
10134 wl.mTimerWindow = t;
10135 }
10136 return t;
10137 }
10138 case WAKE_TYPE_DRAW: {
10139 StopwatchTimer t = wl.mTimerDraw;
10140 if (t == null) {
10141 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_DRAW,
10142 mBsi.mDrawTimers, mBsi.mOnBatteryTimeBase);
10143 wl.mTimerDraw = t;
10144 }
10145 return t;
10146 }
10147 default:
10148 throw new IllegalArgumentException("type=" + type);
10149 }
10150 }
10151
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010152 public void noteStartWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070010153 Wakelock wl = mWakelockStats.startObject(name);
10154 if (wl != null) {
Bookatz5b5ec322017-05-26 09:40:38 -070010155 getWakelockTimerLocked(wl, type).startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010156 }
Bookatzc8c44962017-05-11 12:12:54 -070010157 if (type == WAKE_TYPE_PARTIAL) {
10158 createAggregatedPartialWakelockTimerLocked().startRunningLocked(elapsedRealtimeMs);
10159 if (pid >= 0) {
10160 Pid p = getPidStatsLocked(pid);
10161 if (p.mWakeNesting++ == 0) {
10162 p.mWakeStartMs = elapsedRealtimeMs;
10163 }
Dianne Hackbornb8071d792010-09-09 16:45:15 -070010164 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010165 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010166 }
10167
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010168 public void noteStopWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070010169 Wakelock wl = mWakelockStats.stopObject(name);
10170 if (wl != null) {
Bookatzd6746242017-10-24 18:39:35 -070010171 StopwatchTimer wlt = getWakelockTimerLocked(wl, type);
10172 wlt.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010173 }
Bookatzc8c44962017-05-11 12:12:54 -070010174 if (type == WAKE_TYPE_PARTIAL) {
10175 if (mAggregatedPartialWakelockTimer != null) {
10176 mAggregatedPartialWakelockTimer.stopRunningLocked(elapsedRealtimeMs);
10177 }
10178 if (pid >= 0) {
10179 Pid p = mPids.get(pid);
10180 if (p != null && p.mWakeNesting > 0) {
10181 if (p.mWakeNesting-- == 1) {
10182 p.mWakeSumMs += elapsedRealtimeMs - p.mWakeStartMs;
10183 p.mWakeStartMs = 0;
10184 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -080010185 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010186 }
10187 }
10188 }
10189
Dianne Hackborn287952c2010-09-22 22:34:31 -070010190 public void reportExcessiveCpuLocked(String proc, long overTime, long usedTime) {
10191 Proc p = getProcessStatsLocked(proc);
10192 if (p != null) {
10193 p.addExcessiveCpu(overTime, usedTime);
10194 }
10195 }
10196
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010197 public void noteStartSensor(int sensor, long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -080010198 DualTimer t = getSensorTimerLocked(sensor, /* create= */ true);
Amith Yamasani154d1242017-02-16 10:01:48 -080010199 t.startRunningLocked(elapsedRealtimeMs);
Narayan Kamath32684dd2018-01-08 17:32:51 +000010200 if (sensor != Sensor.GPS) {
Yangster-mac2f5daec2018-01-16 10:23:15 -080010201 StatsLog.write_non_chained(StatsLog.SENSOR_STATE_CHANGED, getUid(), null, sensor,
Bookatz90867622018-01-31 15:05:57 -080010202 StatsLog.SENSOR_STATE_CHANGED__STATE__ON);
Bookatzc1a050a2017-10-10 15:49:28 -070010203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010204 }
10205
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010206 public void noteStopSensor(int sensor, long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010207 // Don't create a timer if one doesn't already exist
Bookatz867c0d72017-03-07 18:23:42 -080010208 DualTimer t = getSensorTimerLocked(sensor, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010209 if (t != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010210 t.stopRunningLocked(elapsedRealtimeMs);
Narayan Kamath32684dd2018-01-08 17:32:51 +000010211 if (sensor != Sensor.GPS) {
10212 StatsLog.write_non_chained(StatsLog.SENSOR_STATE_CHANGED, getUid(), null,
Bookatz90867622018-01-31 15:05:57 -080010213 sensor, StatsLog.SENSOR_STATE_CHANGED__STATE__OFF);
Bookatzc1a050a2017-10-10 15:49:28 -070010214 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010215 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010216 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010217
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010218 public void noteStartGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -080010219 noteStartSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010220 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010221
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010222 public void noteStopGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -080010223 noteStopSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010224 }
10225
10226 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -080010227 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010228 }
10229 }
10230
Sudheer Shanka9b735c52017-05-09 18:26:18 -070010231 public long[] getCpuFreqs() {
10232 return mCpuFreqs;
10233 }
10234
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010235 public BatteryStatsImpl(File systemDir, Handler handler, PlatformIdleStateCallback cb,
10236 UserInfoProvider userInfoProvider) {
10237 this(new SystemClocks(), systemDir, handler, cb, userInfoProvider);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010238 }
10239
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010240 private BatteryStatsImpl(Clocks clocks, File systemDir, Handler handler,
10241 PlatformIdleStateCallback cb,
10242 UserInfoProvider userInfoProvider) {
Joe Onoratoabded112016-02-08 16:49:39 -080010243 init(clocks);
10244
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010245 if (systemDir != null) {
10246 mFile = new JournaledFile(new File(systemDir, "batterystats.bin"),
10247 new File(systemDir, "batterystats.bin.tmp"));
10248 } else {
10249 mFile = null;
10250 }
10251 mCheckinFile = new AtomicFile(new File(systemDir, "batterystats-checkin.bin"));
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010252 mDailyFile = new AtomicFile(new File(systemDir, "batterystats-daily.xml"));
Jeff Brown6f357d32014-01-15 20:40:55 -080010253 mHandler = new MyHandler(handler.getLooper());
Sudheer Shanka5c19b892018-01-05 17:25:46 -080010254 mConstants = new Constants(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010255 mStartCount++;
Joe Onoratoabded112016-02-08 16:49:39 -080010256 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -070010257 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -070010258 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010259 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010260 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010261 }
Joe Onoratoabded112016-02-08 16:49:39 -080010262 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase);
10263 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
10264 mOnBatteryTimeBase);
10265 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -11, null,
10266 mOnBatteryTimeBase);
10267 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
10268 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null, mOnBatteryTimeBase);
10269 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase);
10270 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase);
10271 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
10272 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i, null,
10273 mOnBatteryTimeBase);
10274 }
10275 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
10276 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010277 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010278 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010279 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010280 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010281 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010282 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
10283 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010284 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010285 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase, NUM_WIFI_TX_LEVELS);
10286 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
10287 NUM_BT_TX_LEVELS);
10288 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
10289 ModemActivityInfo.TX_POWER_LEVELS);
Joe Onoratoabded112016-02-08 16:49:39 -080010290 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null, mOnBatteryTimeBase);
10291 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
10292 mOnBatteryTimeBase);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010293 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010294 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase);
10295 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080010296 mWifiMulticastWakelockTimer = new StopwatchTimer(mClocks, null,
10297 WIFI_AGGREGATE_MULTICAST_ENABLED, null, mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -080010298 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase);
10299 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null, mOnBatteryTimeBase);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010300 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010301 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i, null,
Dianne Hackborn3251b902014-06-20 14:40:53 -070010302 mOnBatteryTimeBase);
10303 }
Joe Onoratoabded112016-02-08 16:49:39 -080010304 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
10305 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i, null,
10306 mOnBatteryTimeBase);
10307 }
10308 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
10309 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i, null,
10310 mOnBatteryTimeBase);
10311 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080010312 mWifiActiveTimer = new StopwatchTimer(mClocks, null, -900, null, mOnBatteryTimeBase);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080010313 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
10314 mGpsSignalQualityTimer[i] = new StopwatchTimer(mClocks, null, -1000-i, null,
10315 mOnBatteryTimeBase);
10316 }
Joe Onoratoabded112016-02-08 16:49:39 -080010317 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
10318 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
10319 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase);
10320 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase);
10321 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010322 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -070010323 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Mike Ma15313c92017-11-15 17:58:21 -080010324 mDischargeLightDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
10325 mDischargeDeepDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010326 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010327 mOnBattery = mOnBatteryInternal = false;
Joe Onoratoabded112016-02-08 16:49:39 -080010328 long uptime = mClocks.uptimeMillis() * 1000;
10329 long realtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010330 initTimes(uptime, realtime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070010331 mStartPlatformVersion = mEndPlatformVersion = Build.ID;
Evan Millar633a1742009-04-02 16:36:33 -070010332 mDischargeStartLevel = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010333 mDischargeUnplugLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010334 mDischargePlugLevel = -1;
Evan Millar633a1742009-04-02 16:36:33 -070010335 mDischargeCurrentLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010336 mCurrentBatteryLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010337 initDischarge();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010338 clearHistoryLocked();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010339 updateDailyDeadlineLocked();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010340 mPlatformIdleStateCallback = cb;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010341 mUserInfoProvider = userInfoProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010342 }
10343
10344 public BatteryStatsImpl(Parcel p) {
Joe Onoratoabded112016-02-08 16:49:39 -080010345 this(new SystemClocks(), p);
10346 }
10347
10348 public BatteryStatsImpl(Clocks clocks, Parcel p) {
10349 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070010350 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010351 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010352 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -070010353 mHandler = null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010354 mExternalSync = null;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080010355 mConstants = new Constants(mHandler);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010356 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010357 readFromParcel(p);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010358 mPlatformIdleStateCallback = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010359 }
10360
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010361 public void setPowerProfileLocked(PowerProfile profile) {
10362 mPowerProfile = profile;
Adam Lesinski6832f392015-09-05 18:05:40 -070010363
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010364 // We need to initialize the KernelCpuSpeedReaders to read from
10365 // the first cpu of each core. Once we have the PowerProfile, we have access to this
10366 // information.
10367 final int numClusters = mPowerProfile.getNumCpuClusters();
10368 mKernelCpuSpeedReaders = new KernelCpuSpeedReader[numClusters];
10369 int firstCpuOfCluster = 0;
10370 for (int i = 0; i < numClusters; i++) {
10371 final int numSpeedSteps = mPowerProfile.getNumSpeedStepsInCpuCluster(i);
10372 mKernelCpuSpeedReaders[i] = new KernelCpuSpeedReader(firstCpuOfCluster,
10373 numSpeedSteps);
10374 firstCpuOfCluster += mPowerProfile.getNumCoresInCpuCluster(i);
10375 }
Adam Lesinskif9b20a92016-06-17 17:30:01 -070010376
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010377 if (mEstimatedBatteryCapacity == -1) {
10378 // Initialize the estimated battery capacity to a known preset one.
10379 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
Adam Lesinskie08af192015-03-25 16:42:59 -070010380 }
10381 }
10382
Dianne Hackborn0d903a82010-09-07 23:51:03 -070010383 public void setCallback(BatteryCallback cb) {
10384 mCallback = cb;
10385 }
10386
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010387 public void setRadioScanningTimeoutLocked(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -070010388 if (mPhoneSignalScanningTimer != null) {
10389 mPhoneSignalScanningTimer.setTimeout(timeout);
10390 }
10391 }
10392
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070010393 public void setExternalStatsSyncLocked(ExternalStatsSync sync) {
10394 mExternalSync = sync;
10395 }
10396
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010397 public void updateDailyDeadlineLocked() {
10398 // Get the current time.
10399 long currentTime = mDailyStartTime = System.currentTimeMillis();
10400 Calendar calDeadline = Calendar.getInstance();
10401 calDeadline.setTimeInMillis(currentTime);
10402
10403 // Move time up to the next day, ranging from 1am to 3pm.
10404 calDeadline.set(Calendar.DAY_OF_YEAR, calDeadline.get(Calendar.DAY_OF_YEAR) + 1);
10405 calDeadline.set(Calendar.MILLISECOND, 0);
10406 calDeadline.set(Calendar.SECOND, 0);
10407 calDeadline.set(Calendar.MINUTE, 0);
10408 calDeadline.set(Calendar.HOUR_OF_DAY, 1);
10409 mNextMinDailyDeadline = calDeadline.getTimeInMillis();
10410 calDeadline.set(Calendar.HOUR_OF_DAY, 3);
10411 mNextMaxDailyDeadline = calDeadline.getTimeInMillis();
10412 }
10413
10414 public void recordDailyStatsIfNeededLocked(boolean settled) {
10415 long currentTime = System.currentTimeMillis();
10416 if (currentTime >= mNextMaxDailyDeadline) {
10417 recordDailyStatsLocked();
10418 } else if (settled && currentTime >= mNextMinDailyDeadline) {
10419 recordDailyStatsLocked();
10420 } else if (currentTime < (mDailyStartTime-(1000*60*60*24))) {
10421 recordDailyStatsLocked();
10422 }
10423 }
10424
10425 public void recordDailyStatsLocked() {
10426 DailyItem item = new DailyItem();
10427 item.mStartTime = mDailyStartTime;
10428 item.mEndTime = System.currentTimeMillis();
10429 boolean hasData = false;
10430 if (mDailyDischargeStepTracker.mNumStepDurations > 0) {
10431 hasData = true;
10432 item.mDischargeSteps = new LevelStepTracker(
10433 mDailyDischargeStepTracker.mNumStepDurations,
10434 mDailyDischargeStepTracker.mStepDurations);
10435 }
10436 if (mDailyChargeStepTracker.mNumStepDurations > 0) {
10437 hasData = true;
10438 item.mChargeSteps = new LevelStepTracker(
10439 mDailyChargeStepTracker.mNumStepDurations,
10440 mDailyChargeStepTracker.mStepDurations);
10441 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010442 if (mDailyPackageChanges != null) {
10443 hasData = true;
10444 item.mPackageChanges = mDailyPackageChanges;
10445 mDailyPackageChanges = null;
10446 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010447 mDailyDischargeStepTracker.init();
10448 mDailyChargeStepTracker.init();
10449 updateDailyDeadlineLocked();
10450
10451 if (hasData) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080010452 final long startTime = SystemClock.uptimeMillis();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010453 mDailyItems.add(item);
10454 while (mDailyItems.size() > MAX_DAILY_ITEMS) {
10455 mDailyItems.remove(0);
10456 }
10457 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
10458 try {
10459 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010010460 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010461 writeDailyItemsLocked(out);
Dianne Hackborne17b4452018-01-10 13:15:40 -080010462 final long initialTime = SystemClock.uptimeMillis() - startTime;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010463 BackgroundThread.getHandler().post(new Runnable() {
10464 @Override
10465 public void run() {
10466 synchronized (mCheckinFile) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080010467 final long startTime2 = SystemClock.uptimeMillis();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010468 FileOutputStream stream = null;
10469 try {
10470 stream = mDailyFile.startWrite();
10471 memStream.writeTo(stream);
10472 stream.flush();
10473 FileUtils.sync(stream);
10474 stream.close();
10475 mDailyFile.finishWrite(stream);
Dianne Hackborne17b4452018-01-10 13:15:40 -080010476 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
10477 "batterystats-daily",
10478 initialTime + SystemClock.uptimeMillis() - startTime2);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010479 } catch (IOException e) {
10480 Slog.w("BatteryStats",
10481 "Error writing battery daily items", e);
10482 mDailyFile.failWrite(stream);
10483 }
10484 }
10485 }
10486 });
10487 } catch (IOException e) {
10488 }
10489 }
10490 }
10491
10492 private void writeDailyItemsLocked(XmlSerializer out) throws IOException {
10493 StringBuilder sb = new StringBuilder(64);
10494 out.startDocument(null, true);
10495 out.startTag(null, "daily-items");
10496 for (int i=0; i<mDailyItems.size(); i++) {
10497 final DailyItem dit = mDailyItems.get(i);
10498 out.startTag(null, "item");
10499 out.attribute(null, "start", Long.toString(dit.mStartTime));
10500 out.attribute(null, "end", Long.toString(dit.mEndTime));
10501 writeDailyLevelSteps(out, "dis", dit.mDischargeSteps, sb);
10502 writeDailyLevelSteps(out, "chg", dit.mChargeSteps, sb);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010503 if (dit.mPackageChanges != null) {
10504 for (int j=0; j<dit.mPackageChanges.size(); j++) {
10505 PackageChange pc = dit.mPackageChanges.get(j);
10506 if (pc.mUpdate) {
10507 out.startTag(null, "upd");
10508 out.attribute(null, "pkg", pc.mPackageName);
Dianne Hackborn3accca02013-09-20 09:32:11 -070010509 out.attribute(null, "ver", Long.toString(pc.mVersionCode));
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010510 out.endTag(null, "upd");
10511 } else {
10512 out.startTag(null, "rem");
10513 out.attribute(null, "pkg", pc.mPackageName);
10514 out.endTag(null, "rem");
10515 }
10516 }
10517 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010518 out.endTag(null, "item");
10519 }
10520 out.endTag(null, "daily-items");
10521 out.endDocument();
10522 }
10523
10524 private void writeDailyLevelSteps(XmlSerializer out, String tag, LevelStepTracker steps,
10525 StringBuilder tmpBuilder) throws IOException {
10526 if (steps != null) {
10527 out.startTag(null, tag);
10528 out.attribute(null, "n", Integer.toString(steps.mNumStepDurations));
10529 for (int i=0; i<steps.mNumStepDurations; i++) {
10530 out.startTag(null, "s");
10531 tmpBuilder.setLength(0);
10532 steps.encodeEntryAt(i, tmpBuilder);
10533 out.attribute(null, "v", tmpBuilder.toString());
10534 out.endTag(null, "s");
10535 }
10536 out.endTag(null, tag);
10537 }
10538 }
10539
10540 public void readDailyStatsLocked() {
10541 Slog.d(TAG, "Reading daily items from " + mDailyFile.getBaseFile());
10542 mDailyItems.clear();
10543 FileInputStream stream;
10544 try {
10545 stream = mDailyFile.openRead();
10546 } catch (FileNotFoundException e) {
10547 return;
10548 }
10549 try {
10550 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010010551 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010552 readDailyItemsLocked(parser);
10553 } catch (XmlPullParserException e) {
10554 } finally {
10555 try {
10556 stream.close();
10557 } catch (IOException e) {
10558 }
10559 }
10560 }
10561
10562 private void readDailyItemsLocked(XmlPullParser parser) {
10563 try {
10564 int type;
10565 while ((type = parser.next()) != XmlPullParser.START_TAG
10566 && type != XmlPullParser.END_DOCUMENT) {
10567 ;
10568 }
10569
10570 if (type != XmlPullParser.START_TAG) {
10571 throw new IllegalStateException("no start tag found");
10572 }
10573
10574 int outerDepth = parser.getDepth();
10575 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10576 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10577 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10578 continue;
10579 }
10580
10581 String tagName = parser.getName();
10582 if (tagName.equals("item")) {
10583 readDailyItemTagLocked(parser);
10584 } else {
10585 Slog.w(TAG, "Unknown element under <daily-items>: "
10586 + parser.getName());
10587 XmlUtils.skipCurrentTag(parser);
10588 }
10589 }
10590
10591 } catch (IllegalStateException e) {
10592 Slog.w(TAG, "Failed parsing daily " + e);
10593 } catch (NullPointerException e) {
10594 Slog.w(TAG, "Failed parsing daily " + e);
10595 } catch (NumberFormatException e) {
10596 Slog.w(TAG, "Failed parsing daily " + e);
10597 } catch (XmlPullParserException e) {
10598 Slog.w(TAG, "Failed parsing daily " + e);
10599 } catch (IOException e) {
10600 Slog.w(TAG, "Failed parsing daily " + e);
10601 } catch (IndexOutOfBoundsException e) {
10602 Slog.w(TAG, "Failed parsing daily " + e);
10603 }
10604 }
10605
10606 void readDailyItemTagLocked(XmlPullParser parser) throws NumberFormatException,
10607 XmlPullParserException, IOException {
10608 DailyItem dit = new DailyItem();
10609 String attr = parser.getAttributeValue(null, "start");
10610 if (attr != null) {
10611 dit.mStartTime = Long.parseLong(attr);
10612 }
10613 attr = parser.getAttributeValue(null, "end");
10614 if (attr != null) {
10615 dit.mEndTime = Long.parseLong(attr);
10616 }
10617 int outerDepth = parser.getDepth();
10618 int type;
10619 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10620 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10621 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10622 continue;
10623 }
10624
10625 String tagName = parser.getName();
10626 if (tagName.equals("dis")) {
10627 readDailyItemTagDetailsLocked(parser, dit, false, "dis");
10628 } else if (tagName.equals("chg")) {
10629 readDailyItemTagDetailsLocked(parser, dit, true, "chg");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010630 } else if (tagName.equals("upd")) {
10631 if (dit.mPackageChanges == null) {
10632 dit.mPackageChanges = new ArrayList<>();
10633 }
10634 PackageChange pc = new PackageChange();
10635 pc.mUpdate = true;
10636 pc.mPackageName = parser.getAttributeValue(null, "pkg");
10637 String verStr = parser.getAttributeValue(null, "ver");
Dianne Hackborn3accca02013-09-20 09:32:11 -070010638 pc.mVersionCode = verStr != null ? Long.parseLong(verStr) : 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010639 dit.mPackageChanges.add(pc);
10640 XmlUtils.skipCurrentTag(parser);
10641 } else if (tagName.equals("rem")) {
10642 if (dit.mPackageChanges == null) {
10643 dit.mPackageChanges = new ArrayList<>();
10644 }
10645 PackageChange pc = new PackageChange();
10646 pc.mUpdate = false;
10647 pc.mPackageName = parser.getAttributeValue(null, "pkg");
10648 dit.mPackageChanges.add(pc);
10649 XmlUtils.skipCurrentTag(parser);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010650 } else {
10651 Slog.w(TAG, "Unknown element under <item>: "
10652 + parser.getName());
10653 XmlUtils.skipCurrentTag(parser);
10654 }
10655 }
10656 mDailyItems.add(dit);
10657 }
10658
10659 void readDailyItemTagDetailsLocked(XmlPullParser parser, DailyItem dit, boolean isCharge,
10660 String tag)
10661 throws NumberFormatException, XmlPullParserException, IOException {
10662 final String numAttr = parser.getAttributeValue(null, "n");
10663 if (numAttr == null) {
10664 Slog.w(TAG, "Missing 'n' attribute at " + parser.getPositionDescription());
10665 XmlUtils.skipCurrentTag(parser);
10666 return;
10667 }
10668 final int num = Integer.parseInt(numAttr);
10669 LevelStepTracker steps = new LevelStepTracker(num);
10670 if (isCharge) {
10671 dit.mChargeSteps = steps;
10672 } else {
10673 dit.mDischargeSteps = steps;
10674 }
10675 int i = 0;
10676 int outerDepth = parser.getDepth();
10677 int type;
10678 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10679 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10680 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10681 continue;
10682 }
10683
10684 String tagName = parser.getName();
10685 if ("s".equals(tagName)) {
10686 if (i < num) {
10687 String valueAttr = parser.getAttributeValue(null, "v");
10688 if (valueAttr != null) {
10689 steps.decodeEntryAt(i, valueAttr);
10690 i++;
10691 }
10692 }
10693 } else {
10694 Slog.w(TAG, "Unknown element under <" + tag + ">: "
10695 + parser.getName());
10696 XmlUtils.skipCurrentTag(parser);
10697 }
10698 }
10699 steps.mNumStepDurations = i;
10700 }
10701
10702 @Override
10703 public DailyItem getDailyItemLocked(int daysAgo) {
10704 int index = mDailyItems.size()-1-daysAgo;
10705 return index >= 0 ? mDailyItems.get(index) : null;
10706 }
10707
10708 @Override
10709 public long getCurrentDailyStartTime() {
10710 return mDailyStartTime;
10711 }
10712
10713 @Override
10714 public long getNextMinDailyDeadline() {
10715 return mNextMinDailyDeadline;
10716 }
10717
10718 @Override
10719 public long getNextMaxDailyDeadline() {
10720 return mNextMaxDailyDeadline;
10721 }
10722
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010723 @Override
10724 public boolean startIteratingOldHistoryLocked() {
10725 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
10726 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010727 if ((mHistoryIterator = mHistory) == null) {
10728 return false;
10729 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010730 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010731 mHistoryReadTmp.clear();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010732 mReadOverflow = false;
10733 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010734 return true;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010735 }
10736
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010737 @Override
10738 public boolean getNextOldHistoryLocked(HistoryItem out) {
10739 boolean end = mHistoryBuffer.dataPosition() >= mHistoryBuffer.dataSize();
10740 if (!end) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010741 readHistoryDelta(mHistoryBuffer, mHistoryReadTmp);
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010742 mReadOverflow |= mHistoryReadTmp.cmd == HistoryItem.CMD_OVERFLOW;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010743 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010744 HistoryItem cur = mHistoryIterator;
10745 if (cur == null) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010746 if (!mReadOverflow && !end) {
10747 Slog.w(TAG, "Old history ends before new history!");
10748 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010749 return false;
10750 }
10751 out.setTo(cur);
10752 mHistoryIterator = cur.next;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010753 if (!mReadOverflow) {
10754 if (end) {
10755 Slog.w(TAG, "New history ends before old history!");
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010756 } else if (!out.same(mHistoryReadTmp)) {
Dianne Hackborn8c841092013-06-24 13:46:13 -070010757 PrintWriter pw = new FastPrintWriter(new LogWriter(android.util.Log.WARN, TAG));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010758 pw.println("Histories differ!");
10759 pw.println("Old history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010760 (new HistoryPrinter()).printNextItem(pw, out, 0, false, true);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010761 pw.println("New history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010762 (new HistoryPrinter()).printNextItem(pw, mHistoryReadTmp, 0, false,
10763 true);
Dianne Hackborn8c841092013-06-24 13:46:13 -070010764 pw.flush();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010765 }
10766 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010767 return true;
10768 }
10769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010770 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010771 public void finishIteratingOldHistoryLocked() {
10772 mIteratingHistory = false;
10773 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010774 mHistoryIterator = null;
10775 }
10776
10777 public int getHistoryTotalSize() {
10778 return MAX_HISTORY_BUFFER;
10779 }
10780
10781 public int getHistoryUsedSize() {
10782 return mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010783 }
10784
10785 @Override
10786 public boolean startIteratingHistoryLocked() {
10787 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
10788 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010789 if (mHistoryBuffer.dataSize() <= 0) {
10790 return false;
10791 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010792 mHistoryBuffer.setDataPosition(0);
10793 mReadOverflow = false;
10794 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010795 mReadHistoryStrings = new String[mHistoryTagPool.size()];
10796 mReadHistoryUids = new int[mHistoryTagPool.size()];
10797 mReadHistoryChars = 0;
10798 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
10799 final HistoryTag tag = ent.getKey();
10800 final int idx = ent.getValue();
10801 mReadHistoryStrings[idx] = tag.string;
10802 mReadHistoryUids[idx] = tag.uid;
10803 mReadHistoryChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080010804 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010805 return true;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010806 }
10807
10808 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -080010809 public int getHistoryStringPoolSize() {
10810 return mReadHistoryStrings.length;
10811 }
10812
10813 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010814 public int getHistoryStringPoolBytes() {
10815 // Each entry is a fixed 12 bytes: 4 for index, 4 for uid, 4 for string size
10816 // Each string character is 2 bytes.
10817 return (mReadHistoryStrings.length * 12) + (mReadHistoryChars * 2);
10818 }
10819
10820 @Override
10821 public String getHistoryTagPoolString(int index) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080010822 return mReadHistoryStrings[index];
10823 }
10824
10825 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010826 public int getHistoryTagPoolUid(int index) {
10827 return mReadHistoryUids[index];
10828 }
10829
10830 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010831 public boolean getNextHistoryLocked(HistoryItem out) {
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010832 final int pos = mHistoryBuffer.dataPosition();
10833 if (pos == 0) {
10834 out.clear();
10835 }
10836 boolean end = pos >= mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010837 if (end) {
10838 return false;
10839 }
10840
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010841 final long lastRealtime = out.time;
10842 final long lastWalltime = out.currentTime;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010843 readHistoryDelta(mHistoryBuffer, out);
Dianne Hackborn37de0982014-05-09 09:32:18 -070010844 if (out.cmd != HistoryItem.CMD_CURRENT_TIME
10845 && out.cmd != HistoryItem.CMD_RESET && lastWalltime != 0) {
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010846 out.currentTime = lastWalltime + (out.time - lastRealtime);
10847 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010848 return true;
10849 }
10850
10851 @Override
10852 public void finishIteratingHistoryLocked() {
10853 mIteratingHistory = false;
10854 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn099bc622014-01-22 13:39:16 -080010855 mReadHistoryStrings = null;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010856 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010857
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010858 @Override
Dianne Hackbornb5e31652010-09-07 12:13:55 -070010859 public long getHistoryBaseTime() {
10860 return mHistoryBaseTime;
10861 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010862
Dianne Hackbornb5e31652010-09-07 12:13:55 -070010863 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010864 public int getStartCount() {
10865 return mStartCount;
10866 }
10867
10868 public boolean isOnBattery() {
10869 return mOnBattery;
10870 }
10871
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010872 public boolean isCharging() {
10873 return mCharging;
10874 }
10875
Mike Mac2f518a2017-09-19 16:06:03 -070010876 public boolean isScreenOn(int state) {
Chris Phoenix10a4a642017-09-25 13:21:00 -070010877 return state == Display.STATE_ON || state == Display.STATE_VR
10878 || state == Display.STATE_ON_SUSPEND;
Mike Mac2f518a2017-09-19 16:06:03 -070010879 }
10880
10881 public boolean isScreenOff(int state) {
10882 return state == Display.STATE_OFF;
10883 }
10884
10885 public boolean isScreenDoze(int state) {
10886 return state == Display.STATE_DOZE || state == Display.STATE_DOZE_SUSPEND;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010887 }
10888
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010889 void initTimes(long uptime, long realtime) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080010890 mStartClockTime = System.currentTimeMillis();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010891 mOnBatteryTimeBase.init(uptime, realtime);
10892 mOnBatteryScreenOffTimeBase.init(uptime, realtime);
Dianne Hackborn4590e522014-03-24 13:36:46 -070010893 mRealtime = 0;
10894 mUptime = 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010895 mRealtimeStart = realtime;
Dianne Hackborn4590e522014-03-24 13:36:46 -070010896 mUptimeStart = uptime;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010897 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010898
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010899 void initDischarge() {
10900 mLowDischargeAmountSinceCharge = 0;
10901 mHighDischargeAmountSinceCharge = 0;
10902 mDischargeAmountScreenOn = 0;
10903 mDischargeAmountScreenOnSinceCharge = 0;
10904 mDischargeAmountScreenOff = 0;
10905 mDischargeAmountScreenOffSinceCharge = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010906 mDischargeAmountScreenDoze = 0;
10907 mDischargeAmountScreenDozeSinceCharge = 0;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010908 mDischargeStepTracker.init();
10909 mChargeStepTracker.init();
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010910 mDischargeScreenOffCounter.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -070010911 mDischargeScreenDozeCounter.reset(false);
Mike Ma15313c92017-11-15 17:58:21 -080010912 mDischargeLightDozeCounter.reset(false);
10913 mDischargeDeepDozeCounter.reset(false);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010914 mDischargeCounter.reset(false);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010915 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010916
10917 public void resetAllStatsCmdLocked() {
10918 resetAllStatsLocked();
Joe Onoratoabded112016-02-08 16:49:39 -080010919 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -070010920 long uptime = mSecUptime * 1000;
Joe Onoratoabded112016-02-08 16:49:39 -080010921 long mSecRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010922 long realtime = mSecRealtime * 1000;
10923 mDischargeStartLevel = mHistoryCur.batteryLevel;
10924 pullPendingStateUpdatesLocked();
Dianne Hackborn40c87252014-03-19 16:55:40 -070010925 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010926 mDischargeCurrentLevel = mDischargeUnplugLevel = mDischargePlugLevel
10927 = mCurrentBatteryLevel = mHistoryCur.batteryLevel;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010928 mOnBatteryTimeBase.reset(uptime, realtime);
10929 mOnBatteryScreenOffTimeBase.reset(uptime, realtime);
10930 if ((mHistoryCur.states&HistoryItem.STATE_BATTERY_PLUGGED_FLAG) == 0) {
Mike Mac2f518a2017-09-19 16:06:03 -070010931 if (isScreenOn(mScreenState)) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010932 mDischargeScreenOnUnplugLevel = mHistoryCur.batteryLevel;
Mike Mac2f518a2017-09-19 16:06:03 -070010933 mDischargeScreenDozeUnplugLevel = 0;
10934 mDischargeScreenOffUnplugLevel = 0;
10935 } else if (isScreenDoze(mScreenState)) {
10936 mDischargeScreenOnUnplugLevel = 0;
10937 mDischargeScreenDozeUnplugLevel = mHistoryCur.batteryLevel;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010938 mDischargeScreenOffUnplugLevel = 0;
10939 } else {
10940 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010941 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010942 mDischargeScreenOffUnplugLevel = mHistoryCur.batteryLevel;
10943 }
10944 mDischargeAmountScreenOn = 0;
10945 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010946 mDischargeAmountScreenDoze = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010947 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070010948 initActiveHistoryEventsLocked(mSecRealtime, mSecUptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010949 }
10950
10951 private void resetAllStatsLocked() {
Adam Lesinski8ce36942016-05-26 16:05:35 -070010952 final long uptimeMillis = mClocks.uptimeMillis();
10953 final long elapsedRealtimeMillis = mClocks.elapsedRealtime();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010954 mStartCount = 0;
Adam Lesinski8ce36942016-05-26 16:05:35 -070010955 initTimes(uptimeMillis * 1000, elapsedRealtimeMillis * 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010956 mScreenOnTimer.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -070010957 mScreenDozeTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010958 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010959 mScreenBrightnessTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010960 }
Adam Lesinski1a76a622016-06-22 10:28:47 -070010961
10962 if (mPowerProfile != null) {
10963 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
10964 } else {
10965 mEstimatedBatteryCapacity = -1;
10966 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070010967 mMinLearnedBatteryCapacity = -1;
10968 mMaxLearnedBatteryCapacity = -1;
Jeff Browne95c3cd2014-05-02 16:59:26 -070010969 mInteractiveTimer.reset(false);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070010970 mPowerSaveModeEnabledTimer.reset(false);
Adam Lesinski8ce36942016-05-26 16:05:35 -070010971 mLastIdleTimeStart = elapsedRealtimeMillis;
Dianne Hackborn08c47a52015-10-15 12:38:14 -070010972 mLongestLightIdleTime = 0;
10973 mLongestFullIdleTime = 0;
10974 mDeviceIdleModeLightTimer.reset(false);
10975 mDeviceIdleModeFullTimer.reset(false);
10976 mDeviceLightIdlingTimer.reset(false);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010977 mDeviceIdlingTimer.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010978 mPhoneOnTimer.reset(false);
10979 mAudioOnTimer.reset(false);
10980 mVideoOnTimer.reset(false);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070010981 mFlashlightOnTimer.reset(false);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070010982 mCameraOnTimer.reset(false);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010983 mBluetoothScanTimer.reset(false);
Wink Saville52840902011-02-18 12:40:47 -080010984 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010985 mPhoneSignalStrengthsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010986 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010987 mPhoneSignalScanningTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010988 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010989 mPhoneDataConnectionsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010990 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010991 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010992 mNetworkByteActivityCounters[i].reset(false);
10993 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010994 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010995 mMobileRadioActiveTimer.reset(false);
10996 mMobileRadioActivePerAppTimer.reset(false);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010997 mMobileRadioActiveAdjustedTime.reset(false);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080010998 mMobileRadioActiveUnknownTime.reset(false);
10999 mMobileRadioActiveUnknownCount.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011000 mWifiOnTimer.reset(false);
11001 mGlobalWifiRunningTimer.reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080011002 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011003 mWifiStateTimer[i].reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080011004 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070011005 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
11006 mWifiSupplStateTimer[i].reset(false);
11007 }
11008 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
11009 mWifiSignalStrengthsTimer[i].reset(false);
11010 }
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080011011 mWifiMulticastWakelockTimer.reset(false);
Siddharth Rayb50a6842017-12-14 15:15:28 -080011012 mWifiActiveTimer.reset(false);
11013 mWifiActivity.reset(false);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080011014 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
11015 mGpsSignalQualityTimer[i].reset(false);
11016 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011017 mBluetoothActivity.reset(false);
11018 mModemActivity.reset(false);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080011019 mNumConnectivityChange = mLoadedNumConnectivityChange = mUnpluggedNumConnectivityChange = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011020
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011021 for (int i=0; i<mUidStats.size(); i++) {
Bookatz993a0be2017-07-21 09:03:23 -070011022 if (mUidStats.valueAt(i).reset(uptimeMillis * 1000, elapsedRealtimeMillis * 1000)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011023 mUidStats.remove(mUidStats.keyAt(i));
11024 i--;
11025 }
11026 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011027
Bookatz50df7112017-08-04 14:53:26 -070011028 if (mRpmStats.size() > 0) {
11029 for (SamplingTimer timer : mRpmStats.values()) {
11030 mOnBatteryTimeBase.remove(timer);
11031 }
11032 mRpmStats.clear();
11033 }
11034 if (mScreenOffRpmStats.size() > 0) {
11035 for (SamplingTimer timer : mScreenOffRpmStats.values()) {
11036 mOnBatteryScreenOffTimeBase.remove(timer);
11037 }
11038 mScreenOffRpmStats.clear();
11039 }
11040
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011041 if (mKernelWakelockStats.size() > 0) {
11042 for (SamplingTimer timer : mKernelWakelockStats.values()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011043 mOnBatteryScreenOffTimeBase.remove(timer);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011044 }
11045 mKernelWakelockStats.clear();
11046 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011047
James Carr3a226052016-07-01 14:49:52 -070011048 if (mKernelMemoryStats.size() > 0) {
11049 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
11050 mOnBatteryTimeBase.remove(mKernelMemoryStats.valueAt(i));
11051 }
11052 mKernelMemoryStats.clear();
11053 }
11054
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011055 if (mWakeupReasonStats.size() > 0) {
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070011056 for (SamplingTimer timer : mWakeupReasonStats.values()) {
11057 mOnBatteryTimeBase.remove(timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011058 }
11059 mWakeupReasonStats.clear();
11060 }
11061
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080011062 mLastHistoryStepDetails = null;
11063 mLastStepCpuUserTime = mLastStepCpuSystemTime = 0;
11064 mCurStepCpuUserTime = mCurStepCpuSystemTime = 0;
11065 mLastStepCpuUserTime = mCurStepCpuUserTime = 0;
11066 mLastStepCpuSystemTime = mCurStepCpuSystemTime = 0;
11067 mLastStepStatUserTime = mCurStepStatUserTime = 0;
11068 mLastStepStatSystemTime = mCurStepStatSystemTime = 0;
11069 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime = 0;
11070 mLastStepStatIrqTime = mCurStepStatIrqTime = 0;
11071 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime = 0;
11072 mLastStepStatIdleTime = mCurStepStatIdleTime = 0;
11073
Mike Ma234d1822018-03-13 18:53:21 -070011074 mNumAllUidCpuTimeReads = 0;
11075 mNumUidsRemoved = 0;
11076
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011077 initDischarge();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011078
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011079 clearHistoryLocked();
11080 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011081
Dianne Hackborn40c87252014-03-19 16:55:40 -070011082 private void initActiveHistoryEventsLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080011083 for (int i=0; i<HistoryItem.EVENT_COUNT; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011084 if (!mRecordAllHistory && i == HistoryItem.EVENT_PROC) {
11085 // Not recording process starts/stops.
11086 continue;
11087 }
Dianne Hackborn37de0982014-05-09 09:32:18 -070011088 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(i);
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080011089 if (active == null) {
11090 continue;
11091 }
Dianne Hackborn37de0982014-05-09 09:32:18 -070011092 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
11093 SparseIntArray uids = ent.getValue();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080011094 for (int j=0; j<uids.size(); j++) {
Dianne Hackborn37de0982014-05-09 09:32:18 -070011095 addHistoryEventLocked(elapsedRealtimeMs, uptimeMs, i, ent.getKey(),
11096 uids.keyAt(j));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080011097 }
11098 }
11099 }
11100 }
11101
Mike Mac2f518a2017-09-19 16:06:03 -070011102 void updateDischargeScreenLevelsLocked(int oldState, int newState) {
11103 updateOldDischargeScreenLevelLocked(oldState);
11104 updateNewDischargeScreenLevelLocked(newState);
11105 }
11106
11107 private void updateOldDischargeScreenLevelLocked(int state) {
11108 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011109 int diff = mDischargeScreenOnUnplugLevel - mDischargeCurrentLevel;
11110 if (diff > 0) {
11111 mDischargeAmountScreenOn += diff;
11112 mDischargeAmountScreenOnSinceCharge += diff;
11113 }
Mike Mac2f518a2017-09-19 16:06:03 -070011114 } else if (isScreenDoze(state)) {
11115 int diff = mDischargeScreenDozeUnplugLevel - mDischargeCurrentLevel;
11116 if (diff > 0) {
11117 mDischargeAmountScreenDoze += diff;
11118 mDischargeAmountScreenDozeSinceCharge += diff;
11119 }
11120 } else if (isScreenOff(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011121 int diff = mDischargeScreenOffUnplugLevel - mDischargeCurrentLevel;
11122 if (diff > 0) {
11123 mDischargeAmountScreenOff += diff;
11124 mDischargeAmountScreenOffSinceCharge += diff;
11125 }
11126 }
Mike Mac2f518a2017-09-19 16:06:03 -070011127 }
11128
11129 private void updateNewDischargeScreenLevelLocked(int state) {
11130 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011131 mDischargeScreenOnUnplugLevel = mDischargeCurrentLevel;
11132 mDischargeScreenOffUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070011133 mDischargeScreenDozeUnplugLevel = 0;
11134 } else if (isScreenDoze(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011135 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070011136 mDischargeScreenDozeUnplugLevel = mDischargeCurrentLevel;
11137 mDischargeScreenOffUnplugLevel = 0;
11138 } else if (isScreenOff(state)) {
11139 mDischargeScreenOnUnplugLevel = 0;
11140 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011141 mDischargeScreenOffUnplugLevel = mDischargeCurrentLevel;
11142 }
11143 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011144
Dianne Hackborna7c837f2014-01-15 16:20:44 -080011145 public void pullPendingStateUpdatesLocked() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -080011146 if (mOnBatteryInternal) {
Mike Mac2f518a2017-09-19 16:06:03 -070011147 updateDischargeScreenLevelsLocked(mScreenState, mScreenState);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080011148 }
Dianne Hackborna7c837f2014-01-15 16:20:44 -080011149 }
11150
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011151 private final NetworkStatsFactory mNetworkStatsFactory = new NetworkStatsFactory();
11152 private final Pools.Pool<NetworkStats> mNetworkStatsPool = new Pools.SynchronizedPool<>(6);
11153
11154 private final Object mWifiNetworkLock = new Object();
11155
11156 @GuardedBy("mWifiNetworkLock")
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011157 private String[] mWifiIfaces = EmptyArray.STRING;
11158
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011159 @GuardedBy("mWifiNetworkLock")
11160 private NetworkStats mLastWifiNetworkStats = new NetworkStats(0, -1);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011161
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011162 private final Object mModemNetworkLock = new Object();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011163
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011164 @GuardedBy("mModemNetworkLock")
11165 private String[] mModemIfaces = EmptyArray.STRING;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011166
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011167 @GuardedBy("mModemNetworkLock")
11168 private NetworkStats mLastModemNetworkStats = new NetworkStats(0, -1);
11169
11170 private NetworkStats readNetworkStatsLocked(String[] ifaces) {
11171 try {
11172 if (!ArrayUtils.isEmpty(ifaces)) {
11173 return mNetworkStatsFactory.readNetworkStatsDetail(NetworkStats.UID_ALL, ifaces,
11174 NetworkStats.TAG_NONE, mNetworkStatsPool.acquire());
11175 }
11176 } catch (IOException e) {
11177 Slog.e(TAG, "failed to read network stats for ifaces: " + Arrays.toString(ifaces));
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011178 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011179 return null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011180 }
11181
Chenjie Yu89083392018-01-11 14:53:31 -080011182 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011183 * Distribute WiFi energy info and network traffic to apps.
11184 * @param info The energy information from the WiFi controller.
11185 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011186 public void updateWifiState(@Nullable final WifiActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011187 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011188 Slog.d(TAG, "Updating wifi stats: " + Arrays.toString(mWifiIfaces));
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011189 }
11190
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011191 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070011192 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011193 synchronized (mWifiNetworkLock) {
11194 final NetworkStats latestStats = readNetworkStatsLocked(mWifiIfaces);
11195 if (latestStats != null) {
11196 delta = NetworkStats.subtract(latestStats, mLastWifiNetworkStats, null, null,
11197 mNetworkStatsPool.acquire());
11198 mNetworkStatsPool.release(mLastWifiNetworkStats);
11199 mLastWifiNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070011200 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011201 }
11202
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011203 synchronized (this) {
11204 if (!mOnBatteryInternal) {
11205 if (delta != null) {
11206 mNetworkStatsPool.release(delta);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011207 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011208 return;
11209 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011210
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011211 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
11212 SparseLongArray rxPackets = new SparseLongArray();
11213 SparseLongArray txPackets = new SparseLongArray();
11214 long totalTxPackets = 0;
11215 long totalRxPackets = 0;
11216 if (delta != null) {
11217 NetworkStats.Entry entry = new NetworkStats.Entry();
11218 final int size = delta.size();
11219 for (int i = 0; i < size; i++) {
11220 entry = delta.getValues(i, entry);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011221
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011222 if (DEBUG_ENERGY) {
11223 Slog.d(TAG, "Wifi uid " + entry.uid + ": delta rx=" + entry.rxBytes
11224 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
11225 + " txPackets=" + entry.txPackets);
11226 }
11227
11228 if (entry.rxBytes == 0 && entry.txBytes == 0) {
11229 // Skip the lookup below since there is no work to do.
11230 continue;
11231 }
11232
11233 final Uid u = getUidStatsLocked(mapUid(entry.uid));
11234 if (entry.rxBytes != 0) {
11235 u.noteNetworkActivityLocked(NETWORK_WIFI_RX_DATA, entry.rxBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -080011236 entry.rxPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011237 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11238 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_RX_DATA, entry.rxBytes,
11239 entry.rxPackets);
11240 }
11241 mNetworkByteActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
11242 entry.rxBytes);
11243 mNetworkPacketActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
11244 entry.rxPackets);
11245
11246 rxPackets.put(u.getUid(), entry.rxPackets);
11247
11248 // Sum the total number of packets so that the Rx Power can
11249 // be evenly distributed amongst the apps.
11250 totalRxPackets += entry.rxPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -080011251 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011252
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011253 if (entry.txBytes != 0) {
11254 u.noteNetworkActivityLocked(NETWORK_WIFI_TX_DATA, entry.txBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -080011255 entry.txPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011256 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11257 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_TX_DATA, entry.txBytes,
11258 entry.txPackets);
11259 }
11260 mNetworkByteActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
11261 entry.txBytes);
11262 mNetworkPacketActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
11263 entry.txPackets);
11264
11265 txPackets.put(u.getUid(), entry.txPackets);
11266
11267 // Sum the total number of packets so that the Tx Power can
11268 // be evenly distributed amongst the apps.
11269 totalTxPackets += entry.txPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -080011270 }
Adam Lesinskiba88e682015-12-08 12:06:55 -080011271 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011272 mNetworkStatsPool.release(delta);
11273 delta = null;
Adam Lesinskie08af192015-03-25 16:42:59 -070011274 }
11275
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011276 if (info != null) {
11277 mHasWifiReporting = true;
Adam Lesinskie08af192015-03-25 16:42:59 -070011278
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011279 // Measured in mAms
11280 final long txTimeMs = info.getControllerTxTimeMillis();
11281 final long rxTimeMs = info.getControllerRxTimeMillis();
Siddharth Rayb50a6842017-12-14 15:15:28 -080011282 final long scanTimeMs = info.getControllerScanTimeMillis();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011283 final long idleTimeMs = info.getControllerIdleTimeMillis();
11284 final long totalTimeMs = txTimeMs + rxTimeMs + idleTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -070011285
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011286 long leftOverRxTimeMs = rxTimeMs;
11287 long leftOverTxTimeMs = txTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -070011288
Adam Lesinskie08af192015-03-25 16:42:59 -070011289 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011290 Slog.d(TAG, "------ BEGIN WiFi power blaming ------");
11291 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
11292 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
11293 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms");
11294 Slog.d(TAG, " Total Time: " + totalTimeMs + " ms");
Siddharth Rayb50a6842017-12-14 15:15:28 -080011295 Slog.d(TAG, " Scan Time: " + scanTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070011296 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011297
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011298 long totalWifiLockTimeMs = 0;
11299 long totalScanTimeMs = 0;
11300
11301 // On the first pass, collect some totals so that we can normalize power
11302 // calculations if we need to.
11303 final int uidStatsSize = mUidStats.size();
11304 for (int i = 0; i < uidStatsSize; i++) {
11305 final Uid uid = mUidStats.valueAt(i);
11306
11307 // Sum the total scan power for all apps.
11308 totalScanTimeMs += uid.mWifiScanTimer.getTimeSinceMarkLocked(
11309 elapsedRealtimeMs * 1000) / 1000;
11310
11311 // Sum the total time holding wifi lock for all apps.
11312 totalWifiLockTimeMs += uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
11313 elapsedRealtimeMs * 1000) / 1000;
11314 }
11315
11316 if (DEBUG_ENERGY && totalScanTimeMs > rxTimeMs) {
11317 Slog.d(TAG,
11318 " !Estimated scan time > Actual rx time (" + totalScanTimeMs + " ms > "
11319 + rxTimeMs + " ms). Normalizing scan time.");
11320 }
11321 if (DEBUG_ENERGY && totalScanTimeMs > txTimeMs) {
11322 Slog.d(TAG,
11323 " !Estimated scan time > Actual tx time (" + totalScanTimeMs + " ms > "
11324 + txTimeMs + " ms). Normalizing scan time.");
11325 }
11326
11327 // Actually assign and distribute power usage to apps.
11328 for (int i = 0; i < uidStatsSize; i++) {
11329 final Uid uid = mUidStats.valueAt(i);
11330
11331 long scanTimeSinceMarkMs = uid.mWifiScanTimer.getTimeSinceMarkLocked(
11332 elapsedRealtimeMs * 1000) / 1000;
11333 if (scanTimeSinceMarkMs > 0) {
11334 // Set the new mark so that next time we get new data since this point.
11335 uid.mWifiScanTimer.setMark(elapsedRealtimeMs);
11336
11337 long scanRxTimeSinceMarkMs = scanTimeSinceMarkMs;
11338 long scanTxTimeSinceMarkMs = scanTimeSinceMarkMs;
11339
11340 // Our total scan time is more than the reported Tx/Rx time.
11341 // This is possible because the cost of a scan is approximate.
11342 // Let's normalize the result so that we evenly blame each app
11343 // scanning.
11344 //
11345 // This means that we may have apps that transmitted/received packets not be
11346 // blamed for this, but this is fine as scans are relatively more expensive.
11347 if (totalScanTimeMs > rxTimeMs) {
11348 scanRxTimeSinceMarkMs = (rxTimeMs * scanRxTimeSinceMarkMs) /
11349 totalScanTimeMs;
11350 }
11351 if (totalScanTimeMs > txTimeMs) {
11352 scanTxTimeSinceMarkMs = (txTimeMs * scanTxTimeSinceMarkMs) /
11353 totalScanTimeMs;
11354 }
11355
11356 if (DEBUG_ENERGY) {
11357 Slog.d(TAG, " ScanTime for UID " + uid.getUid() + ": Rx:"
11358 + scanRxTimeSinceMarkMs + " ms Tx:"
11359 + scanTxTimeSinceMarkMs + " ms)");
11360 }
11361
11362 ControllerActivityCounterImpl activityCounter =
11363 uid.getOrCreateWifiControllerActivityLocked();
11364 activityCounter.getRxTimeCounter().addCountLocked(scanRxTimeSinceMarkMs);
11365 activityCounter.getTxTimeCounters()[0].addCountLocked(
11366 scanTxTimeSinceMarkMs);
11367 leftOverRxTimeMs -= scanRxTimeSinceMarkMs;
11368 leftOverTxTimeMs -= scanTxTimeSinceMarkMs;
11369 }
11370
11371 // Distribute evenly the power consumed while Idle to each app holding a WiFi
11372 // lock.
11373 final long wifiLockTimeSinceMarkMs =
11374 uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
11375 elapsedRealtimeMs * 1000) / 1000;
11376 if (wifiLockTimeSinceMarkMs > 0) {
11377 // Set the new mark so that next time we get new data since this point.
11378 uid.mFullWifiLockTimer.setMark(elapsedRealtimeMs);
11379
11380 final long myIdleTimeMs = (wifiLockTimeSinceMarkMs * idleTimeMs)
11381 / totalWifiLockTimeMs;
11382 if (DEBUG_ENERGY) {
11383 Slog.d(TAG, " IdleTime for UID " + uid.getUid() + ": "
11384 + myIdleTimeMs + " ms");
11385 }
11386 uid.getOrCreateWifiControllerActivityLocked().getIdleTimeCounter()
11387 .addCountLocked(myIdleTimeMs);
11388 }
11389 }
11390
Adam Lesinskie08af192015-03-25 16:42:59 -070011391 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011392 Slog.d(TAG, " New RxPower: " + leftOverRxTimeMs + " ms");
11393 Slog.d(TAG, " New TxPower: " + leftOverTxTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070011394 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011395
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011396 // Distribute the remaining Tx power appropriately between all apps that transmitted
11397 // packets.
11398 for (int i = 0; i < txPackets.size(); i++) {
11399 final Uid uid = getUidStatsLocked(txPackets.keyAt(i));
11400 final long myTxTimeMs = (txPackets.valueAt(i) * leftOverTxTimeMs)
11401 / totalTxPackets;
11402 if (DEBUG_ENERGY) {
11403 Slog.d(TAG, " TxTime for UID " + uid.getUid() + ": " + myTxTimeMs + " ms");
11404 }
11405 uid.getOrCreateWifiControllerActivityLocked().getTxTimeCounters()[0]
11406 .addCountLocked(myTxTimeMs);
11407 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011408
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011409 // Distribute the remaining Rx power appropriately between all apps that received
11410 // packets.
11411 for (int i = 0; i < rxPackets.size(); i++) {
11412 final Uid uid = getUidStatsLocked(rxPackets.keyAt(i));
11413 final long myRxTimeMs = (rxPackets.valueAt(i) * leftOverRxTimeMs)
11414 / totalRxPackets;
11415 if (DEBUG_ENERGY) {
11416 Slog.d(TAG, " RxTime for UID " + uid.getUid() + ": " + myRxTimeMs + " ms");
11417 }
11418 uid.getOrCreateWifiControllerActivityLocked().getRxTimeCounter()
11419 .addCountLocked(myRxTimeMs);
11420 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011421
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011422 // Any left over power use will be picked up by the WiFi category in BatteryStatsHelper.
11423
11424
11425 // Update WiFi controller stats.
11426 mWifiActivity.getRxTimeCounter().addCountLocked(info.getControllerRxTimeMillis());
11427 mWifiActivity.getTxTimeCounters()[0].addCountLocked(
11428 info.getControllerTxTimeMillis());
Siddharth Rayb50a6842017-12-14 15:15:28 -080011429 mWifiActivity.getScanTimeCounter().addCountLocked(
11430 info.getControllerScanTimeMillis());
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011431 mWifiActivity.getIdleTimeCounter().addCountLocked(
11432 info.getControllerIdleTimeMillis());
11433
11434 // POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11435 final double opVolt = mPowerProfile.getAveragePower(
11436 PowerProfile.POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11437 if (opVolt != 0) {
11438 // We store the power drain as mAms.
11439 mWifiActivity.getPowerCounter().addCountLocked(
11440 (long) (info.getControllerEnergyUsed() / opVolt));
11441 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011442 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011443 }
11444 }
11445
Chenjie Yu89083392018-01-11 14:53:31 -080011446 private ModemActivityInfo mLastModemActivityInfo =
11447 new ModemActivityInfo(0, 0, 0, new int[0], 0, 0);
11448
Chenjie Yua54e54d2018-02-14 20:12:52 -080011449 private ModemActivityInfo getDeltaModemActivityInfo(ModemActivityInfo activityInfo) {
11450 if (activityInfo == null) {
11451 return null;
11452 }
11453 int[] txTimeMs = new int[ModemActivityInfo.TX_POWER_LEVELS];
11454 for (int i = 0; i < ModemActivityInfo.TX_POWER_LEVELS; i++) {
11455 txTimeMs[i] = activityInfo.getTxTimeMillis()[i]
11456 - mLastModemActivityInfo.getTxTimeMillis()[i];
11457 }
11458 ModemActivityInfo deltaInfo = new ModemActivityInfo(activityInfo.getTimestamp(),
11459 activityInfo.getSleepTimeMillis() - mLastModemActivityInfo.getSleepTimeMillis(),
11460 activityInfo.getIdleTimeMillis() - mLastModemActivityInfo.getIdleTimeMillis(),
11461 txTimeMs,
11462 activityInfo.getRxTimeMillis() - mLastModemActivityInfo.getRxTimeMillis(),
11463 activityInfo.getEnergyUsed() - mLastModemActivityInfo.getEnergyUsed());
11464 mLastModemActivityInfo = activityInfo;
11465 return deltaInfo;
11466 }
11467
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011468 /**
11469 * Distribute Cell radio energy info and network traffic to apps.
11470 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011471 public void updateMobileRadioState(@Nullable final ModemActivityInfo activityInfo) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011472 if (DEBUG_ENERGY) {
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011473 Slog.d(TAG, "Updating mobile radio stats with " + activityInfo);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011474 }
Chenjie Yua54e54d2018-02-14 20:12:52 -080011475 ModemActivityInfo deltaInfo = getDeltaModemActivityInfo(activityInfo);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011476
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011477 // Add modem tx power to history.
Chenjie Yua54e54d2018-02-14 20:12:52 -080011478 addModemTxPowerToHistory(deltaInfo);
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011479
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011480 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070011481 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011482 synchronized (mModemNetworkLock) {
11483 final NetworkStats latestStats = readNetworkStatsLocked(mModemIfaces);
11484 if (latestStats != null) {
11485 delta = NetworkStats.subtract(latestStats, mLastModemNetworkStats, null, null,
11486 mNetworkStatsPool.acquire());
11487 mNetworkStatsPool.release(mLastModemNetworkStats);
11488 mLastModemNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070011489 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011490 }
11491
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011492 synchronized (this) {
11493 if (!mOnBatteryInternal) {
11494 if (delta != null) {
11495 mNetworkStatsPool.release(delta);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011496 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011497 return;
Adam Lesinskie08af192015-03-25 16:42:59 -070011498 }
11499
Chenjie Yua54e54d2018-02-14 20:12:52 -080011500 if (deltaInfo != null) {
Siddharth Ray2038af82018-01-17 17:40:26 -080011501 mHasModemReporting = true;
11502 mModemActivity.getIdleTimeCounter().addCountLocked(
Chenjie Yua54e54d2018-02-14 20:12:52 -080011503 deltaInfo.getIdleTimeMillis());
Siddharth Rayed754702018-02-15 12:44:37 -080011504 mModemActivity.getSleepTimeCounter().addCountLocked(
11505 deltaInfo.getSleepTimeMillis());
Chenjie Yua54e54d2018-02-14 20:12:52 -080011506 mModemActivity.getRxTimeCounter().addCountLocked(deltaInfo.getRxTimeMillis());
Siddharth Ray2038af82018-01-17 17:40:26 -080011507 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
11508 mModemActivity.getTxTimeCounters()[lvl]
Chenjie Yua54e54d2018-02-14 20:12:52 -080011509 .addCountLocked(deltaInfo.getTxTimeMillis()[lvl]);
Siddharth Ray2038af82018-01-17 17:40:26 -080011510 }
11511
11512 // POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11513 final double opVolt = mPowerProfile.getAveragePower(
11514 PowerProfile.POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11515 if (opVolt != 0) {
11516 double energyUsed =
Chenjie Yua54e54d2018-02-14 20:12:52 -080011517 deltaInfo.getSleepTimeMillis() *
Siddharth Ray2038af82018-01-17 17:40:26 -080011518 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_SLEEP)
Chenjie Yua54e54d2018-02-14 20:12:52 -080011519 + deltaInfo.getIdleTimeMillis() *
Siddharth Ray2038af82018-01-17 17:40:26 -080011520 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_IDLE)
Chenjie Yua54e54d2018-02-14 20:12:52 -080011521 + deltaInfo.getRxTimeMillis() *
Siddharth Ray2038af82018-01-17 17:40:26 -080011522 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_RX);
Chenjie Yua54e54d2018-02-14 20:12:52 -080011523 int[] txTimeMs = deltaInfo.getTxTimeMillis();
Chenjie Yu89083392018-01-11 14:53:31 -080011524 for (int i = 0; i < Math.min(txTimeMs.length,
Chenjie Yua54e54d2018-02-14 20:12:52 -080011525 SignalStrength.NUM_SIGNAL_STRENGTH_BINS); i++) {
Chenjie Yu89083392018-01-11 14:53:31 -080011526 energyUsed += txTimeMs[i] * mPowerProfile.getAveragePower(
Chenjie Yua54e54d2018-02-14 20:12:52 -080011527 PowerProfile.POWER_MODEM_CONTROLLER_TX, i);
Siddharth Ray2038af82018-01-17 17:40:26 -080011528 }
11529
11530 // We store the power drain as mAms.
11531 mModemActivity.getPowerCounter().addCountLocked((long) energyUsed);
11532 }
11533 }
11534
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070011535 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011536 long radioTime = mMobileRadioActivePerAppTimer.getTimeSinceMarkLocked(
11537 elapsedRealtimeMs * 1000);
11538 mMobileRadioActivePerAppTimer.setMark(elapsedRealtimeMs);
11539
11540 long totalRxPackets = 0;
11541 long totalTxPackets = 0;
11542 if (delta != null) {
11543 NetworkStats.Entry entry = new NetworkStats.Entry();
11544 final int size = delta.size();
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011545 for (int i = 0; i < size; i++) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011546 entry = delta.getValues(i, entry);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011547 if (entry.rxPackets == 0 && entry.txPackets == 0) {
11548 continue;
11549 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011550
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011551 if (DEBUG_ENERGY) {
11552 Slog.d(TAG, "Mobile uid " + entry.uid + ": delta rx=" + entry.rxBytes
11553 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
11554 + " txPackets=" + entry.txPackets);
11555 }
11556
11557 totalRxPackets += entry.rxPackets;
11558 totalTxPackets += entry.txPackets;
11559
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011560 final Uid u = getUidStatsLocked(mapUid(entry.uid));
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011561 u.noteNetworkActivityLocked(NETWORK_MOBILE_RX_DATA, entry.rxBytes,
11562 entry.rxPackets);
11563 u.noteNetworkActivityLocked(NETWORK_MOBILE_TX_DATA, entry.txBytes,
11564 entry.txPackets);
11565 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11566 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_RX_DATA,
11567 entry.rxBytes, entry.rxPackets);
11568 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_TX_DATA,
11569 entry.txBytes, entry.txPackets);
11570 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011571
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011572 mNetworkByteActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
11573 entry.rxBytes);
11574 mNetworkByteActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
11575 entry.txBytes);
11576 mNetworkPacketActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
11577 entry.rxPackets);
11578 mNetworkPacketActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
11579 entry.txPackets);
11580 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011581
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011582 // Now distribute proportional blame to the apps that did networking.
11583 long totalPackets = totalRxPackets + totalTxPackets;
11584 if (totalPackets > 0) {
11585 for (int i = 0; i < size; i++) {
11586 entry = delta.getValues(i, entry);
11587 if (entry.rxPackets == 0 && entry.txPackets == 0) {
11588 continue;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011589 }
11590
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011591 final Uid u = getUidStatsLocked(mapUid(entry.uid));
11592
11593 // Distribute total radio active time in to this app.
11594 final long appPackets = entry.rxPackets + entry.txPackets;
11595 final long appRadioTime = (radioTime * appPackets) / totalPackets;
11596 u.noteMobileRadioActiveTimeLocked(appRadioTime);
11597
11598 // Remove this app from the totals, so that we don't lose any time
11599 // due to rounding.
11600 radioTime -= appRadioTime;
11601 totalPackets -= appPackets;
11602
Chenjie Yua54e54d2018-02-14 20:12:52 -080011603 if (deltaInfo != null) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011604 ControllerActivityCounterImpl activityCounter =
11605 u.getOrCreateModemControllerActivityLocked();
11606 if (totalRxPackets > 0 && entry.rxPackets > 0) {
Chenjie Yua54e54d2018-02-14 20:12:52 -080011607 final long rxMs = (entry.rxPackets * deltaInfo.getRxTimeMillis())
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011608 / totalRxPackets;
11609 activityCounter.getRxTimeCounter().addCountLocked(rxMs);
11610 }
11611
11612 if (totalTxPackets > 0 && entry.txPackets > 0) {
11613 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
11614 long txMs =
Chenjie Yua54e54d2018-02-14 20:12:52 -080011615 entry.txPackets * deltaInfo.getTxTimeMillis()[lvl];
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011616 txMs /= totalTxPackets;
11617 activityCounter.getTxTimeCounters()[lvl].addCountLocked(txMs);
11618 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011619 }
11620 }
11621 }
11622 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011623
11624 if (radioTime > 0) {
11625 // Whoops, there is some radio time we can't blame on an app!
11626 mMobileRadioActiveUnknownTime.addCountLocked(radioTime);
11627 mMobileRadioActiveUnknownCount.addCountLocked(1);
11628 }
11629
11630 mNetworkStatsPool.release(delta);
11631 delta = null;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011632 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011633 }
11634 }
11635
11636 /**
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011637 * Add modem tx power to history
11638 * Device is said to be in high cellular transmit power when it has spent most of the transmit
11639 * time at the highest power level.
11640 * @param activityInfo
11641 */
Siddharth Raya67fb562018-02-28 13:46:16 -080011642 private synchronized void addModemTxPowerToHistory(final ModemActivityInfo activityInfo) {
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011643 if (activityInfo == null) {
11644 return;
11645 }
11646 int[] txTimeMs = activityInfo.getTxTimeMillis();
11647 if (txTimeMs == null || txTimeMs.length != ModemActivityInfo.TX_POWER_LEVELS) {
11648 return;
11649 }
11650 final long elapsedRealtime = mClocks.elapsedRealtime();
11651 final long uptime = mClocks.uptimeMillis();
11652 int levelMaxTimeSpent = 0;
11653 for (int i = 1; i < txTimeMs.length; i++) {
11654 if (txTimeMs[i] > txTimeMs[levelMaxTimeSpent]) {
11655 levelMaxTimeSpent = i;
11656 }
11657 }
11658 if (levelMaxTimeSpent == ModemActivityInfo.TX_POWER_LEVELS - 1) {
11659 if (!mIsCellularTxPowerHigh) {
11660 mHistoryCur.states2 |= HistoryItem.STATE2_CELLULAR_HIGH_TX_POWER_FLAG;
11661 addHistoryRecordLocked(elapsedRealtime, uptime);
11662 mIsCellularTxPowerHigh = true;
11663 }
11664 return;
11665 }
11666 if (mIsCellularTxPowerHigh) {
11667 mHistoryCur.states2 &= ~HistoryItem.STATE2_CELLULAR_HIGH_TX_POWER_FLAG;
11668 addHistoryRecordLocked(elapsedRealtime, uptime);
11669 mIsCellularTxPowerHigh = false;
11670 }
11671 return;
11672 }
11673
Mike Ma561a8d92018-03-20 18:24:05 -070011674 private final class BluetoothActivityInfoCache {
11675 long idleTimeMs;
11676 long rxTimeMs;
11677 long txTimeMs;
11678 long energy;
11679
11680 SparseLongArray uidRxBytes = new SparseLongArray();
11681 SparseLongArray uidTxBytes = new SparseLongArray();
11682
11683 void set(BluetoothActivityEnergyInfo info) {
11684 idleTimeMs = info.getControllerIdleTimeMillis();
11685 rxTimeMs = info.getControllerRxTimeMillis();
11686 txTimeMs = info.getControllerTxTimeMillis();
11687 energy = info.getControllerEnergyUsed();
11688 if (info.getUidTraffic() != null) {
11689 for (UidTraffic traffic : info.getUidTraffic()) {
11690 uidRxBytes.put(traffic.getUid(), traffic.getRxBytes());
11691 uidTxBytes.put(traffic.getUid(), traffic.getTxBytes());
11692 }
11693 }
11694 }
11695 }
11696
11697 private final BluetoothActivityInfoCache mLastBluetoothActivityInfo
11698 = new BluetoothActivityInfoCache();
11699
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011700 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011701 * Distribute Bluetooth energy info and network traffic to apps.
Mike Ma561a8d92018-03-20 18:24:05 -070011702 *
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011703 * @param info The energy information from the bluetooth controller.
11704 */
11705 public void updateBluetoothStateLocked(@Nullable final BluetoothActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011706 if (DEBUG_ENERGY) {
Adam Lesinski50e47602015-12-04 17:04:54 -080011707 Slog.d(TAG, "Updating bluetooth stats: " + info);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011708 }
11709
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011710 if (info == null || !mOnBatteryInternal) {
11711 return;
11712 }
Adam Lesinskie283d332015-04-16 12:29:25 -070011713
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011714 mHasBluetoothReporting = true;
11715
Bookatz867c0d72017-03-07 18:23:42 -080011716 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Mike Ma561a8d92018-03-20 18:24:05 -070011717 final long rxTimeMs =
11718 info.getControllerRxTimeMillis() - mLastBluetoothActivityInfo.rxTimeMs;
11719 final long txTimeMs =
11720 info.getControllerTxTimeMillis() - mLastBluetoothActivityInfo.txTimeMs;
11721 final long idleTimeMs =
11722 info.getControllerIdleTimeMillis() - mLastBluetoothActivityInfo.idleTimeMs;
11723
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011724 if (DEBUG_ENERGY) {
11725 Slog.d(TAG, "------ BEGIN BLE power blaming ------");
11726 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
11727 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
Chenjie Yu89083392018-01-11 14:53:31 -080011728 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms");
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011729 }
11730
11731 long totalScanTimeMs = 0;
11732
11733 final int uidCount = mUidStats.size();
11734 for (int i = 0; i < uidCount; i++) {
11735 final Uid u = mUidStats.valueAt(i);
11736 if (u.mBluetoothScanTimer == null) {
11737 continue;
Adam Lesinskie283d332015-04-16 12:29:25 -070011738 }
Adam Lesinski50e47602015-12-04 17:04:54 -080011739
Bookatzaa4594a2017-03-24 12:39:56 -070011740 totalScanTimeMs += u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011741 elapsedRealtimeMs * 1000) / 1000;
11742 }
11743
11744 final boolean normalizeScanRxTime = (totalScanTimeMs > rxTimeMs);
11745 final boolean normalizeScanTxTime = (totalScanTimeMs > txTimeMs);
11746
11747 if (DEBUG_ENERGY) {
11748 Slog.d(TAG, "Normalizing scan power for RX=" + normalizeScanRxTime
11749 + " TX=" + normalizeScanTxTime);
11750 }
11751
11752 long leftOverRxTimeMs = rxTimeMs;
11753 long leftOverTxTimeMs = txTimeMs;
11754
11755 for (int i = 0; i < uidCount; i++) {
11756 final Uid u = mUidStats.valueAt(i);
11757 if (u.mBluetoothScanTimer == null) {
11758 continue;
11759 }
11760
Bookatzaa4594a2017-03-24 12:39:56 -070011761 long scanTimeSinceMarkMs = u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011762 elapsedRealtimeMs * 1000) / 1000;
11763 if (scanTimeSinceMarkMs > 0) {
11764 // Set the new mark so that next time we get new data since this point.
11765 u.mBluetoothScanTimer.setMark(elapsedRealtimeMs);
11766
11767 long scanTimeRxSinceMarkMs = scanTimeSinceMarkMs;
11768 long scanTimeTxSinceMarkMs = scanTimeSinceMarkMs;
11769
11770 if (normalizeScanRxTime) {
11771 // Scan time is longer than the total rx time in the controller,
11772 // so distribute the scan time proportionately. This means regular traffic
11773 // will not blamed, but scans are more expensive anyways.
11774 scanTimeRxSinceMarkMs = (rxTimeMs * scanTimeRxSinceMarkMs) / totalScanTimeMs;
11775 }
11776
11777 if (normalizeScanTxTime) {
11778 // Scan time is longer than the total tx time in the controller,
11779 // so distribute the scan time proportionately. This means regular traffic
11780 // will not blamed, but scans are more expensive anyways.
11781 scanTimeTxSinceMarkMs = (txTimeMs * scanTimeTxSinceMarkMs) / totalScanTimeMs;
11782 }
11783
11784 final ControllerActivityCounterImpl counter =
11785 u.getOrCreateBluetoothControllerActivityLocked();
11786 counter.getRxTimeCounter().addCountLocked(scanTimeRxSinceMarkMs);
11787 counter.getTxTimeCounters()[0].addCountLocked(scanTimeTxSinceMarkMs);
11788
11789 leftOverRxTimeMs -= scanTimeRxSinceMarkMs;
11790 leftOverTxTimeMs -= scanTimeTxSinceMarkMs;
11791 }
11792 }
11793
11794 if (DEBUG_ENERGY) {
Mike Ma561a8d92018-03-20 18:24:05 -070011795 Slog.d(TAG, "Left over time for traffic RX=" + leftOverRxTimeMs + " TX="
11796 + leftOverTxTimeMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011797 }
11798
11799 //
11800 // Now distribute blame to apps that did bluetooth traffic.
11801 //
11802
11803 long totalTxBytes = 0;
11804 long totalRxBytes = 0;
11805
11806 final UidTraffic[] uidTraffic = info.getUidTraffic();
Mike Ma561a8d92018-03-20 18:24:05 -070011807 final int numUids = uidTraffic != null ? uidTraffic.length : 0;
11808 for (int i = 0; i < numUids; i++) {
11809 final UidTraffic traffic = uidTraffic[i];
11810 final long rxBytes = traffic.getRxBytes() - mLastBluetoothActivityInfo.uidRxBytes.get(
11811 traffic.getUid());
11812 final long txBytes = traffic.getTxBytes() - mLastBluetoothActivityInfo.uidTxBytes.get(
11813 traffic.getUid());
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011814
11815 // Add to the global counters.
Mike Ma561a8d92018-03-20 18:24:05 -070011816 mNetworkByteActivityCounters[NETWORK_BT_RX_DATA].addCountLocked(rxBytes);
11817 mNetworkByteActivityCounters[NETWORK_BT_TX_DATA].addCountLocked(txBytes);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011818
11819 // Add to the UID counters.
11820 final Uid u = getUidStatsLocked(mapUid(traffic.getUid()));
Mike Ma561a8d92018-03-20 18:24:05 -070011821 u.noteNetworkActivityLocked(NETWORK_BT_RX_DATA, rxBytes, 0);
11822 u.noteNetworkActivityLocked(NETWORK_BT_TX_DATA, txBytes, 0);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011823
11824 // Calculate the total traffic.
Mike Ma561a8d92018-03-20 18:24:05 -070011825 totalRxBytes += rxBytes;
11826 totalTxBytes += txBytes;
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011827 }
11828
Mike Ma561a8d92018-03-20 18:24:05 -070011829 if ((totalTxBytes != 0 || totalRxBytes != 0) && (leftOverRxTimeMs != 0
11830 || leftOverTxTimeMs != 0)) {
11831 for (int i = 0; i < numUids; i++) {
11832 final UidTraffic traffic = uidTraffic[i];
11833 final int uid = traffic.getUid();
11834 final long rxBytes =
11835 traffic.getRxBytes() - mLastBluetoothActivityInfo.uidRxBytes.get(uid);
11836 final long txBytes =
11837 traffic.getTxBytes() - mLastBluetoothActivityInfo.uidTxBytes.get(uid);
Adam Lesinski50e47602015-12-04 17:04:54 -080011838
Mike Ma561a8d92018-03-20 18:24:05 -070011839 final Uid u = getUidStatsLocked(mapUid(uid));
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011840 final ControllerActivityCounterImpl counter =
11841 u.getOrCreateBluetoothControllerActivityLocked();
11842
Mike Ma561a8d92018-03-20 18:24:05 -070011843 if (totalRxBytes > 0 && rxBytes > 0) {
11844 final long timeRxMs = (leftOverRxTimeMs * rxBytes) / totalRxBytes;
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011845 if (DEBUG_ENERGY) {
Mike Ma561a8d92018-03-20 18:24:05 -070011846 Slog.d(TAG, "UID=" + uid + " rx_bytes=" + rxBytes + " rx_time=" + timeRxMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011847 }
11848 counter.getRxTimeCounter().addCountLocked(timeRxMs);
11849 leftOverRxTimeMs -= timeRxMs;
11850 }
11851
Mike Ma561a8d92018-03-20 18:24:05 -070011852 if (totalTxBytes > 0 && txBytes > 0) {
11853 final long timeTxMs = (leftOverTxTimeMs * txBytes) / totalTxBytes;
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011854 if (DEBUG_ENERGY) {
Mike Ma561a8d92018-03-20 18:24:05 -070011855 Slog.d(TAG, "UID=" + uid + " tx_bytes=" + txBytes + " tx_time=" + timeTxMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011856 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011857 counter.getTxTimeCounters()[0].addCountLocked(timeTxMs);
11858 leftOverTxTimeMs -= timeTxMs;
11859 }
Adam Lesinski50e47602015-12-04 17:04:54 -080011860 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011861 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011862
Chenjie Yu89083392018-01-11 14:53:31 -080011863 mBluetoothActivity.getRxTimeCounter().addCountLocked(rxTimeMs);
11864 mBluetoothActivity.getTxTimeCounters()[0].addCountLocked(txTimeMs);
11865 mBluetoothActivity.getIdleTimeCounter().addCountLocked(idleTimeMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011866
11867 // POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11868 final double opVolt = mPowerProfile.getAveragePower(
11869 PowerProfile.POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11870 if (opVolt != 0) {
11871 // We store the power drain as mAms.
11872 mBluetoothActivity.getPowerCounter().addCountLocked(
Mike Ma561a8d92018-03-20 18:24:05 -070011873 (long) ((info.getControllerEnergyUsed() - mLastBluetoothActivityInfo.energy)
11874 / opVolt));
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011875 }
Mike Ma561a8d92018-03-20 18:24:05 -070011876 mLastBluetoothActivityInfo.set(info);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011877 }
11878
11879 /**
Bookatz0b8a0502017-09-13 11:51:52 -070011880 * Read and record Resource Power Manager (RPM) state and voter times.
11881 * If RPM stats were fetched more recently than RPM_STATS_UPDATE_FREQ_MS ago, uses the old data
11882 * instead of fetching it anew.
Bookatz50df7112017-08-04 14:53:26 -070011883 */
11884 public void updateRpmStatsLocked() {
11885 if (mPlatformIdleStateCallback == null) return;
Bookatz0b8a0502017-09-13 11:51:52 -070011886 long now = SystemClock.elapsedRealtime();
11887 if (now - mLastRpmStatsUpdateTimeMs >= RPM_STATS_UPDATE_FREQ_MS) {
11888 mPlatformIdleStateCallback.fillLowPowerStats(mTmpRpmStats);
11889 mLastRpmStatsUpdateTimeMs = now;
11890 }
Bookatz50df7112017-08-04 14:53:26 -070011891
11892 for (Map.Entry<String, RpmStats.PowerStatePlatformSleepState> pstate
11893 : mTmpRpmStats.mPlatformLowPowerStats.entrySet()) {
11894
11895 // Update values for this platform state.
11896 final String pName = pstate.getKey();
11897 final long pTimeUs = pstate.getValue().mTimeMs * 1000;
11898 final int pCount = pstate.getValue().mCount;
11899 getRpmTimerLocked(pName).update(pTimeUs, pCount);
Bookatz82b341172017-09-07 19:06:08 -070011900 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11901 getScreenOffRpmTimerLocked(pName).update(pTimeUs, pCount);
11902 }
Bookatz50df7112017-08-04 14:53:26 -070011903
11904 // Update values for each voter of this platform state.
11905 for (Map.Entry<String, RpmStats.PowerStateElement> voter
11906 : pstate.getValue().mVoters.entrySet()) {
11907 final String vName = pName + "." + voter.getKey();
11908 final long vTimeUs = voter.getValue().mTimeMs * 1000;
11909 final int vCount = voter.getValue().mCount;
11910 getRpmTimerLocked(vName).update(vTimeUs, vCount);
Bookatz82b341172017-09-07 19:06:08 -070011911 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11912 getScreenOffRpmTimerLocked(vName).update(vTimeUs, vCount);
11913 }
Bookatz50df7112017-08-04 14:53:26 -070011914 }
11915 }
11916
11917 for (Map.Entry<String, RpmStats.PowerStateSubsystem> subsys
11918 : mTmpRpmStats.mSubsystemLowPowerStats.entrySet()) {
11919
11920 final String subsysName = subsys.getKey();
11921 for (Map.Entry<String, RpmStats.PowerStateElement> sstate
11922 : subsys.getValue().mStates.entrySet()) {
11923 final String name = subsysName + "." + sstate.getKey();
11924 final long timeUs = sstate.getValue().mTimeMs * 1000;
11925 final int count = sstate.getValue().mCount;
11926 getRpmTimerLocked(name).update(timeUs, count);
Bookatz82b341172017-09-07 19:06:08 -070011927 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11928 getScreenOffRpmTimerLocked(name).update(timeUs, count);
11929 }
Bookatz50df7112017-08-04 14:53:26 -070011930 }
11931 }
11932 }
11933
11934 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011935 * Read and distribute kernel wake lock use across apps.
11936 */
11937 public void updateKernelWakelocksLocked() {
11938 final KernelWakelockStats wakelockStats = mKernelWakelockReader.readKernelWakelockStats(
11939 mTmpWakelockStats);
11940 if (wakelockStats == null) {
11941 // Not crashing might make board bringup easier.
11942 Slog.w(TAG, "Couldn't get kernel wake lock stats");
11943 return;
11944 }
11945
11946 for (Map.Entry<String, KernelWakelockStats.Entry> ent : wakelockStats.entrySet()) {
11947 String name = ent.getKey();
11948 KernelWakelockStats.Entry kws = ent.getValue();
11949
11950 SamplingTimer kwlt = mKernelWakelockStats.get(name);
11951 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -070011952 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011953 mKernelWakelockStats.put(name, kwlt);
11954 }
Adam Lesinskid84ad302016-05-17 18:31:02 -070011955
Adam Lesinski757c6ea2016-04-21 09:55:41 -070011956 kwlt.update(kws.mTotalTime, kws.mCount);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011957 kwlt.setUpdateVersion(kws.mVersion);
11958 }
11959
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011960 int numWakelocksSetStale = 0;
Adam Lesinskid84ad302016-05-17 18:31:02 -070011961 // Set timers to stale if they didn't appear in /d/wakeup_sources (or /proc/wakelocks)
11962 // this time.
11963 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
11964 SamplingTimer st = ent.getValue();
11965 if (st.getUpdateVersion() != wakelockStats.kernelWakelockVersion) {
11966 st.endSample();
11967 numWakelocksSetStale++;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011968 }
11969 }
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011970
Adam Lesinskid84ad302016-05-17 18:31:02 -070011971 // Record whether we've seen a non-zero time (for debugging b/22716723).
11972 if (wakelockStats.isEmpty()) {
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011973 Slog.wtf(TAG, "All kernel wakelocks had time of zero");
11974 }
11975
11976 if (numWakelocksSetStale == mKernelWakelockStats.size()) {
11977 Slog.wtf(TAG, "All kernel wakelocks were set stale. new version=" +
11978 wakelockStats.kernelWakelockVersion);
11979 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011980 }
11981
Adam Lesinski72478f02015-06-17 15:39:43 -070011982 // We use an anonymous class to access these variables,
11983 // so they can't live on the stack or they'd have to be
11984 // final MutableLong objects (more allocations).
11985 // Used in updateCpuTimeLocked().
11986 long mTempTotalCpuUserTimeUs;
11987 long mTempTotalCpuSystemTimeUs;
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011988 long[][] mWakeLockAllocationsUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070011989
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011990 /**
James Carr3a226052016-07-01 14:49:52 -070011991 * Reads the newest memory stats from the kernel.
11992 */
11993 public void updateKernelMemoryBandwidthLocked() {
11994 mKernelMemoryBandwidthStats.updateStats();
11995 LongSparseLongArray bandwidthEntries = mKernelMemoryBandwidthStats.getBandwidthEntries();
11996 final int bandwidthEntryCount = bandwidthEntries.size();
11997 int index;
11998 for (int i = 0; i < bandwidthEntryCount; i++) {
11999 SamplingTimer timer;
12000 if ((index = mKernelMemoryStats.indexOfKey(bandwidthEntries.keyAt(i))) >= 0) {
12001 timer = mKernelMemoryStats.valueAt(index);
12002 } else {
12003 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
12004 mKernelMemoryStats.put(bandwidthEntries.keyAt(i), timer);
12005 }
12006 timer.update(bandwidthEntries.valueAt(i), 1);
12007 if (DEBUG_MEMORY) {
12008 Slog.d(TAG, String.format("Added entry %d and updated timer to: "
12009 + "mUnpluggedReportedTotalTime %d size %d", bandwidthEntries.keyAt(i),
12010 mKernelMemoryStats.get(
12011 bandwidthEntries.keyAt(i)).mUnpluggedReportedTotalTime,
12012 mKernelMemoryStats.size()));
12013 }
12014 }
12015 }
12016
Sudheer Shankac57729a2018-02-09 15:44:42 -080012017 public boolean isOnBatteryLocked() {
12018 return mOnBatteryTimeBase.isRunning();
12019 }
12020
12021 public boolean isOnBatteryScreenOffLocked() {
12022 return mOnBatteryScreenOffTimeBase.isRunning();
12023 }
12024
James Carr3a226052016-07-01 14:49:52 -070012025 /**
Adam Lesinski72478f02015-06-17 15:39:43 -070012026 * Read and distribute CPU usage across apps. If their are partial wakelocks being held
12027 * and we are on battery with screen off, we give more of the cpu time to those apps holding
12028 * wakelocks. If the screen is on, we just assign the actual cpu time an app used.
Sudheer Shankac57729a2018-02-09 15:44:42 -080012029 * It's possible this will be invoked after the internal battery/screen states are updated, so
12030 * passing the appropriate battery/screen states to try attribute the cpu times to correct
12031 * buckets.
Adam Lesinski06af1fa2015-05-05 17:35:35 -070012032 */
Andreas Gampe3f24e692018-02-05 13:24:28 -080012033 @GuardedBy("this")
Sudheer Shankac57729a2018-02-09 15:44:42 -080012034 public void updateCpuTimeLocked(boolean onBattery, boolean onBatteryScreenOff) {
Adam Lesinski52290c9c2015-09-21 16:54:52 -070012035 if (mPowerProfile == null) {
12036 return;
12037 }
12038
Adam Lesinski72478f02015-06-17 15:39:43 -070012039 if (DEBUG_ENERGY_CPU) {
12040 Slog.d(TAG, "!Cpu updating!");
12041 }
12042
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012043 if (mCpuFreqs == null) {
12044 mCpuFreqs = mKernelUidCpuFreqTimeReader.readFreqs(mPowerProfile);
12045 }
12046
Sudheer Shanka38383232017-07-25 09:55:03 -070012047 // Calculate the wakelocks we have to distribute amongst. The system is excluded as it is
12048 // usually holding the wakelock on behalf of an app.
12049 // And Only distribute cpu power to wakelocks if the screen is off and we're on battery.
12050 ArrayList<StopwatchTimer> partialTimersToConsider = null;
Sudheer Shankac57729a2018-02-09 15:44:42 -080012051 if (onBatteryScreenOff) {
Sudheer Shanka38383232017-07-25 09:55:03 -070012052 partialTimersToConsider = new ArrayList<>();
12053 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070012054 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070012055 // Since the collection and blaming of wakelocks can be scheduled to run after
12056 // some delay, the mPartialTimers list may have new entries. We can't blame
12057 // the newly added timer for past cpu time, so we only consider timers that
12058 // were present for one round of collection. Once a timer has gone through
12059 // a round of collection, its mInList field is set to true.
Adam Lesinski72478f02015-06-17 15:39:43 -070012060 if (timer.mInList && timer.mUid != null && timer.mUid.mUid != Process.SYSTEM_UID) {
Sudheer Shanka38383232017-07-25 09:55:03 -070012061 partialTimersToConsider.add(timer);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070012062 }
Adam Lesinski72478f02015-06-17 15:39:43 -070012063 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070012064 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012065 markPartialTimersAsEligible();
Adam Lesinski72478f02015-06-17 15:39:43 -070012066
Sudheer Shanka38383232017-07-25 09:55:03 -070012067 // When the battery is not on, we don't attribute the cpu times to any timers but we still
12068 // need to take the snapshots.
Sudheer Shankac57729a2018-02-09 15:44:42 -080012069 if (!onBattery) {
Sudheer Shanka38383232017-07-25 09:55:03 -070012070 mKernelUidCpuTimeReader.readDelta(null);
12071 mKernelUidCpuFreqTimeReader.readDelta(null);
Mike Ma234d1822018-03-13 18:53:21 -070012072 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080012073 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
12074 mKernelUidCpuActiveTimeReader.readDelta(null);
12075 mKernelUidCpuClusterTimeReader.readDelta(null);
Mike Ma234d1822018-03-13 18:53:21 -070012076 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080012077 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012078 for (int cluster = mKernelCpuSpeedReaders.length - 1; cluster >= 0; --cluster) {
12079 mKernelCpuSpeedReaders[cluster].readDelta();
12080 }
12081 return;
12082 }
Adam Lesinski72478f02015-06-17 15:39:43 -070012083
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070012084 mUserInfoProvider.refreshUserIds();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012085 final SparseLongArray updatedUids = mKernelUidCpuFreqTimeReader.perClusterTimesAvailable()
12086 ? null : new SparseLongArray();
Sudheer Shankac57729a2018-02-09 15:44:42 -080012087 readKernelUidCpuTimesLocked(partialTimersToConsider, updatedUids, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012088 // updatedUids=null means /proc/uid_time_in_state provides snapshots of per-cluster cpu
12089 // freqs, so no need to approximate these values.
12090 if (updatedUids != null) {
Sudheer Shankac57729a2018-02-09 15:44:42 -080012091 updateClusterSpeedTimes(updatedUids, onBattery);
Sudheer Shanka671985f2017-05-19 11:33:42 -070012092 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080012093 readKernelUidCpuFreqTimesLocked(partialTimersToConsider, onBattery, onBatteryScreenOff);
Mike Ma234d1822018-03-13 18:53:21 -070012094 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080012095 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
Sudheer Shankac57729a2018-02-09 15:44:42 -080012096 readKernelUidCpuActiveTimesLocked(onBattery);
12097 readKernelUidCpuClusterTimesLocked(onBattery);
Mike Ma234d1822018-03-13 18:53:21 -070012098 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080012099 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012100 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012101
Sudheer Shanka38383232017-07-25 09:55:03 -070012102 /**
12103 * Mark the current partial timers as gone through a collection so that they will be
12104 * considered in the next cpu times distribution to wakelock holders.
12105 */
12106 @VisibleForTesting
12107 public void markPartialTimersAsEligible() {
12108 if (ArrayUtils.referenceEquals(mPartialTimers, mLastPartialTimers)) {
12109 // No difference, so each timer is now considered for the next collection.
12110 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
12111 mPartialTimers.get(i).mInList = true;
12112 }
12113 } else {
12114 // The lists are different, meaning we added (or removed a timer) since the last
12115 // collection.
12116 for (int i = mLastPartialTimers.size() - 1; i >= 0; --i) {
12117 mLastPartialTimers.get(i).mInList = false;
12118 }
12119 mLastPartialTimers.clear();
Adam Lesinski72478f02015-06-17 15:39:43 -070012120
Sudheer Shanka38383232017-07-25 09:55:03 -070012121 // Mark the current timers as gone through a collection.
12122 final int numPartialTimers = mPartialTimers.size();
12123 for (int i = 0; i < numPartialTimers; ++i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070012124 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070012125 timer.mInList = true;
12126 mLastPartialTimers.add(timer);
Adam Lesinski72478f02015-06-17 15:39:43 -070012127 }
12128 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012129 }
Adam Lesinski72478f02015-06-17 15:39:43 -070012130
Sudheer Shanka38383232017-07-25 09:55:03 -070012131 /**
12132 * Take snapshot of cpu times (aggregated over all uids) at different frequencies and
12133 * calculate cpu times spent by each uid at different frequencies.
12134 *
12135 * @param updatedUids The uids for which times spent at different frequencies are calculated.
12136 */
12137 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012138 public void updateClusterSpeedTimes(@NonNull SparseLongArray updatedUids, boolean onBattery) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070012139 long totalCpuClustersTimeMs = 0;
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012140 // Read the time spent for each cluster at various cpu frequencies.
Sudheer Shankaaf857412017-07-21 00:14:24 -070012141 final long[][] clusterSpeedTimesMs = new long[mKernelCpuSpeedReaders.length][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012142 for (int cluster = 0; cluster < mKernelCpuSpeedReaders.length; cluster++) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070012143 clusterSpeedTimesMs[cluster] = mKernelCpuSpeedReaders[cluster].readDelta();
12144 if (clusterSpeedTimesMs[cluster] != null) {
12145 for (int speed = clusterSpeedTimesMs[cluster].length - 1; speed >= 0; --speed) {
12146 totalCpuClustersTimeMs += clusterSpeedTimesMs[cluster][speed];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012147 }
12148 }
12149 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070012150 if (totalCpuClustersTimeMs != 0) {
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012151 // We have cpu times per freq aggregated over all uids but we need the times per uid.
12152 // So, we distribute total time spent by an uid to different cpu freqs based on the
12153 // amount of time cpu was running at that freq.
12154 final int updatedUidsCount = updatedUids.size();
12155 for (int i = 0; i < updatedUidsCount; ++i) {
12156 final Uid u = getUidStatsLocked(updatedUids.keyAt(i));
Sudheer Shankaaf857412017-07-21 00:14:24 -070012157 final long appCpuTimeUs = updatedUids.valueAt(i);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012158 // Add the cpu speeds to this UID.
12159 final int numClusters = mPowerProfile.getNumCpuClusters();
Sudheer Shanka38383232017-07-25 09:55:03 -070012160 if (u.mCpuClusterSpeedTimesUs == null ||
12161 u.mCpuClusterSpeedTimesUs.length != numClusters) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070012162 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012163 }
12164
Sudheer Shankaaf857412017-07-21 00:14:24 -070012165 for (int cluster = 0; cluster < clusterSpeedTimesMs.length; cluster++) {
12166 final int speedsInCluster = clusterSpeedTimesMs[cluster].length;
12167 if (u.mCpuClusterSpeedTimesUs[cluster] == null || speedsInCluster !=
12168 u.mCpuClusterSpeedTimesUs[cluster].length) {
12169 u.mCpuClusterSpeedTimesUs[cluster]
12170 = new LongSamplingCounter[speedsInCluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012171 }
12172
Sudheer Shankaaf857412017-07-21 00:14:24 -070012173 final LongSamplingCounter[] cpuSpeeds = u.mCpuClusterSpeedTimesUs[cluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012174 for (int speed = 0; speed < speedsInCluster; speed++) {
12175 if (cpuSpeeds[speed] == null) {
12176 cpuSpeeds[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
12177 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070012178 cpuSpeeds[speed].addCountLocked(appCpuTimeUs
12179 * clusterSpeedTimesMs[cluster][speed]
Sudheer Shankac57729a2018-02-09 15:44:42 -080012180 / totalCpuClustersTimeMs, onBattery);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012181 }
12182 }
12183 }
12184 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012185 }
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012186
Sudheer Shanka38383232017-07-25 09:55:03 -070012187 /**
12188 * Take a snapshot of the cpu times spent by each uid and update the corresponding counters.
12189 * If {@param partialTimers} is not null and empty, then we assign a portion of cpu times to
12190 * wakelock holders.
12191 *
12192 * @param partialTimers The wakelock holders among which the cpu times will be distributed.
12193 * @param updatedUids If not null, then the uids found in the snapshot will be added to this.
12194 */
12195 @VisibleForTesting
12196 public void readKernelUidCpuTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers,
Sudheer Shankac57729a2018-02-09 15:44:42 -080012197 @Nullable SparseLongArray updatedUids, boolean onBattery) {
Sudheer Shanka38383232017-07-25 09:55:03 -070012198 mTempTotalCpuUserTimeUs = mTempTotalCpuSystemTimeUs = 0;
12199 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
12200 final long startTimeMs = mClocks.uptimeMillis();
Adam Lesinski72478f02015-06-17 15:39:43 -070012201
Sudheer Shanka38383232017-07-25 09:55:03 -070012202 mKernelUidCpuTimeReader.readDelta((uid, userTimeUs, systemTimeUs) -> {
12203 uid = mapUid(uid);
12204 if (Process.isIsolated(uid)) {
12205 // This could happen if the isolated uid mapping was removed before that process
12206 // was actually killed.
12207 mKernelUidCpuTimeReader.removeUid(uid);
12208 Slog.d(TAG, "Got readings for an isolated uid with no mapping: " + uid);
12209 return;
12210 }
12211 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12212 Slog.d(TAG, "Got readings for an invalid user's uid " + uid);
12213 mKernelUidCpuTimeReader.removeUid(uid);
12214 return;
12215 }
12216 final Uid u = getUidStatsLocked(uid);
12217
12218 // Accumulate the total system and user time.
12219 mTempTotalCpuUserTimeUs += userTimeUs;
12220 mTempTotalCpuSystemTimeUs += systemTimeUs;
12221
12222 StringBuilder sb = null;
12223 if (DEBUG_ENERGY_CPU) {
12224 sb = new StringBuilder();
12225 sb.append(" got time for uid=").append(u.mUid).append(": u=");
12226 TimeUtils.formatDuration(userTimeUs / 1000, sb);
12227 sb.append(" s=");
12228 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
12229 sb.append("\n");
12230 }
12231
12232 if (numWakelocks > 0) {
12233 // We have wakelocks being held, so only give a portion of the
12234 // time to the process. The rest will be distributed among wakelock
12235 // holders.
12236 userTimeUs = (userTimeUs * WAKE_LOCK_WEIGHT) / 100;
12237 systemTimeUs = (systemTimeUs * WAKE_LOCK_WEIGHT) / 100;
12238 }
12239
12240 if (sb != null) {
12241 sb.append(" adding to uid=").append(u.mUid).append(": u=");
12242 TimeUtils.formatDuration(userTimeUs / 1000, sb);
12243 sb.append(" s=");
12244 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
12245 Slog.d(TAG, sb.toString());
12246 }
12247
Sudheer Shankac57729a2018-02-09 15:44:42 -080012248 u.mUserCpuTime.addCountLocked(userTimeUs, onBattery);
12249 u.mSystemCpuTime.addCountLocked(systemTimeUs, onBattery);
Sudheer Shanka38383232017-07-25 09:55:03 -070012250 if (updatedUids != null) {
12251 updatedUids.put(u.getUid(), userTimeUs + systemTimeUs);
12252 }
12253 });
12254
12255 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12256 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12257 Slog.d(TAG, "Reading cpu stats took " + elapsedTimeMs + "ms");
12258 }
12259
12260 if (numWakelocks > 0) {
12261 // Distribute a portion of the total cpu time to wakelock holders.
12262 mTempTotalCpuUserTimeUs = (mTempTotalCpuUserTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
12263 mTempTotalCpuSystemTimeUs =
12264 (mTempTotalCpuSystemTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
12265
12266 for (int i = 0; i < numWakelocks; ++i) {
12267 final StopwatchTimer timer = partialTimers.get(i);
12268 final int userTimeUs = (int) (mTempTotalCpuUserTimeUs / (numWakelocks - i));
12269 final int systemTimeUs = (int) (mTempTotalCpuSystemTimeUs / (numWakelocks - i));
12270
12271 if (DEBUG_ENERGY_CPU) {
12272 final StringBuilder sb = new StringBuilder();
12273 sb.append(" Distributing wakelock uid=").append(timer.mUid.mUid)
12274 .append(": u=");
12275 TimeUtils.formatDuration(userTimeUs / 1000, sb);
12276 sb.append(" s=");
12277 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
12278 Slog.d(TAG, sb.toString());
12279 }
12280
Sudheer Shankac57729a2018-02-09 15:44:42 -080012281 timer.mUid.mUserCpuTime.addCountLocked(userTimeUs, onBattery);
12282 timer.mUid.mSystemCpuTime.addCountLocked(systemTimeUs, onBattery);
Sudheer Shanka38383232017-07-25 09:55:03 -070012283 if (updatedUids != null) {
12284 final int uid = timer.mUid.getUid();
12285 updatedUids.put(uid, updatedUids.get(uid, 0) + userTimeUs + systemTimeUs);
12286 }
12287
12288 final Uid.Proc proc = timer.mUid.getProcessStatsLocked("*wakelock*");
Sudheer Shankac57729a2018-02-09 15:44:42 -080012289 proc.addCpuTimeLocked(userTimeUs / 1000, systemTimeUs / 1000, onBattery);
Sudheer Shanka38383232017-07-25 09:55:03 -070012290
12291 mTempTotalCpuUserTimeUs -= userTimeUs;
12292 mTempTotalCpuSystemTimeUs -= systemTimeUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070012293 }
12294 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070012295 }
12296
Sudheer Shanka38383232017-07-25 09:55:03 -070012297 /**
12298 * Take a snapshot of the cpu times spent by each uid in each freq and update the
12299 * corresponding counters.
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012300 *
12301 * @param partialTimers The wakelock holders among which the cpu freq times will be distributed.
Sudheer Shanka38383232017-07-25 09:55:03 -070012302 */
12303 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012304 public void readKernelUidCpuFreqTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers,
12305 boolean onBattery, boolean onBatteryScreenOff) {
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012306 final boolean perClusterTimesAvailable =
12307 mKernelUidCpuFreqTimeReader.perClusterTimesAvailable();
12308 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
12309 final int numClusters = mPowerProfile.getNumCpuClusters();
12310 mWakeLockAllocationsUs = null;
Sudheer Shankaac5b88f2017-12-11 15:36:35 -080012311 final long startTimeMs = mClocks.uptimeMillis();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012312 mKernelUidCpuFreqTimeReader.readDelta((uid, cpuFreqTimeMs) -> {
12313 uid = mapUid(uid);
12314 if (Process.isIsolated(uid)) {
12315 mKernelUidCpuFreqTimeReader.removeUid(uid);
12316 Slog.d(TAG, "Got freq readings for an isolated uid with no mapping: " + uid);
12317 return;
Sudheer Shanka38383232017-07-25 09:55:03 -070012318 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012319 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12320 Slog.d(TAG, "Got freq readings for an invalid user's uid " + uid);
12321 mKernelUidCpuFreqTimeReader.removeUid(uid);
12322 return;
12323 }
12324 final Uid u = getUidStatsLocked(uid);
12325 if (u.mCpuFreqTimeMs == null || u.mCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
12326 u.mCpuFreqTimeMs = new LongSamplingCounterArray(mOnBatteryTimeBase);
12327 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080012328 u.mCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012329 if (u.mScreenOffCpuFreqTimeMs == null ||
12330 u.mScreenOffCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
12331 u.mScreenOffCpuFreqTimeMs = new LongSamplingCounterArray(
12332 mOnBatteryScreenOffTimeBase);
12333 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080012334 u.mScreenOffCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs, onBatteryScreenOff);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012335
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012336 if (perClusterTimesAvailable) {
12337 if (u.mCpuClusterSpeedTimesUs == null ||
12338 u.mCpuClusterSpeedTimesUs.length != numClusters) {
12339 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070012340 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012341 if (numWakelocks > 0 && mWakeLockAllocationsUs == null) {
12342 mWakeLockAllocationsUs = new long[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070012343 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012344
12345 int freqIndex = 0;
12346 for (int cluster = 0; cluster < numClusters; ++cluster) {
12347 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
12348 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
12349 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
12350 u.mCpuClusterSpeedTimesUs[cluster]
12351 = new LongSamplingCounter[speedsInCluster];
12352 }
12353 if (numWakelocks > 0 && mWakeLockAllocationsUs[cluster] == null) {
12354 mWakeLockAllocationsUs[cluster] = new long[speedsInCluster];
12355 }
12356 final LongSamplingCounter[] cpuTimesUs = u.mCpuClusterSpeedTimesUs[cluster];
12357 for (int speed = 0; speed < speedsInCluster; ++speed) {
12358 if (cpuTimesUs[speed] == null) {
12359 cpuTimesUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
12360 }
12361 final long appAllocationUs;
12362 if (mWakeLockAllocationsUs != null) {
12363 appAllocationUs =
12364 (cpuFreqTimeMs[freqIndex] * 1000 * WAKE_LOCK_WEIGHT) / 100;
12365 mWakeLockAllocationsUs[cluster][speed] +=
12366 (cpuFreqTimeMs[freqIndex] * 1000 - appAllocationUs);
12367 } else {
12368 appAllocationUs = cpuFreqTimeMs[freqIndex] * 1000;
12369 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080012370 cpuTimesUs[speed].addCountLocked(appAllocationUs, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012371 freqIndex++;
12372 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012373 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012374 }
12375 });
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012376
Sudheer Shankaac5b88f2017-12-11 15:36:35 -080012377 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12378 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12379 Slog.d(TAG, "Reading cpu freq times took " + elapsedTimeMs + "ms");
12380 }
12381
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012382 if (mWakeLockAllocationsUs != null) {
12383 for (int i = 0; i < numWakelocks; ++i) {
12384 final Uid u = partialTimers.get(i).mUid;
12385 if (u.mCpuClusterSpeedTimesUs == null ||
12386 u.mCpuClusterSpeedTimesUs.length != numClusters) {
12387 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
12388 }
12389
12390 for (int cluster = 0; cluster < numClusters; ++cluster) {
12391 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
12392 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
12393 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
12394 u.mCpuClusterSpeedTimesUs[cluster]
12395 = new LongSamplingCounter[speedsInCluster];
12396 }
12397 final LongSamplingCounter[] cpuTimeUs = u.mCpuClusterSpeedTimesUs[cluster];
12398 for (int speed = 0; speed < speedsInCluster; ++speed) {
12399 if (cpuTimeUs[speed] == null) {
12400 cpuTimeUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
12401 }
12402 final long allocationUs =
12403 mWakeLockAllocationsUs[cluster][speed] / (numWakelocks - i);
Sudheer Shankac57729a2018-02-09 15:44:42 -080012404 cpuTimeUs[speed].addCountLocked(allocationUs, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012405 mWakeLockAllocationsUs[cluster][speed] -= allocationUs;
12406 }
12407 }
12408 }
12409 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012410 }
12411
Mike Ma3d422c32017-10-25 11:08:57 -070012412 /**
12413 * Take a snapshot of the cpu active times spent by each uid and update the corresponding
12414 * counters.
12415 */
12416 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012417 public void readKernelUidCpuActiveTimesLocked(boolean onBattery) {
Mike Ma3d422c32017-10-25 11:08:57 -070012418 final long startTimeMs = mClocks.uptimeMillis();
Mike Ma2ab01442018-02-13 14:22:47 -080012419 mKernelUidCpuActiveTimeReader.readDelta((uid, cpuActiveTimesMs) -> {
Mike Ma3d422c32017-10-25 11:08:57 -070012420 uid = mapUid(uid);
12421 if (Process.isIsolated(uid)) {
12422 mKernelUidCpuActiveTimeReader.removeUid(uid);
12423 Slog.w(TAG, "Got active times for an isolated uid with no mapping: " + uid);
12424 return;
12425 }
12426 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12427 Slog.w(TAG, "Got active times for an invalid user's uid " + uid);
12428 mKernelUidCpuActiveTimeReader.removeUid(uid);
12429 return;
12430 }
12431 final Uid u = getUidStatsLocked(uid);
Mike Ma2ab01442018-02-13 14:22:47 -080012432 u.mCpuActiveTimeMs.addCountLocked(cpuActiveTimesMs, onBattery);
Mike Ma3d422c32017-10-25 11:08:57 -070012433 });
12434
12435 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12436 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12437 Slog.d(TAG, "Reading cpu active times took " + elapsedTimeMs + "ms");
12438 }
12439 }
12440
12441 /**
12442 * Take a snapshot of the cpu cluster times spent by each uid and update the corresponding
12443 * counters.
12444 */
12445 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012446 public void readKernelUidCpuClusterTimesLocked(boolean onBattery) {
Mike Ma3d422c32017-10-25 11:08:57 -070012447 final long startTimeMs = mClocks.uptimeMillis();
Mike Ma2ab01442018-02-13 14:22:47 -080012448 mKernelUidCpuClusterTimeReader.readDelta((uid, cpuClusterTimesMs) -> {
Mike Ma3d422c32017-10-25 11:08:57 -070012449 uid = mapUid(uid);
12450 if (Process.isIsolated(uid)) {
12451 mKernelUidCpuClusterTimeReader.removeUid(uid);
12452 Slog.w(TAG, "Got cluster times for an isolated uid with no mapping: " + uid);
12453 return;
12454 }
12455 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12456 Slog.w(TAG, "Got cluster times for an invalid user's uid " + uid);
12457 mKernelUidCpuClusterTimeReader.removeUid(uid);
12458 return;
12459 }
12460 final Uid u = getUidStatsLocked(uid);
Mike Ma2ab01442018-02-13 14:22:47 -080012461 u.mCpuClusterTimesMs.addCountLocked(cpuClusterTimesMs, onBattery);
Mike Ma3d422c32017-10-25 11:08:57 -070012462 });
12463
12464 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12465 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12466 Slog.d(TAG, "Reading cpu cluster times took " + elapsedTimeMs + "ms");
12467 }
12468 }
12469
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012470 boolean setChargingLocked(boolean charging) {
12471 if (mCharging != charging) {
12472 mCharging = charging;
12473 if (charging) {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012474 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012475 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012476 mHistoryCur.states2 &= ~HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012477 }
12478 mHandler.sendEmptyMessage(MSG_REPORT_CHARGING);
12479 return true;
12480 }
12481 return false;
12482 }
12483
Andreas Gampe3f24e692018-02-05 13:24:28 -080012484 @GuardedBy("this")
Mike Mac2f518a2017-09-19 16:06:03 -070012485 protected void setOnBatteryLocked(final long mSecRealtime, final long mSecUptime,
12486 final boolean onBattery, final int oldStatus, final int level, final int chargeUAh) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012487 boolean doWrite = false;
12488 Message m = mHandler.obtainMessage(MSG_REPORT_POWER_CHANGE);
12489 m.arg1 = onBattery ? 1 : 0;
12490 mHandler.sendMessage(m);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012491
Dianne Hackborn40c87252014-03-19 16:55:40 -070012492 final long uptime = mSecUptime * 1000;
12493 final long realtime = mSecRealtime * 1000;
Mike Mac2f518a2017-09-19 16:06:03 -070012494 final int screenState = mScreenState;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012495 if (onBattery) {
12496 // We will reset our status if we are unplugging after the
12497 // battery was last full, or the level is at 100, or
12498 // we have gone through a significant charge (from a very low
12499 // level to a now very high level).
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080012500 boolean reset = false;
Dianne Hackborn9a755432014-05-15 17:05:22 -070012501 if (!mNoAutoReset && (oldStatus == BatteryManager.BATTERY_STATUS_FULL
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012502 || level >= 90
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070012503 || (mDischargeCurrentLevel < 20 && level >= 80)
12504 || (getHighDischargeAmountSinceCharge() >= 200
12505 && mHistoryBuffer.dataSize() >= MAX_HISTORY_BUFFER))) {
Dianne Hackborn73d6a822014-09-29 10:52:47 -070012506 Slog.i(TAG, "Resetting battery stats: level=" + level + " status=" + oldStatus
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070012507 + " dischargeLevel=" + mDischargeCurrentLevel
Dianne Hackborn73d6a822014-09-29 10:52:47 -070012508 + " lowAmount=" + getLowDischargeAmountSinceCharge()
12509 + " highAmount=" + getHighDischargeAmountSinceCharge());
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012510 // Before we write, collect a snapshot of the final aggregated
12511 // stats to be reported in the next checkin. Only do this if we have
12512 // a sufficient amount of data to make it interesting.
12513 if (getLowDischargeAmountSinceCharge() >= 20) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080012514 final long startTime = SystemClock.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012515 final Parcel parcel = Parcel.obtain();
12516 writeSummaryToParcel(parcel, true);
Dianne Hackborne17b4452018-01-10 13:15:40 -080012517 final long initialTime = SystemClock.uptimeMillis() - startTime;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012518 BackgroundThread.getHandler().post(new Runnable() {
12519 @Override public void run() {
12520 synchronized (mCheckinFile) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080012521 final long startTime2 = SystemClock.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012522 FileOutputStream stream = null;
12523 try {
12524 stream = mCheckinFile.startWrite();
12525 stream.write(parcel.marshall());
12526 stream.flush();
12527 FileUtils.sync(stream);
12528 stream.close();
12529 mCheckinFile.finishWrite(stream);
Dianne Hackborne17b4452018-01-10 13:15:40 -080012530 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
12531 "batterystats-checkin",
12532 initialTime + SystemClock.uptimeMillis() - startTime2);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012533 } catch (IOException e) {
12534 Slog.w("BatteryStats",
12535 "Error writing checkin battery statistics", e);
12536 mCheckinFile.failWrite(stream);
12537 } finally {
12538 parcel.recycle();
12539 }
12540 }
12541 }
12542 });
12543 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012544 doWrite = true;
12545 resetAllStatsLocked();
Ying Wai (Daniel) Fan442ab762017-01-31 22:00:10 -080012546 if (chargeUAh > 0 && level > 0) {
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012547 // Only use the reported coulomb charge value if it is supported and reported.
Ying Wai (Daniel) Fan9238b612017-01-18 15:50:19 -080012548 mEstimatedBatteryCapacity = (int) ((chargeUAh / 1000) / (level / 100.0));
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012549 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012550 mDischargeStartLevel = level;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080012551 reset = true;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012552 mDischargeStepTracker.init();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012553 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012554 if (mCharging) {
12555 setChargingLocked(false);
12556 }
12557 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080012558 mOnBattery = mOnBatteryInternal = true;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012559 mLastDischargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070012560 mMinDischargeStepLevel = level;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012561 mDischargeStepTracker.clearTime();
12562 mDailyDischargeStepTracker.clearTime();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012563 mInitStepMode = mCurStepMode;
12564 mModStepMode = 0;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012565 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012566 mHistoryCur.batteryLevel = (byte)level;
12567 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
12568 if (DEBUG_HISTORY) Slog.v(TAG, "Battery unplugged to: "
12569 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012570 if (reset) {
12571 mRecordingHistory = true;
12572 startRecordingHistory(mSecRealtime, mSecUptime, reset);
12573 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070012574 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012575 mDischargeCurrentLevel = mDischargeUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070012576 if (isScreenOn(screenState)) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012577 mDischargeScreenOnUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070012578 mDischargeScreenDozeUnplugLevel = 0;
12579 mDischargeScreenOffUnplugLevel = 0;
12580 } else if (isScreenDoze(screenState)) {
12581 mDischargeScreenOnUnplugLevel = 0;
12582 mDischargeScreenDozeUnplugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012583 mDischargeScreenOffUnplugLevel = 0;
12584 } else {
12585 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012586 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012587 mDischargeScreenOffUnplugLevel = level;
12588 }
12589 mDischargeAmountScreenOn = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012590 mDischargeAmountScreenDoze = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012591 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012592 updateTimeBasesLocked(true, screenState, uptime, realtime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012593 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012594 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080012595 mOnBattery = mOnBatteryInternal = false;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012596 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012597 mHistoryCur.batteryLevel = (byte)level;
12598 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
12599 if (DEBUG_HISTORY) Slog.v(TAG, "Battery plugged to: "
12600 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -070012601 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012602 mDischargeCurrentLevel = mDischargePlugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012603 if (level < mDischargeUnplugLevel) {
12604 mLowDischargeAmountSinceCharge += mDischargeUnplugLevel-level-1;
12605 mHighDischargeAmountSinceCharge += mDischargeUnplugLevel-level;
12606 }
Mike Mac2f518a2017-09-19 16:06:03 -070012607 updateDischargeScreenLevelsLocked(screenState, screenState);
12608 updateTimeBasesLocked(false, screenState, uptime, realtime);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012609 mChargeStepTracker.init();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012610 mLastChargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070012611 mMaxChargeStepLevel = level;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012612 mInitStepMode = mCurStepMode;
12613 mModStepMode = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012614 }
12615 if (doWrite || (mLastWriteTime + (60 * 1000)) < mSecRealtime) {
12616 if (mFile != null) {
12617 writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012618 }
12619 }
12620 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012621
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012622 private void startRecordingHistory(final long elapsedRealtimeMs, final long uptimeMs,
12623 boolean reset) {
12624 mRecordingHistory = true;
12625 mHistoryCur.currentTime = System.currentTimeMillis();
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012626 addHistoryBufferLocked(elapsedRealtimeMs,
Dianne Hackborn37de0982014-05-09 09:32:18 -070012627 reset ? HistoryItem.CMD_RESET : HistoryItem.CMD_CURRENT_TIME,
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012628 mHistoryCur);
12629 mHistoryCur.currentTime = 0;
12630 if (reset) {
12631 initActiveHistoryEventsLocked(elapsedRealtimeMs, uptimeMs);
12632 }
12633 }
12634
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012635 private void recordCurrentTimeChangeLocked(final long currentTime, final long elapsedRealtimeMs,
12636 final long uptimeMs) {
12637 if (mRecordingHistory) {
12638 mHistoryCur.currentTime = currentTime;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012639 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_CURRENT_TIME, mHistoryCur);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012640 mHistoryCur.currentTime = 0;
12641 }
12642 }
12643
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080012644 private void recordShutdownLocked(final long elapsedRealtimeMs, final long uptimeMs) {
12645 if (mRecordingHistory) {
12646 mHistoryCur.currentTime = System.currentTimeMillis();
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012647 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_SHUTDOWN, mHistoryCur);
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080012648 mHistoryCur.currentTime = 0;
12649 }
12650 }
12651
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012652 private void scheduleSyncExternalStatsLocked(String reason, int updateFlags) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012653 if (mExternalSync != null) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012654 mExternalSync.scheduleSync(reason, updateFlags);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070012655 }
12656 }
12657
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012658 // This should probably be exposed in the API, though it's not critical
Bookatz1a1b0462018-01-12 11:47:03 -080012659 public static final int BATTERY_PLUGGED_NONE = OsProtoEnums.BATTERY_PLUGGED_NONE; // = 0
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012660
Andreas Gampe3f24e692018-02-05 13:24:28 -080012661 @GuardedBy("this")
Bookatz8c6571b2017-10-24 15:04:41 -070012662 public void setBatteryStateLocked(final int status, final int health, final int plugType,
12663 final int level, /* not final */ int temp, final int volt, final int chargeUAh,
12664 final int chargeFullUAh) {
Adam Lesinski29ddfe52017-03-29 19:29:00 -070012665 // Temperature is encoded without the signed bit, so clamp any negative temperatures to 0.
12666 temp = Math.max(0, temp);
12667
Bookatz8c6571b2017-10-24 15:04:41 -070012668 reportChangesToStatsLog(mHaveBatteryLevel ? mHistoryCur : null,
Tej Singh40298312018-02-16 00:15:09 -080012669 status, plugType, level);
Bookatz8c6571b2017-10-24 15:04:41 -070012670
Sudheer Shankac57729a2018-02-09 15:44:42 -080012671 final boolean onBattery = isOnBattery(plugType, status);
Joe Onoratoabded112016-02-08 16:49:39 -080012672 final long uptime = mClocks.uptimeMillis();
12673 final long elapsedRealtime = mClocks.elapsedRealtime();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012674 if (!mHaveBatteryLevel) {
12675 mHaveBatteryLevel = true;
12676 // We start out assuming that the device is plugged in (not
12677 // on battery). If our first report is now that we are indeed
12678 // plugged in, then twiddle our state to correctly reflect that
12679 // since we won't be going through the full setOnBattery().
12680 if (onBattery == mOnBattery) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012681 if (onBattery) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012682 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012683 } else {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012684 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012685 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012686 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012687 // Always start out assuming charging, that will be updated later.
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012688 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012689 mHistoryCur.batteryStatus = (byte)status;
12690 mHistoryCur.batteryLevel = (byte)level;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012691 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012692 mMaxChargeStepLevel = mMinDischargeStepLevel =
12693 mLastChargeStepLevel = mLastDischargeStepLevel = level;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012694 mLastChargingStateLevel = level;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012695 } else if (mCurrentBatteryLevel != level || mOnBattery != onBattery) {
12696 recordDailyStatsIfNeededLocked(level >= 100 && onBattery);
12697 }
12698 int oldStatus = mHistoryCur.batteryStatus;
12699 if (onBattery) {
12700 mDischargeCurrentLevel = level;
12701 if (!mRecordingHistory) {
12702 mRecordingHistory = true;
12703 startRecordingHistory(elapsedRealtime, uptime, true);
12704 }
Todd Poynor1acf06a2017-12-07 19:19:35 -080012705 } else if (level < 96 &&
12706 status != BatteryManager.BATTERY_STATUS_UNKNOWN) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012707 if (!mRecordingHistory) {
12708 mRecordingHistory = true;
12709 startRecordingHistory(elapsedRealtime, uptime, true);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012710 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070012711 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012712 mCurrentBatteryLevel = level;
12713 if (mDischargePlugLevel < 0) {
12714 mDischargePlugLevel = level;
Marco Nelissend8593312009-04-30 14:45:06 -070012715 }
Adam Lesinski926969b2016-04-28 17:31:12 -070012716
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012717 if (onBattery != mOnBattery) {
12718 mHistoryCur.batteryLevel = (byte)level;
12719 mHistoryCur.batteryStatus = (byte)status;
12720 mHistoryCur.batteryHealth = (byte)health;
12721 mHistoryCur.batteryPlugType = (byte)plugType;
12722 mHistoryCur.batteryTemperature = (short)temp;
12723 mHistoryCur.batteryVoltage = (char)volt;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012724 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
12725 // Only record discharges
12726 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
12727 mDischargeCounter.addCountLocked(chargeDiff);
12728 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070012729 if (isScreenDoze(mScreenState)) {
12730 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
12731 }
Mike Ma15313c92017-11-15 17:58:21 -080012732 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
12733 mDischargeLightDozeCounter.addCountLocked(chargeDiff);
12734 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
12735 mDischargeDeepDozeCounter.addCountLocked(chargeDiff);
12736 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012737 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012738 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012739 setOnBatteryLocked(elapsedRealtime, uptime, onBattery, oldStatus, level, chargeUAh);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012740 } else {
12741 boolean changed = false;
12742 if (mHistoryCur.batteryLevel != level) {
12743 mHistoryCur.batteryLevel = (byte)level;
12744 changed = true;
Marco Nelissend8593312009-04-30 14:45:06 -070012745
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012746 // TODO(adamlesinski): Schedule the creation of a HistoryStepDetails record
12747 // which will pull external stats.
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012748 scheduleSyncExternalStatsLocked("battery-level", ExternalStatsSync.UPDATE_ALL);
Evan Millarc64edde2009-04-18 12:26:32 -070012749 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012750 if (mHistoryCur.batteryStatus != status) {
12751 mHistoryCur.batteryStatus = (byte)status;
12752 changed = true;
12753 }
12754 if (mHistoryCur.batteryHealth != health) {
12755 mHistoryCur.batteryHealth = (byte)health;
12756 changed = true;
12757 }
12758 if (mHistoryCur.batteryPlugType != plugType) {
12759 mHistoryCur.batteryPlugType = (byte)plugType;
12760 changed = true;
12761 }
12762 if (temp >= (mHistoryCur.batteryTemperature+10)
12763 || temp <= (mHistoryCur.batteryTemperature-10)) {
12764 mHistoryCur.batteryTemperature = (short)temp;
12765 changed = true;
12766 }
12767 if (volt > (mHistoryCur.batteryVoltage+20)
12768 || volt < (mHistoryCur.batteryVoltage-20)) {
12769 mHistoryCur.batteryVoltage = (char)volt;
12770 changed = true;
12771 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012772 if (chargeUAh >= (mHistoryCur.batteryChargeUAh+10)
12773 || chargeUAh <= (mHistoryCur.batteryChargeUAh-10)) {
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012774 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
12775 // Only record discharges
12776 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
12777 mDischargeCounter.addCountLocked(chargeDiff);
12778 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070012779 if (isScreenDoze(mScreenState)) {
12780 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
12781 }
Mike Ma15313c92017-11-15 17:58:21 -080012782 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
12783 mDischargeLightDozeCounter.addCountLocked(chargeDiff);
12784 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
12785 mDischargeDeepDozeCounter.addCountLocked(chargeDiff);
12786 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012787 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012788 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski926969b2016-04-28 17:31:12 -070012789 changed = true;
12790 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012791 long modeBits = (((long)mInitStepMode) << STEP_LEVEL_INITIAL_MODE_SHIFT)
12792 | (((long)mModStepMode) << STEP_LEVEL_MODIFIED_MODE_SHIFT)
12793 | (((long)(level&0xff)) << STEP_LEVEL_LEVEL_SHIFT);
12794 if (onBattery) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012795 changed |= setChargingLocked(false);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012796 if (mLastDischargeStepLevel != level && mMinDischargeStepLevel > level) {
12797 mDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
12798 modeBits, elapsedRealtime);
12799 mDailyDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
12800 modeBits, elapsedRealtime);
12801 mLastDischargeStepLevel = level;
12802 mMinDischargeStepLevel = level;
12803 mInitStepMode = mCurStepMode;
12804 mModStepMode = 0;
12805 }
12806 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012807 if (level >= 90) {
12808 // If the battery level is at least 90%, always consider the device to be
12809 // charging even if it happens to go down a level.
12810 changed |= setChargingLocked(true);
12811 mLastChargeStepLevel = level;
12812 } if (!mCharging) {
12813 if (mLastChargeStepLevel < level) {
12814 // We have not reporting that we are charging, but the level has now
12815 // gone up, so consider the state to be charging.
12816 changed |= setChargingLocked(true);
12817 mLastChargeStepLevel = level;
12818 }
12819 } else {
12820 if (mLastChargeStepLevel > level) {
12821 // We had reported that the device was charging, but here we are with
12822 // power connected and the level going down. Looks like the current
12823 // power supplied isn't enough, so consider the device to now be
12824 // discharging.
12825 changed |= setChargingLocked(false);
12826 mLastChargeStepLevel = level;
12827 }
12828 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012829 if (mLastChargeStepLevel != level && mMaxChargeStepLevel < level) {
12830 mChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
12831 modeBits, elapsedRealtime);
12832 mDailyChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
12833 modeBits, elapsedRealtime);
12834 mLastChargeStepLevel = level;
12835 mMaxChargeStepLevel = level;
12836 mInitStepMode = mCurStepMode;
12837 mModStepMode = 0;
Evan Millarc64edde2009-04-18 12:26:32 -070012838 }
12839 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012840 if (changed) {
12841 addHistoryRecordLocked(elapsedRealtime, uptime);
12842 }
Evan Millarc64edde2009-04-18 12:26:32 -070012843 }
Todd Poynor1acf06a2017-12-07 19:19:35 -080012844 if (!onBattery &&
12845 (status == BatteryManager.BATTERY_STATUS_FULL ||
12846 status == BatteryManager.BATTERY_STATUS_UNKNOWN)) {
12847 // We don't record history while we are plugged in and fully charged
12848 // (or when battery is not present). The next time we are
12849 // unplugged, history will be cleared.
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012850 mRecordingHistory = DEBUG;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080012851 }
Adam Lesinski041d9172016-12-12 12:03:56 -080012852
Jocelyn Dangc627d102017-04-14 13:15:14 -070012853 if (mMinLearnedBatteryCapacity == -1) {
12854 mMinLearnedBatteryCapacity = chargeFullUAh;
12855 } else {
12856 Math.min(mMinLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski041d9172016-12-12 12:03:56 -080012857 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070012858 mMaxLearnedBatteryCapacity = Math.max(mMaxLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski33dac552015-03-09 15:24:48 -070012859 }
12860
Sudheer Shankac57729a2018-02-09 15:44:42 -080012861 public static boolean isOnBattery(int plugType, int status) {
12862 return plugType == BATTERY_PLUGGED_NONE && status != BatteryManager.BATTERY_STATUS_UNKNOWN;
12863 }
12864
Bookatz8c6571b2017-10-24 15:04:41 -070012865 // Inform StatsLog of setBatteryState changes.
12866 // If this is the first reporting, pass in recentPast == null.
12867 private void reportChangesToStatsLog(HistoryItem recentPast,
Tej Singh40298312018-02-16 00:15:09 -080012868 final int status, final int plugType, final int level) {
Bookatz8c6571b2017-10-24 15:04:41 -070012869
12870 if (recentPast == null || recentPast.batteryStatus != status) {
12871 StatsLog.write(StatsLog.CHARGING_STATE_CHANGED, status);
12872 }
12873 if (recentPast == null || recentPast.batteryPlugType != plugType) {
12874 StatsLog.write(StatsLog.PLUGGED_STATE_CHANGED, plugType);
12875 }
12876 if (recentPast == null || recentPast.batteryLevel != level) {
12877 StatsLog.write(StatsLog.BATTERY_LEVEL_CHANGED, level);
12878 }
Bookatz8c6571b2017-10-24 15:04:41 -070012879 }
12880
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012881 public long getAwakeTimeBattery() {
12882 return computeBatteryUptime(getBatteryUptimeLocked(), STATS_CURRENT);
12883 }
12884
12885 public long getAwakeTimePlugged() {
Joe Onoratoabded112016-02-08 16:49:39 -080012886 return (mClocks.uptimeMillis() * 1000) - getAwakeTimeBattery();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012887 }
12888
12889 @Override
12890 public long computeUptime(long curTime, int which) {
12891 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012892 case STATS_SINCE_CHARGED: return mUptime + (curTime-mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012893 case STATS_CURRENT: return (curTime-mUptimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070012894 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getUptimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012895 }
12896 return 0;
12897 }
12898
12899 @Override
12900 public long computeRealtime(long curTime, int which) {
12901 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012902 case STATS_SINCE_CHARGED: return mRealtime + (curTime-mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012903 case STATS_CURRENT: return (curTime-mRealtimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070012904 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getRealtimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012905 }
12906 return 0;
12907 }
12908
12909 @Override
12910 public long computeBatteryUptime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012911 return mOnBatteryTimeBase.computeUptime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012912 }
12913
12914 @Override
12915 public long computeBatteryRealtime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012916 return mOnBatteryTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012917 }
12918
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012919 @Override
12920 public long computeBatteryScreenOffUptime(long curTime, int which) {
12921 return mOnBatteryScreenOffTimeBase.computeUptime(curTime, which);
12922 }
12923
12924 @Override
12925 public long computeBatteryScreenOffRealtime(long curTime, int which) {
12926 return mOnBatteryScreenOffTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012927 }
12928
Dianne Hackborn260c5022014-04-29 11:23:16 -070012929 private long computeTimePerLevel(long[] steps, int numSteps) {
12930 // For now we'll do a simple average across all steps.
12931 if (numSteps <= 0) {
12932 return -1;
12933 }
12934 long total = 0;
12935 for (int i=0; i<numSteps; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012936 total += steps[i] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012937 }
12938 return total / numSteps;
12939 /*
12940 long[] buckets = new long[numSteps];
12941 int numBuckets = 0;
12942 int numToAverage = 4;
12943 int i = 0;
12944 while (i < numSteps) {
12945 long totalTime = 0;
12946 int num = 0;
12947 for (int j=0; j<numToAverage && (i+j)<numSteps; j++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012948 totalTime += steps[i+j] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012949 num++;
12950 }
12951 buckets[numBuckets] = totalTime / num;
12952 numBuckets++;
12953 numToAverage *= 2;
12954 i += num;
12955 }
12956 if (numBuckets < 1) {
12957 return -1;
12958 }
12959 long averageTime = buckets[numBuckets-1];
12960 for (i=numBuckets-2; i>=0; i--) {
12961 averageTime = (averageTime + buckets[i]) / 2;
12962 }
12963 return averageTime;
12964 */
12965 }
12966
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012967 @Override
12968 public long computeBatteryTimeRemaining(long curTime) {
12969 if (!mOnBattery) {
12970 return -1;
12971 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070012972 /* Simple implementation just looks at the average discharge per level across the
12973 entire sample period.
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012974 int discharge = (getLowDischargeAmountSinceCharge()+getHighDischargeAmountSinceCharge())/2;
12975 if (discharge < 2) {
12976 return -1;
12977 }
12978 long duration = computeBatteryRealtime(curTime, STATS_SINCE_CHARGED);
12979 if (duration < 1000*1000) {
12980 return -1;
12981 }
12982 long usPerLevel = duration/discharge;
12983 return usPerLevel * mCurrentBatteryLevel;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012984 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012985 if (mDischargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012986 return -1;
12987 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012988 long msPerLevel = mDischargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012989 if (msPerLevel <= 0) {
12990 return -1;
12991 }
12992 return (msPerLevel * mCurrentBatteryLevel) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012993 }
12994
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012995 @Override
12996 public LevelStepTracker getDischargeLevelStepTracker() {
12997 return mDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012998 }
12999
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013000 @Override
13001 public LevelStepTracker getDailyDischargeLevelStepTracker() {
13002 return mDailyDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070013003 }
13004
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013005 @Override
13006 public long computeChargeTimeRemaining(long curTime) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070013007 if (mOnBattery) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013008 // Not yet working.
13009 return -1;
13010 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070013011 /* Broken
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013012 int curLevel = mCurrentBatteryLevel;
13013 int plugLevel = mDischargePlugLevel;
13014 if (plugLevel < 0 || curLevel < (plugLevel+1)) {
13015 return -1;
13016 }
13017 long duration = computeBatteryRealtime(curTime, STATS_SINCE_UNPLUGGED);
13018 if (duration < 1000*1000) {
13019 return -1;
13020 }
13021 long usPerLevel = duration/(curLevel-plugLevel);
13022 return usPerLevel * (100-curLevel);
Dianne Hackborn260c5022014-04-29 11:23:16 -070013023 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013024 if (mChargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070013025 return -1;
13026 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013027 long msPerLevel = mChargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070013028 if (msPerLevel <= 0) {
13029 return -1;
13030 }
13031 return (msPerLevel * (100-mCurrentBatteryLevel)) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013032 }
13033
Siddharth Raya1fd0572017-11-13 14:20:47 -080013034 /*@hide */
13035 public CellularBatteryStats getCellularBatteryStats() {
13036 CellularBatteryStats s = new CellularBatteryStats();
13037 final int which = STATS_SINCE_CHARGED;
13038 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
13039 final ControllerActivityCounter counter = getModemControllerActivity();
Siddharth Rayed754702018-02-15 12:44:37 -080013040 final long sleepTimeMs = counter.getSleepTimeCounter().getCountLocked(which);
Siddharth Raya1fd0572017-11-13 14:20:47 -080013041 final long idleTimeMs = counter.getIdleTimeCounter().getCountLocked(which);
13042 final long rxTimeMs = counter.getRxTimeCounter().getCountLocked(which);
13043 final long energyConsumedMaMs = counter.getPowerCounter().getCountLocked(which);
13044 long[] timeInRatMs = new long[BatteryStats.NUM_DATA_CONNECTION_TYPES];
13045 for (int i = 0; i < timeInRatMs.length; i++) {
13046 timeInRatMs[i] = getPhoneDataConnectionTime(i, rawRealTime, which) / 1000;
13047 }
13048 long[] timeInRxSignalStrengthLevelMs = new long[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
13049 for (int i = 0; i < timeInRxSignalStrengthLevelMs.length; i++) {
13050 timeInRxSignalStrengthLevelMs[i]
13051 = getPhoneSignalStrengthTime(i, rawRealTime, which) / 1000;
13052 }
13053 long[] txTimeMs = new long[Math.min(ModemActivityInfo.TX_POWER_LEVELS,
13054 counter.getTxTimeCounters().length)];
13055 long totalTxTimeMs = 0;
13056 for (int i = 0; i < txTimeMs.length; i++) {
13057 txTimeMs[i] = counter.getTxTimeCounters()[i].getCountLocked(which);
13058 totalTxTimeMs += txTimeMs[i];
13059 }
Siddharth Raya1fd0572017-11-13 14:20:47 -080013060 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
13061 s.setKernelActiveTimeMs(getMobileRadioActiveTime(rawRealTime, which) / 1000);
13062 s.setNumPacketsTx(getNetworkActivityPackets(NETWORK_MOBILE_TX_DATA, which));
13063 s.setNumBytesTx(getNetworkActivityBytes(NETWORK_MOBILE_TX_DATA, which));
13064 s.setNumPacketsRx(getNetworkActivityPackets(NETWORK_MOBILE_RX_DATA, which));
13065 s.setNumBytesRx(getNetworkActivityBytes(NETWORK_MOBILE_RX_DATA, which));
13066 s.setSleepTimeMs(sleepTimeMs);
13067 s.setIdleTimeMs(idleTimeMs);
13068 s.setRxTimeMs(rxTimeMs);
13069 s.setEnergyConsumedMaMs(energyConsumedMaMs);
13070 s.setTimeInRatMs(timeInRatMs);
13071 s.setTimeInRxSignalStrengthLevelMs(timeInRxSignalStrengthLevelMs);
13072 s.setTxTimeMs(txTimeMs);
13073 return s;
13074 }
13075
Siddharth Rayb50a6842017-12-14 15:15:28 -080013076 /*@hide */
13077 public WifiBatteryStats getWifiBatteryStats() {
13078 WifiBatteryStats s = new WifiBatteryStats();
13079 final int which = STATS_SINCE_CHARGED;
13080 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
13081 final ControllerActivityCounter counter = getWifiControllerActivity();
13082 final long idleTimeMs = counter.getIdleTimeCounter().getCountLocked(which);
13083 final long scanTimeMs = counter.getScanTimeCounter().getCountLocked(which);
13084 final long rxTimeMs = counter.getRxTimeCounter().getCountLocked(which);
13085 final long txTimeMs = counter.getTxTimeCounters()[0].getCountLocked(which);
13086 final long totalControllerActivityTimeMs
13087 = computeBatteryRealtime(SystemClock.elapsedRealtime() * 1000, which) / 1000;
13088 final long sleepTimeMs
13089 = totalControllerActivityTimeMs - (idleTimeMs + rxTimeMs + txTimeMs);
13090 final long energyConsumedMaMs = counter.getPowerCounter().getCountLocked(which);
13091 long numAppScanRequest = 0;
13092 for (int i = 0; i < mUidStats.size(); i++) {
13093 numAppScanRequest += mUidStats.valueAt(i).mWifiScanTimer.getCountLocked(which);
13094 }
13095 long[] timeInStateMs = new long[NUM_WIFI_STATES];
13096 for (int i=0; i<NUM_WIFI_STATES; i++) {
13097 timeInStateMs[i] = getWifiStateTime(i, rawRealTime, which) / 1000;
13098 }
13099 long[] timeInSupplStateMs = new long[NUM_WIFI_SUPPL_STATES];
13100 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
13101 timeInSupplStateMs[i] = getWifiSupplStateTime(i, rawRealTime, which) / 1000;
13102 }
13103 long[] timeSignalStrengthTimeMs = new long[NUM_WIFI_SIGNAL_STRENGTH_BINS];
13104 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
13105 timeSignalStrengthTimeMs[i] = getWifiSignalStrengthTime(i, rawRealTime, which) / 1000;
13106 }
13107 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
13108 s.setKernelActiveTimeMs(getWifiActiveTime(rawRealTime, which) / 1000);
13109 s.setNumPacketsTx(getNetworkActivityPackets(NETWORK_WIFI_TX_DATA, which));
13110 s.setNumBytesTx(getNetworkActivityBytes(NETWORK_WIFI_TX_DATA, which));
13111 s.setNumPacketsRx(getNetworkActivityPackets(NETWORK_WIFI_RX_DATA, which));
13112 s.setNumBytesRx(getNetworkActivityBytes(NETWORK_WIFI_RX_DATA, which));
13113 s.setSleepTimeMs(sleepTimeMs);
13114 s.setIdleTimeMs(idleTimeMs);
13115 s.setRxTimeMs(rxTimeMs);
13116 s.setTxTimeMs(txTimeMs);
13117 s.setScanTimeMs(scanTimeMs);
13118 s.setEnergyConsumedMaMs(energyConsumedMaMs);
13119 s.setNumAppScanRequest(numAppScanRequest);
13120 s.setTimeInStateMs(timeInStateMs);
13121 s.setTimeInSupplicantStateMs(timeInSupplStateMs);
13122 s.setTimeInRxSignalStrengthLevelMs(timeSignalStrengthTimeMs);
13123 return s;
13124 }
13125
Siddharth Ray78ccaf52017-12-23 16:16:21 -080013126 /*@hide */
13127 public GpsBatteryStats getGpsBatteryStats() {
13128 GpsBatteryStats s = new GpsBatteryStats();
13129 final int which = STATS_SINCE_CHARGED;
13130 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
13131 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
13132 s.setEnergyConsumedMaMs(getGpsBatteryDrainMaMs());
13133 long[] time = new long[GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS];
13134 for (int i=0; i<time.length; i++) {
13135 time[i] = getGpsSignalQualityTime(i, rawRealTime, which) / 1000;
13136 }
13137 s.setTimeInGpsSignalQualityLevel(time);
13138 return s;
13139 }
13140
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013141 @Override
13142 public LevelStepTracker getChargeLevelStepTracker() {
13143 return mChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070013144 }
13145
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013146 @Override
13147 public LevelStepTracker getDailyChargeLevelStepTracker() {
13148 return mDailyChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070013149 }
13150
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013151 @Override
13152 public ArrayList<PackageChange> getDailyPackageChanges() {
13153 return mDailyPackageChanges;
13154 }
13155
Joe Onoratoe1acd632016-02-23 13:25:10 -080013156 protected long getBatteryUptimeLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080013157 return mOnBatteryTimeBase.getUptime(mClocks.uptimeMillis() * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013158 }
13159
13160 @Override
13161 public long getBatteryUptime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013162 return mOnBatteryTimeBase.getUptime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013163 }
13164
13165 @Override
13166 public long getBatteryRealtime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013167 return mOnBatteryTimeBase.getRealtime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013168 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -070013169
The Android Open Source Project10592532009-03-18 17:39:46 -070013170 @Override
Evan Millar633a1742009-04-02 16:36:33 -070013171 public int getDischargeStartLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070013172 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070013173 return getDischargeStartLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070013174 }
13175 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013176
Evan Millar633a1742009-04-02 16:36:33 -070013177 public int getDischargeStartLevelLocked() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013178 return mDischargeUnplugLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070013179 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013180
The Android Open Source Project10592532009-03-18 17:39:46 -070013181 @Override
Evan Millar633a1742009-04-02 16:36:33 -070013182 public int getDischargeCurrentLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070013183 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070013184 return getDischargeCurrentLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070013185 }
13186 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013187
Evan Millar633a1742009-04-02 16:36:33 -070013188 public int getDischargeCurrentLevelLocked() {
Dianne Hackborne4a59512010-12-07 11:08:07 -080013189 return mDischargeCurrentLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070013190 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013191
Amith Yamasanie43530a2009-08-21 13:11:37 -070013192 @Override
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013193 public int getLowDischargeAmountSinceCharge() {
13194 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080013195 int val = mLowDischargeAmountSinceCharge;
13196 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
13197 val += mDischargeUnplugLevel-mDischargeCurrentLevel-1;
13198 }
13199 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013200 }
13201 }
13202
13203 @Override
13204 public int getHighDischargeAmountSinceCharge() {
13205 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080013206 int val = mHighDischargeAmountSinceCharge;
13207 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
13208 val += mDischargeUnplugLevel-mDischargeCurrentLevel;
13209 }
13210 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013211 }
13212 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070013213
13214 @Override
13215 public int getDischargeAmount(int which) {
13216 int dischargeAmount = which == STATS_SINCE_CHARGED
13217 ? getHighDischargeAmountSinceCharge()
13218 : (getDischargeStartLevel() - getDischargeCurrentLevel());
13219 if (dischargeAmount < 0) {
13220 dischargeAmount = 0;
13221 }
13222 return dischargeAmount;
13223 }
13224
Mike Mac2f518a2017-09-19 16:06:03 -070013225 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013226 public int getDischargeAmountScreenOn() {
13227 synchronized(this) {
13228 int val = mDischargeAmountScreenOn;
Mike Mac2f518a2017-09-19 16:06:03 -070013229 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013230 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
13231 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
13232 }
13233 return val;
13234 }
13235 }
13236
Mike Mac2f518a2017-09-19 16:06:03 -070013237 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013238 public int getDischargeAmountScreenOnSinceCharge() {
13239 synchronized(this) {
13240 int val = mDischargeAmountScreenOnSinceCharge;
Mike Mac2f518a2017-09-19 16:06:03 -070013241 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013242 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
13243 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
13244 }
13245 return val;
13246 }
13247 }
13248
Mike Mac2f518a2017-09-19 16:06:03 -070013249 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013250 public int getDischargeAmountScreenOff() {
13251 synchronized(this) {
13252 int val = mDischargeAmountScreenOff;
Mike Mac2f518a2017-09-19 16:06:03 -070013253 if (mOnBattery && isScreenOff(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013254 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
13255 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
13256 }
Mike Mac2f518a2017-09-19 16:06:03 -070013257 // For backward compatibility, doze discharge is counted into screen off.
13258 return val + getDischargeAmountScreenDoze();
13259 }
13260 }
13261
13262 @Override
13263 public int getDischargeAmountScreenOffSinceCharge() {
13264 synchronized(this) {
13265 int val = mDischargeAmountScreenOffSinceCharge;
13266 if (mOnBattery && isScreenOff(mScreenState)
13267 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
13268 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
13269 }
13270 // For backward compatibility, doze discharge is counted into screen off.
13271 return val + getDischargeAmountScreenDozeSinceCharge();
13272 }
13273 }
13274
13275 @Override
13276 public int getDischargeAmountScreenDoze() {
13277 synchronized(this) {
13278 int val = mDischargeAmountScreenDoze;
13279 if (mOnBattery && isScreenDoze(mScreenState)
13280 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
13281 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
13282 }
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013283 return val;
13284 }
13285 }
13286
Mike Mac2f518a2017-09-19 16:06:03 -070013287 @Override
13288 public int getDischargeAmountScreenDozeSinceCharge() {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013289 synchronized(this) {
Mike Mac2f518a2017-09-19 16:06:03 -070013290 int val = mDischargeAmountScreenDozeSinceCharge;
13291 if (mOnBattery && isScreenDoze(mScreenState)
13292 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
13293 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013294 }
13295 return val;
13296 }
13297 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013299 /**
13300 * Retrieve the statistics object for a particular uid, creating if needed.
13301 */
13302 public Uid getUidStatsLocked(int uid) {
13303 Uid u = mUidStats.get(uid);
13304 if (u == null) {
Joe Onoratoabded112016-02-08 16:49:39 -080013305 u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013306 mUidStats.put(uid, u);
13307 }
13308 return u;
13309 }
13310
Sudheer Shankab2f83c12017-11-13 19:25:01 -080013311 /**
13312 * Retrieve the statistics object for a particular uid. Returns null if the object is not
13313 * available.
13314 */
13315 public Uid getAvailableUidStatsLocked(int uid) {
13316 Uid u = mUidStats.get(uid);
13317 return u;
13318 }
13319
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070013320 public void onCleanupUserLocked(int userId) {
13321 final int firstUidForUser = UserHandle.getUid(userId, 0);
13322 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
Mike Ma234d1822018-03-13 18:53:21 -070013323 mPendingRemovedUids.add(
13324 new UidToRemove(firstUidForUser, lastUidForUser, mClocks.elapsedRealtime()));
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070013325 }
13326
13327 public void onUserRemovedLocked(int userId) {
13328 final int firstUidForUser = UserHandle.getUid(userId, 0);
13329 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
13330 mUidStats.put(firstUidForUser, null);
13331 mUidStats.put(lastUidForUser, null);
13332 final int firstIndex = mUidStats.indexOfKey(firstUidForUser);
13333 final int lastIndex = mUidStats.indexOfKey(lastUidForUser);
13334 mUidStats.removeAtRange(firstIndex, lastIndex - firstIndex + 1);
13335 }
13336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013337 /**
13338 * Remove the statistics object for a particular uid.
13339 */
13340 public void removeUidStatsLocked(int uid) {
13341 mUidStats.remove(uid);
Mike Ma234d1822018-03-13 18:53:21 -070013342 mPendingRemovedUids.add(new UidToRemove(uid, mClocks.elapsedRealtime()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013343 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -070013344
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013345 /**
13346 * Retrieve the statistics object for a particular process, creating
13347 * if needed.
13348 */
13349 public Uid.Proc getProcessStatsLocked(int uid, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013350 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013351 Uid u = getUidStatsLocked(uid);
13352 return u.getProcessStatsLocked(name);
13353 }
13354
13355 /**
13356 * Retrieve the statistics object for a particular process, creating
13357 * if needed.
13358 */
13359 public Uid.Pkg getPackageStatsLocked(int uid, String pkg) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013360 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013361 Uid u = getUidStatsLocked(uid);
13362 return u.getPackageStatsLocked(pkg);
13363 }
13364
13365 /**
13366 * Retrieve the statistics object for a particular service, creating
13367 * if needed.
13368 */
13369 public Uid.Pkg.Serv getServiceStatsLocked(int uid, String pkg, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013370 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013371 Uid u = getUidStatsLocked(uid);
13372 return u.getServiceStatsLocked(pkg, name);
13373 }
13374
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013375 public void shutdownLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080013376 recordShutdownLocked(mClocks.elapsedRealtime(), mClocks.uptimeMillis());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013377 writeSyncLocked();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013378 mShuttingDown = true;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013379 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013380
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013381 public boolean trackPerProcStateCpuTimes() {
13382 return mConstants.TRACK_CPU_TIMES_BY_PROC_STATE && mPerProcStateCpuTimesAvailable;
13383 }
13384
13385 public void systemServicesReady(Context context) {
13386 mConstants.startObserving(context.getContentResolver());
13387 }
13388
13389 @VisibleForTesting
13390 public final class Constants extends ContentObserver {
13391 public static final String KEY_TRACK_CPU_TIMES_BY_PROC_STATE
13392 = "track_cpu_times_by_proc_state";
Mike Mafae87da2018-01-19 20:07:20 -080013393 public static final String KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME
13394 = "track_cpu_active_cluster_time";
Sudheer Shankac20379e2018-02-15 00:06:21 -080013395 public static final String KEY_PROC_STATE_CPU_TIMES_READ_DELAY_MS
13396 = "proc_state_cpu_times_read_delay_ms";
Mike Ma2ab01442018-02-13 14:22:47 -080013397 public static final String KEY_KERNEL_UID_READERS_THROTTLE_TIME
13398 = "kernel_uid_readers_throttle_time";
Mike Ma234d1822018-03-13 18:53:21 -070013399 public static final String KEY_UID_REMOVE_DELAY_MS
13400 = "uid_remove_delay_ms";
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013401
13402 private static final boolean DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE = true;
Mike Mafae87da2018-01-19 20:07:20 -080013403 private static final boolean DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME = true;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013404 private static final long DEFAULT_PROC_STATE_CPU_TIMES_READ_DELAY_MS = 5_000;
Mike Ma2ab01442018-02-13 14:22:47 -080013405 private static final long DEFAULT_KERNEL_UID_READERS_THROTTLE_TIME = 10_000;
Mike Ma234d1822018-03-13 18:53:21 -070013406 private static final long DEFAULT_UID_REMOVE_DELAY_MS = 5L * 60L * 1000L;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013407
13408 public boolean TRACK_CPU_TIMES_BY_PROC_STATE = DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE;
Mike Mafae87da2018-01-19 20:07:20 -080013409 public boolean TRACK_CPU_ACTIVE_CLUSTER_TIME = DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013410 public long PROC_STATE_CPU_TIMES_READ_DELAY_MS = DEFAULT_PROC_STATE_CPU_TIMES_READ_DELAY_MS;
Mike Ma2ab01442018-02-13 14:22:47 -080013411 public long KERNEL_UID_READERS_THROTTLE_TIME = DEFAULT_KERNEL_UID_READERS_THROTTLE_TIME;
Mike Ma234d1822018-03-13 18:53:21 -070013412 public long UID_REMOVE_DELAY_MS = DEFAULT_UID_REMOVE_DELAY_MS;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013413
13414 private ContentResolver mResolver;
13415 private final KeyValueListParser mParser = new KeyValueListParser(',');
13416
13417 public Constants(Handler handler) {
13418 super(handler);
13419 }
13420
13421 public void startObserving(ContentResolver resolver) {
13422 mResolver = resolver;
13423 mResolver.registerContentObserver(
13424 Settings.Global.getUriFor(Settings.Global.BATTERY_STATS_CONSTANTS),
13425 false /* notifyForDescendants */, this);
13426 updateConstants();
13427 }
13428
13429 @Override
13430 public void onChange(boolean selfChange, Uri uri) {
13431 updateConstants();
13432 }
13433
13434 private void updateConstants() {
13435 synchronized (BatteryStatsImpl.this) {
13436 try {
13437 mParser.setString(Settings.Global.getString(mResolver,
13438 Settings.Global.BATTERY_STATS_CONSTANTS));
13439 } catch (IllegalArgumentException e) {
13440 // Failed to parse the settings string, log this and move on
13441 // with defaults.
13442 Slog.e(TAG, "Bad batterystats settings", e);
13443 }
13444
13445 updateTrackCpuTimesByProcStateLocked(TRACK_CPU_TIMES_BY_PROC_STATE,
13446 mParser.getBoolean(KEY_TRACK_CPU_TIMES_BY_PROC_STATE,
13447 DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE));
Mike Mafae87da2018-01-19 20:07:20 -080013448 TRACK_CPU_ACTIVE_CLUSTER_TIME = mParser.getBoolean(
13449 KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME, DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME);
Sudheer Shankac20379e2018-02-15 00:06:21 -080013450 updateProcStateCpuTimesReadDelayMs(PROC_STATE_CPU_TIMES_READ_DELAY_MS,
13451 mParser.getLong(KEY_PROC_STATE_CPU_TIMES_READ_DELAY_MS,
Mike Ma2ab01442018-02-13 14:22:47 -080013452 DEFAULT_PROC_STATE_CPU_TIMES_READ_DELAY_MS));
13453 updateKernelUidReadersThrottleTime(KERNEL_UID_READERS_THROTTLE_TIME,
13454 mParser.getLong(KEY_KERNEL_UID_READERS_THROTTLE_TIME,
13455 DEFAULT_KERNEL_UID_READERS_THROTTLE_TIME));
Mike Ma234d1822018-03-13 18:53:21 -070013456 updateUidRemoveDelay(
13457 mParser.getLong(KEY_UID_REMOVE_DELAY_MS, DEFAULT_UID_REMOVE_DELAY_MS));
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013458 }
13459 }
13460
13461 private void updateTrackCpuTimesByProcStateLocked(boolean wasEnabled, boolean isEnabled) {
13462 TRACK_CPU_TIMES_BY_PROC_STATE = isEnabled;
13463 if (isEnabled && !wasEnabled) {
13464 mKernelSingleUidTimeReader.markDataAsStale(true);
13465 mExternalSync.scheduleCpuSyncDueToSettingChange();
Sudheer Shankac20379e2018-02-15 00:06:21 -080013466
Mike Ma234d1822018-03-13 18:53:21 -070013467 mNumSingleUidCpuTimeReads = 0;
13468 mNumBatchedSingleUidCpuTimeReads = 0;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013469 mCpuTimeReadsTrackingStartTime = mClocks.uptimeMillis();
13470 }
13471 }
13472
13473 private void updateProcStateCpuTimesReadDelayMs(long oldDelayMillis, long newDelayMillis) {
13474 PROC_STATE_CPU_TIMES_READ_DELAY_MS = newDelayMillis;
13475 if (oldDelayMillis != newDelayMillis) {
Mike Ma234d1822018-03-13 18:53:21 -070013476 mNumSingleUidCpuTimeReads = 0;
13477 mNumBatchedSingleUidCpuTimeReads = 0;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013478 mCpuTimeReadsTrackingStartTime = mClocks.uptimeMillis();
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013479 }
13480 }
13481
Mike Ma2ab01442018-02-13 14:22:47 -080013482 private void updateKernelUidReadersThrottleTime(long oldTimeMs, long newTimeMs) {
13483 KERNEL_UID_READERS_THROTTLE_TIME = newTimeMs;
13484 if (oldTimeMs != newTimeMs) {
Mike Ma69d8b3e2018-02-23 14:51:26 -080013485 mKernelUidCpuTimeReader.setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
Mike Ma2ab01442018-02-13 14:22:47 -080013486 mKernelUidCpuFreqTimeReader.setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
13487 mKernelUidCpuActiveTimeReader.setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
13488 mKernelUidCpuClusterTimeReader
13489 .setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
13490 }
13491 }
13492
Mike Ma234d1822018-03-13 18:53:21 -070013493 private void updateUidRemoveDelay(long newTimeMs) {
13494 UID_REMOVE_DELAY_MS = newTimeMs;
13495 clearPendingRemovedUids();
13496 }
13497
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013498 public void dumpLocked(PrintWriter pw) {
13499 pw.print(KEY_TRACK_CPU_TIMES_BY_PROC_STATE); pw.print("=");
13500 pw.println(TRACK_CPU_TIMES_BY_PROC_STATE);
Mike Mafae87da2018-01-19 20:07:20 -080013501 pw.print(KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME); pw.print("=");
13502 pw.println(TRACK_CPU_ACTIVE_CLUSTER_TIME);
Sudheer Shankac20379e2018-02-15 00:06:21 -080013503 pw.print(KEY_PROC_STATE_CPU_TIMES_READ_DELAY_MS); pw.print("=");
13504 pw.println(PROC_STATE_CPU_TIMES_READ_DELAY_MS);
Mike Ma2ab01442018-02-13 14:22:47 -080013505 pw.print(KEY_KERNEL_UID_READERS_THROTTLE_TIME); pw.print("=");
13506 pw.println(KERNEL_UID_READERS_THROTTLE_TIME);
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013507 }
13508 }
13509
Andreas Gampe3f24e692018-02-05 13:24:28 -080013510 @GuardedBy("this")
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013511 public void dumpConstantsLocked(PrintWriter pw) {
13512 mConstants.dumpLocked(pw);
13513 }
13514
Mike Ma234d1822018-03-13 18:53:21 -070013515 @GuardedBy("this")
13516 public void dumpCpuStatsLocked(PrintWriter pw) {
13517 int size = mUidStats.size();
13518 pw.println("Per UID CPU user & system time in ms:");
13519 for (int i = 0; i < size; i++) {
13520 int u = mUidStats.keyAt(i);
13521 Uid uid = mUidStats.get(u);
13522 pw.print(" "); pw.print(u); pw.print(": ");
13523 pw.print(uid.getUserCpuTimeUs(STATS_SINCE_CHARGED) / 1000); pw.print(" ");
13524 pw.println(uid.getSystemCpuTimeUs(STATS_SINCE_CHARGED) / 1000);
13525 }
13526 pw.println("Per UID CPU active time in ms:");
13527 for (int i = 0; i < size; i++) {
13528 int u = mUidStats.keyAt(i);
13529 Uid uid = mUidStats.get(u);
13530 if (uid.getCpuActiveTime() > 0) {
13531 pw.print(" "); pw.print(u); pw.print(": "); pw.println(uid.getCpuActiveTime());
13532 }
13533 }
13534 pw.println("Per UID CPU cluster time in ms:");
13535 for (int i = 0; i < size; i++) {
13536 int u = mUidStats.keyAt(i);
13537 long[] times = mUidStats.get(u).getCpuClusterTimes();
13538 if (times != null) {
13539 pw.print(" "); pw.print(u); pw.print(": "); pw.println(Arrays.toString(times));
13540 }
13541 }
13542 pw.println("Per UID CPU frequency time in ms:");
13543 for (int i = 0; i < size; i++) {
13544 int u = mUidStats.keyAt(i);
13545 long[] times = mUidStats.get(u).getCpuFreqTimes(STATS_SINCE_CHARGED);
13546 if (times != null) {
13547 pw.print(" "); pw.print(u); pw.print(": "); pw.println(Arrays.toString(times));
13548 }
13549 }
13550 }
13551
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013552 Parcel mPendingWrite = null;
13553 final ReentrantLock mWriteLock = new ReentrantLock();
13554
13555 public void writeAsyncLocked() {
13556 writeLocked(false);
13557 }
13558
13559 public void writeSyncLocked() {
13560 writeLocked(true);
13561 }
13562
13563 void writeLocked(boolean sync) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013564 if (mFile == null) {
13565 Slog.w("BatteryStats", "writeLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013566 return;
13567 }
13568
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013569 if (mShuttingDown) {
13570 return;
13571 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013572
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013573 Parcel out = Parcel.obtain();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013574 writeSummaryToParcel(out, true);
Joe Onoratoabded112016-02-08 16:49:39 -080013575 mLastWriteTime = mClocks.elapsedRealtime();
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013576
13577 if (mPendingWrite != null) {
13578 mPendingWrite.recycle();
13579 }
13580 mPendingWrite = out;
13581
13582 if (sync) {
13583 commitPendingDataToDisk();
13584 } else {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013585 BackgroundThread.getHandler().post(new Runnable() {
13586 @Override public void run() {
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013587 commitPendingDataToDisk();
13588 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013589 });
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013590 }
13591 }
13592
13593 public void commitPendingDataToDisk() {
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070013594 final Parcel next;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013595 synchronized (this) {
13596 next = mPendingWrite;
13597 mPendingWrite = null;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070013598 if (next == null) {
13599 return;
13600 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013601 }
13602
Amith Yamasanid2450862017-02-07 15:58:24 -080013603 mWriteLock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013604 try {
Dianne Hackborne17b4452018-01-10 13:15:40 -080013605 final long startTime = SystemClock.uptimeMillis();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013606 FileOutputStream stream = new FileOutputStream(mFile.chooseForWrite());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013607 stream.write(next.marshall());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013608 stream.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070013609 FileUtils.sync(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013610 stream.close();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013611 mFile.commit();
Dianne Hackborne17b4452018-01-10 13:15:40 -080013612 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
13613 "batterystats", SystemClock.uptimeMillis() - startTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013614 } catch (IOException e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013615 Slog.w("BatteryStats", "Error writing battery statistics", e);
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013616 mFile.rollback();
13617 } finally {
13618 next.recycle();
13619 mWriteLock.unlock();
Suchi Amalapurapu8550f252009-09-29 15:20:32 -070013620 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013621 }
13622
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013623 public void readLocked() {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013624 if (mDailyFile != null) {
13625 readDailyStatsLocked();
13626 }
13627
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013628 if (mFile == null) {
13629 Slog.w("BatteryStats", "readLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013630 return;
13631 }
13632
13633 mUidStats.clear();
13634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013635 try {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013636 File file = mFile.chooseForRead();
13637 if (!file.exists()) {
13638 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013639 }
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013640 FileInputStream stream = new FileInputStream(file);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013641
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013642 byte[] raw = BatteryStatsHelper.readFully(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013643 Parcel in = Parcel.obtain();
13644 in.unmarshall(raw, 0, raw.length);
13645 in.setDataPosition(0);
13646 stream.close();
13647
13648 readSummaryFromParcel(in);
Dianne Hackborn00e25212014-02-19 10:49:24 -080013649 } catch(Exception e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013650 Slog.e("BatteryStats", "Error reading battery statistics", e);
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013651 resetAllStatsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013652 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013653
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013654 mEndPlatformVersion = Build.ID;
13655
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013656 if (mHistoryBuffer.dataPosition() > 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013657 mRecordingHistory = true;
Joe Onoratoabded112016-02-08 16:49:39 -080013658 final long elapsedRealtime = mClocks.elapsedRealtime();
13659 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013660 if (USE_OLD_HISTORY) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013661 addHistoryRecordLocked(elapsedRealtime, uptime, HistoryItem.CMD_START, mHistoryCur);
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013662 }
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000013663 addHistoryBufferLocked(elapsedRealtime, HistoryItem.CMD_START, mHistoryCur);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013664 startRecordingHistory(elapsedRealtime, uptime, false);
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013665 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013666
13667 recordDailyStatsIfNeededLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013668 }
13669
13670 public int describeContents() {
13671 return 0;
13672 }
13673
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013674 void readHistory(Parcel in, boolean andOldHistory) throws ParcelFormatException {
Dianne Hackbornae384452011-06-28 12:33:48 -070013675 final long historyBaseTime = in.readLong();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013676
13677 mHistoryBuffer.setDataSize(0);
13678 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013679 mHistoryTagPool.clear();
13680 mNextHistoryTagIdx = 0;
13681 mNumHistoryTagChars = 0;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013682
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013683 int numTags = in.readInt();
13684 for (int i=0; i<numTags; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080013685 int idx = in.readInt();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013686 String str = in.readString();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013687 if (str == null) {
13688 throw new ParcelFormatException("null history tag string");
13689 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013690 int uid = in.readInt();
13691 HistoryTag tag = new HistoryTag();
13692 tag.string = str;
13693 tag.uid = uid;
13694 tag.poolIdx = idx;
13695 mHistoryTagPool.put(tag, idx);
13696 if (idx >= mNextHistoryTagIdx) {
13697 mNextHistoryTagIdx = idx+1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013698 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013699 mNumHistoryTagChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013700 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013701
13702 int bufSize = in.readInt();
13703 int curPos = in.dataPosition();
13704 if (bufSize >= (MAX_MAX_HISTORY_BUFFER*3)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013705 throw new ParcelFormatException("File corrupt: history data buffer too large " +
13706 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013707 } else if ((bufSize&~3) != bufSize) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013708 throw new ParcelFormatException("File corrupt: history data buffer not aligned " +
13709 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013710 } else {
13711 if (DEBUG_HISTORY) Slog.i(TAG, "***************** READING NEW HISTORY: " + bufSize
13712 + " bytes at " + curPos);
13713 mHistoryBuffer.appendFrom(in, curPos, bufSize);
13714 in.setDataPosition(curPos + bufSize);
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013715 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013716
Dianne Hackbornae384452011-06-28 12:33:48 -070013717 if (andOldHistory) {
13718 readOldHistory(in);
13719 }
13720
13721 if (DEBUG_HISTORY) {
13722 StringBuilder sb = new StringBuilder(128);
13723 sb.append("****************** OLD mHistoryBaseTime: ");
13724 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13725 Slog.i(TAG, sb.toString());
13726 }
13727 mHistoryBaseTime = historyBaseTime;
13728 if (DEBUG_HISTORY) {
13729 StringBuilder sb = new StringBuilder(128);
13730 sb.append("****************** NEW mHistoryBaseTime: ");
13731 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13732 Slog.i(TAG, sb.toString());
13733 }
13734
13735 // We are just arbitrarily going to insert 1 minute from the sample of
13736 // the last run until samples in this run.
13737 if (mHistoryBaseTime > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -080013738 long oldnow = mClocks.elapsedRealtime();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013739 mHistoryBaseTime = mHistoryBaseTime - oldnow + 1;
Dianne Hackbornae384452011-06-28 12:33:48 -070013740 if (DEBUG_HISTORY) {
13741 StringBuilder sb = new StringBuilder(128);
13742 sb.append("****************** ADJUSTED mHistoryBaseTime: ");
13743 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13744 Slog.i(TAG, sb.toString());
13745 }
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -070013746 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013747 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013748
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013749 void readOldHistory(Parcel in) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013750 if (!USE_OLD_HISTORY) {
13751 return;
13752 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013753 mHistory = mHistoryEnd = mHistoryCache = null;
13754 long time;
Conley Owens5e3357f2011-05-02 09:59:30 -070013755 while (in.dataAvail() > 0 && (time=in.readLong()) >= 0) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013756 HistoryItem rec = new HistoryItem(time, in);
13757 addHistoryRecordLocked(rec);
13758 }
13759 }
13760
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013761 void writeHistory(Parcel out, boolean inclData, boolean andOldHistory) {
Dianne Hackbornae384452011-06-28 12:33:48 -070013762 if (DEBUG_HISTORY) {
13763 StringBuilder sb = new StringBuilder(128);
13764 sb.append("****************** WRITING mHistoryBaseTime: ");
13765 TimeUtils.formatDuration(mHistoryBaseTime, sb);
Dianne Hackborn40c87252014-03-19 16:55:40 -070013766 sb.append(" mLastHistoryElapsedRealtime: ");
13767 TimeUtils.formatDuration(mLastHistoryElapsedRealtime, sb);
Dianne Hackbornae384452011-06-28 12:33:48 -070013768 Slog.i(TAG, sb.toString());
13769 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070013770 out.writeLong(mHistoryBaseTime + mLastHistoryElapsedRealtime);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013771 if (!inclData) {
13772 out.writeInt(0);
13773 out.writeInt(0);
13774 return;
13775 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013776 out.writeInt(mHistoryTagPool.size());
13777 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
13778 HistoryTag tag = ent.getKey();
Dianne Hackborn099bc622014-01-22 13:39:16 -080013779 out.writeInt(ent.getValue());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013780 out.writeString(tag.string);
13781 out.writeInt(tag.uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -080013782 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013783 out.writeInt(mHistoryBuffer.dataSize());
13784 if (DEBUG_HISTORY) Slog.i(TAG, "***************** WRITING HISTORY: "
13785 + mHistoryBuffer.dataSize() + " bytes at " + out.dataPosition());
13786 out.appendFrom(mHistoryBuffer, 0, mHistoryBuffer.dataSize());
Dianne Hackbornae384452011-06-28 12:33:48 -070013787
13788 if (andOldHistory) {
13789 writeOldHistory(out);
13790 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013791 }
13792
13793 void writeOldHistory(Parcel out) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013794 if (!USE_OLD_HISTORY) {
13795 return;
13796 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013797 HistoryItem rec = mHistory;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013798 while (rec != null) {
13799 if (rec.time >= 0) rec.writeToParcel(out, 0);
13800 rec = rec.next;
13801 }
13802 out.writeLong(-1);
13803 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013804
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013805 public void readSummaryFromParcel(Parcel in) throws ParcelFormatException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013806 final int version = in.readInt();
13807 if (version != VERSION) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013808 Slog.w("BatteryStats", "readFromParcel: version got " + version
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013809 + ", expected " + VERSION + "; erasing old stats");
13810 return;
13811 }
13812
Dianne Hackbornae384452011-06-28 12:33:48 -070013813 readHistory(in, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013815 mStartCount = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013816 mUptime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013817 mRealtime = in.readLong();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080013818 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013819 mStartPlatformVersion = in.readString();
13820 mEndPlatformVersion = in.readString();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013821 mOnBatteryTimeBase.readSummaryFromParcel(in);
13822 mOnBatteryScreenOffTimeBase.readSummaryFromParcel(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013823 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013824 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070013825 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013826 mCurrentBatteryLevel = in.readInt();
Adam Lesinskif9b20a92016-06-17 17:30:01 -070013827 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070013828 mMinLearnedBatteryCapacity = in.readInt();
13829 mMaxLearnedBatteryCapacity = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013830 mLowDischargeAmountSinceCharge = in.readInt();
13831 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013832 mDischargeAmountScreenOnSinceCharge = in.readInt();
13833 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070013834 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013835 mDischargeStepTracker.readFromParcel(in);
13836 mChargeStepTracker.readFromParcel(in);
13837 mDailyDischargeStepTracker.readFromParcel(in);
13838 mDailyChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070013839 mDischargeCounter.readSummaryFromParcelLocked(in);
13840 mDischargeScreenOffCounter.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070013841 mDischargeScreenDozeCounter.readSummaryFromParcelLocked(in);
Mike Ma15313c92017-11-15 17:58:21 -080013842 mDischargeLightDozeCounter.readSummaryFromParcelLocked(in);
13843 mDischargeDeepDozeCounter.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013844 int NPKG = in.readInt();
13845 if (NPKG > 0) {
13846 mDailyPackageChanges = new ArrayList<>(NPKG);
13847 while (NPKG > 0) {
13848 NPKG--;
13849 PackageChange pc = new PackageChange();
13850 pc.mPackageName = in.readString();
13851 pc.mUpdate = in.readInt() != 0;
Dianne Hackborn3accca02013-09-20 09:32:11 -070013852 pc.mVersionCode = in.readLong();
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013853 mDailyPackageChanges.add(pc);
13854 }
13855 } else {
13856 mDailyPackageChanges = null;
13857 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013858 mDailyStartTime = in.readLong();
13859 mNextMinDailyDeadline = in.readLong();
13860 mNextMaxDailyDeadline = in.readLong();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013862 mStartCount++;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013863
Jeff Browne95c3cd2014-05-02 16:59:26 -070013864 mScreenState = Display.STATE_UNKNOWN;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013865 mScreenOnTimer.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070013866 mScreenDozeTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn617f8772009-03-31 15:04:46 -070013867 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
13868 mScreenBrightnessTimer[i].readSummaryFromParcelLocked(in);
13869 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070013870 mInteractive = false;
13871 mInteractiveTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013872 mPhoneOn = false;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070013873 mPowerSaveModeEnabledTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070013874 mLongestLightIdleTime = in.readLong();
13875 mLongestFullIdleTime = in.readLong();
13876 mDeviceIdleModeLightTimer.readSummaryFromParcelLocked(in);
13877 mDeviceIdleModeFullTimer.readSummaryFromParcelLocked(in);
13878 mDeviceLightIdlingTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013879 mDeviceIdlingTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013880 mPhoneOnTimer.readSummaryFromParcelLocked(in);
Wink Saville52840902011-02-18 12:40:47 -080013881 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn627bba72009-03-24 22:32:56 -070013882 mPhoneSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
13883 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070013884 mPhoneSignalScanningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013885 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
13886 mPhoneDataConnectionsTimer[i].readSummaryFromParcelLocked(in);
13887 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013888 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013889 mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
13890 mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013891 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013892 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborne13c4c02014-02-11 17:18:35 -080013893 mMobileRadioActiveTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080013894 mMobileRadioActivePerAppTimer.readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013895 mMobileRadioActiveAdjustedTime.readSummaryFromParcelLocked(in);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013896 mMobileRadioActiveUnknownTime.readSummaryFromParcelLocked(in);
13897 mMobileRadioActiveUnknownCount.readSummaryFromParcelLocked(in);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080013898 mWifiMulticastWakelockTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070013899 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
The Android Open Source Project10592532009-03-18 17:39:46 -070013900 mWifiOn = false;
13901 mWifiOnTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013902 mGlobalWifiRunning = false;
13903 mGlobalWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080013904 for (int i=0; i<NUM_WIFI_STATES; i++) {
13905 mWifiStateTimer[i].readSummaryFromParcelLocked(in);
13906 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070013907 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
13908 mWifiSupplStateTimer[i].readSummaryFromParcelLocked(in);
13909 }
13910 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
13911 mWifiSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
13912 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080013913 mWifiActiveTimer.readSummaryFromParcelLocked(in);
13914 mWifiActivity.readSummaryFromParcel(in);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080013915 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
13916 mGpsSignalQualityTimer[i].readSummaryFromParcelLocked(in);
13917 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080013918 mBluetoothActivity.readSummaryFromParcel(in);
13919 mModemActivity.readSummaryFromParcel(in);
13920 mHasWifiReporting = in.readInt() != 0;
13921 mHasBluetoothReporting = in.readInt() != 0;
13922 mHasModemReporting = in.readInt() != 0;
Adam Lesinski33dac552015-03-09 15:24:48 -070013923
Dianne Hackborn1e01d162014-12-04 17:46:42 -080013924 mNumConnectivityChange = mLoadedNumConnectivityChange = in.readInt();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013925 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -070013926 mFlashlightOnTimer.readSummaryFromParcelLocked(in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013927 mCameraOnNesting = 0;
13928 mCameraOnTimer.readSummaryFromParcelLocked(in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013929 mBluetoothScanNesting = 0;
13930 mBluetoothScanTimer.readSummaryFromParcelLocked(in);
Siddharth Rayf5e796a2018-01-22 18:18:17 -080013931 mIsCellularTxPowerHigh = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013932
Bookatz50df7112017-08-04 14:53:26 -070013933 int NRPMS = in.readInt();
13934 if (NRPMS > 10000) {
13935 throw new ParcelFormatException("File corrupt: too many rpm stats " + NRPMS);
13936 }
13937 for (int irpm = 0; irpm < NRPMS; irpm++) {
13938 if (in.readInt() != 0) {
13939 String rpmName = in.readString();
13940 getRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
13941 }
13942 }
13943 int NSORPMS = in.readInt();
13944 if (NSORPMS > 10000) {
13945 throw new ParcelFormatException("File corrupt: too many screen-off rpm stats " + NSORPMS);
13946 }
13947 for (int irpm = 0; irpm < NSORPMS; irpm++) {
13948 if (in.readInt() != 0) {
13949 String rpmName = in.readString();
13950 getScreenOffRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
13951 }
13952 }
13953
Evan Millarc64edde2009-04-18 12:26:32 -070013954 int NKW = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013955 if (NKW > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013956 throw new ParcelFormatException("File corrupt: too many kernel wake locks " + NKW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013957 }
Evan Millarc64edde2009-04-18 12:26:32 -070013958 for (int ikw = 0; ikw < NKW; ikw++) {
13959 if (in.readInt() != 0) {
13960 String kwltName = in.readString();
13961 getKernelWakelockTimerLocked(kwltName).readSummaryFromParcelLocked(in);
13962 }
13963 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070013964
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013965 int NWR = in.readInt();
13966 if (NWR > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013967 throw new ParcelFormatException("File corrupt: too many wakeup reasons " + NWR);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013968 }
13969 for (int iwr = 0; iwr < NWR; iwr++) {
13970 if (in.readInt() != 0) {
13971 String reasonName = in.readString();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070013972 getWakeupReasonTimerLocked(reasonName).readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013973 }
13974 }
13975
James Carr3a226052016-07-01 14:49:52 -070013976 int NMS = in.readInt();
13977 for (int ims = 0; ims < NMS; ims++) {
13978 if (in.readInt() != 0) {
13979 long kmstName = in.readLong();
13980 getKernelMemoryTimerLocked(kmstName).readSummaryFromParcelLocked(in);
13981 }
13982 }
13983
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013984 final int NU = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013985 if (NU > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013986 throw new ParcelFormatException("File corrupt: too many uids " + NU);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013987 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013988 for (int iu = 0; iu < NU; iu++) {
13989 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080013990 Uid u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013991 mUidStats.put(uid, u);
13992
Bookatz867c0d72017-03-07 18:23:42 -080013993 u.mOnBatteryBackgroundTimeBase.readSummaryFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -070013994 u.mOnBatteryScreenOffBackgroundTimeBase.readSummaryFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -080013995
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013996 u.mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013997 if (in.readInt() != 0) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013998 u.mWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013999 }
The Android Open Source Project10592532009-03-18 17:39:46 -070014000 u.mFullWifiLockOut = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014001 if (in.readInt() != 0) {
14002 u.mFullWifiLockTimer.readSummaryFromParcelLocked(in);
14003 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070014004 u.mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014005 if (in.readInt() != 0) {
Nick Pelly6ccaa542012-06-15 15:22:47 -070014006 u.mWifiScanTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014007 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070014008 u.mWifiBatchedScanBinStarted = Uid.NO_BATCHED_SCAN_STARTED;
14009 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
14010 if (in.readInt() != 0) {
14011 u.makeWifiBatchedScanBin(i, null);
14012 u.mWifiBatchedScanTimer[i].readSummaryFromParcelLocked(in);
14013 }
14014 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070014015 u.mWifiMulticastEnabled = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014016 if (in.readInt() != 0) {
14017 u.mWifiMulticastTimer.readSummaryFromParcelLocked(in);
14018 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014019 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014020 u.createAudioTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014021 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014022 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014023 u.createVideoTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
14024 }
14025 if (in.readInt() != 0) {
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014026 u.createFlashlightTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
14027 }
14028 if (in.readInt() != 0) {
14029 u.createCameraTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
14030 }
14031 if (in.readInt() != 0) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014032 u.createForegroundActivityTimerLocked().readSummaryFromParcelLocked(in);
14033 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014034 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070014035 u.createForegroundServiceTimerLocked().readSummaryFromParcelLocked(in);
14036 }
14037 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -070014038 u.createAggregatedPartialWakelockTimerLocked().readSummaryFromParcelLocked(in);
14039 }
14040 if (in.readInt() != 0) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014041 u.createBluetoothScanTimerLocked().readSummaryFromParcelLocked(in);
14042 }
Bookatz956f36bf2017-04-28 09:48:17 -070014043 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -070014044 u.createBluetoothUnoptimizedScanTimerLocked().readSummaryFromParcelLocked(in);
14045 }
14046 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -070014047 u.createBluetoothScanResultCounterLocked().readSummaryFromParcelLocked(in);
14048 }
Bookatzb1f04f32017-05-19 13:57:32 -070014049 if (in.readInt() != 0) {
14050 u.createBluetoothScanResultBgCounterLocked().readSummaryFromParcelLocked(in);
14051 }
Dianne Hackborna8d10942015-11-19 17:55:19 -080014052 u.mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -070014053 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
14054 if (in.readInt() != 0) {
14055 u.makeProcessState(i, null);
14056 u.mProcessStateTimer[i].readSummaryFromParcelLocked(in);
14057 }
14058 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014059 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014060 u.createVibratorOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014061 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070014062
Dianne Hackborn617f8772009-03-31 15:04:46 -070014063 if (in.readInt() != 0) {
14064 if (u.mUserActivityCounters == null) {
14065 u.initUserActivityLocked();
14066 }
14067 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
14068 u.mUserActivityCounters[i].readSummaryFromParcelLocked(in);
14069 }
14070 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014071
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014072 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014073 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014074 u.initNetworkActivityLocked();
14075 }
14076 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014077 u.mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
14078 u.mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014079 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080014080 u.mMobileRadioActiveTime.readSummaryFromParcelLocked(in);
14081 u.mMobileRadioActiveCount.readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014082 }
14083
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014084 u.mUserCpuTime.readSummaryFromParcelLocked(in);
14085 u.mSystemCpuTime.readSummaryFromParcelLocked(in);
14086
Adam Lesinski6832f392015-09-05 18:05:40 -070014087 if (in.readInt() != 0) {
14088 final int numClusters = in.readInt();
14089 if (mPowerProfile != null && mPowerProfile.getNumCpuClusters() != numClusters) {
14090 throw new ParcelFormatException("Incompatible cpu cluster arrangement");
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014091 }
Adam Lesinski6832f392015-09-05 18:05:40 -070014092
Sudheer Shankaaf857412017-07-21 00:14:24 -070014093 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -070014094 for (int cluster = 0; cluster < numClusters; cluster++) {
Adam Lesinski6832f392015-09-05 18:05:40 -070014095 if (in.readInt() != 0) {
Adam Lesinskia57a5402015-09-28 10:21:33 -070014096 final int NSB = in.readInt();
14097 if (mPowerProfile != null &&
14098 mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != NSB) {
14099 throw new ParcelFormatException("File corrupt: too many speed bins " +
14100 NSB);
14101 }
14102
Sudheer Shankaaf857412017-07-21 00:14:24 -070014103 u.mCpuClusterSpeedTimesUs[cluster] = new LongSamplingCounter[NSB];
Adam Lesinski6832f392015-09-05 18:05:40 -070014104 for (int speed = 0; speed < NSB; speed++) {
14105 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070014106 u.mCpuClusterSpeedTimesUs[cluster][speed] = new LongSamplingCounter(
Adam Lesinski6832f392015-09-05 18:05:40 -070014107 mOnBatteryTimeBase);
Sudheer Shankaaf857412017-07-21 00:14:24 -070014108 u.mCpuClusterSpeedTimesUs[cluster][speed].readSummaryFromParcelLocked(in);
Adam Lesinski6832f392015-09-05 18:05:40 -070014109 }
14110 }
Adam Lesinskia57a5402015-09-28 10:21:33 -070014111 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070014112 u.mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -070014113 }
14114 }
14115 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070014116 u.mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014117 }
14118
Sudheer Shanka59f5c002017-05-15 10:57:15 -070014119 u.mCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
14120 in, mOnBatteryTimeBase);
14121 u.mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
14122 in, mOnBatteryScreenOffTimeBase);
Mike Ma3d422c32017-10-25 11:08:57 -070014123
14124 u.mCpuActiveTimeMs.readSummaryFromParcelLocked(in);
14125 u.mCpuClusterTimesMs.readSummaryFromParcelLocked(in);
14126
Sudheer Shankab2f83c12017-11-13 19:25:01 -080014127 int length = in.readInt();
14128 if (length == Uid.NUM_PROCESS_STATE) {
14129 u.mProcStateTimeMs = new LongSamplingCounterArray[length];
14130 for (int procState = 0; procState < length; ++procState) {
14131 u.mProcStateTimeMs[procState]
14132 = LongSamplingCounterArray.readSummaryFromParcelLocked(
14133 in, mOnBatteryTimeBase);
14134 }
14135 } else {
14136 u.mProcStateTimeMs = null;
14137 }
14138 length = in.readInt();
14139 if (length == Uid.NUM_PROCESS_STATE) {
14140 u.mProcStateScreenOffTimeMs = new LongSamplingCounterArray[length];
14141 for (int procState = 0; procState < length; ++procState) {
14142 u.mProcStateScreenOffTimeMs[procState]
14143 = LongSamplingCounterArray.readSummaryFromParcelLocked(
14144 in, mOnBatteryScreenOffTimeBase);
14145 }
14146 } else {
14147 u.mProcStateScreenOffTimeMs = null;
14148 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070014149
14150 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -070014151 u.mMobileRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
14152 u.mMobileRadioApWakeupCount.readSummaryFromParcelLocked(in);
14153 } else {
14154 u.mMobileRadioApWakeupCount = null;
14155 }
14156
14157 if (in.readInt() != 0) {
14158 u.mWifiRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
14159 u.mWifiRadioApWakeupCount.readSummaryFromParcelLocked(in);
14160 } else {
14161 u.mWifiRadioApWakeupCount = null;
14162 }
14163
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014164 int NW = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070014165 if (NW > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014166 throw new ParcelFormatException("File corrupt: too many wake locks " + NW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014167 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014168 for (int iw = 0; iw < NW; iw++) {
14169 String wlName = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014170 u.readWakeSummaryFromParcelLocked(wlName, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014171 }
14172
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014173 int NS = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070014174 if (NS > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014175 throw new ParcelFormatException("File corrupt: too many syncs " + NS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014176 }
14177 for (int is = 0; is < NS; is++) {
14178 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014179 u.readSyncSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014180 }
14181
14182 int NJ = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070014183 if (NJ > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014184 throw new ParcelFormatException("File corrupt: too many job timers " + NJ);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014185 }
14186 for (int ij = 0; ij < NJ; ij++) {
14187 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014188 u.readJobSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014189 }
14190
Dianne Hackborn94326cb2017-06-28 16:17:20 -070014191 u.readJobCompletionsFromParcelLocked(in);
14192
Amith Yamasani977e11f2018-02-16 11:29:54 -080014193 u.mJobsDeferredEventCount.readSummaryFromParcelLocked(in);
14194 u.mJobsDeferredCount.readSummaryFromParcelLocked(in);
14195 u.mJobsFreshnessTimeMs.readSummaryFromParcelLocked(in);
14196 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
14197 if (in.readInt() != 0) {
14198 u.mJobsFreshnessBuckets[i] = new Counter(u.mBsi.mOnBatteryTimeBase);
14199 u.mJobsFreshnessBuckets[i].readSummaryFromParcelLocked(in);
14200 }
14201 }
14202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014203 int NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014204 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014205 throw new ParcelFormatException("File corrupt: too many sensors " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014206 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014207 for (int is = 0; is < NP; is++) {
14208 int seNumber = in.readInt();
14209 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -080014210 u.getSensorTimerLocked(seNumber, true).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014211 }
14212 }
14213
14214 NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014215 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014216 throw new ParcelFormatException("File corrupt: too many processes " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014217 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014218 for (int ip = 0; ip < NP; ip++) {
14219 String procName = in.readString();
14220 Uid.Proc p = u.getProcessStatsLocked(procName);
14221 p.mUserTime = p.mLoadedUserTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014222 p.mSystemTime = p.mLoadedSystemTime = in.readLong();
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014223 p.mForegroundTime = p.mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014224 p.mStarts = p.mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014225 p.mNumCrashes = p.mLoadedNumCrashes = in.readInt();
14226 p.mNumAnrs = p.mLoadedNumAnrs = in.readInt();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014227 p.readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014228 }
14229
14230 NP = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014231 if (NP > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014232 throw new ParcelFormatException("File corrupt: too many packages " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014233 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014234 for (int ip = 0; ip < NP; ip++) {
14235 String pkgName = in.readString();
14236 Uid.Pkg p = u.getPackageStatsLocked(pkgName);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014237 final int NWA = in.readInt();
14238 if (NWA > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014239 throw new ParcelFormatException("File corrupt: too many wakeup alarms " + NWA);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014240 }
14241 p.mWakeupAlarms.clear();
14242 for (int iwa=0; iwa<NWA; iwa++) {
14243 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -070014244 Counter c = new Counter(mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014245 c.readSummaryFromParcelLocked(in);
14246 p.mWakeupAlarms.put(tag, c);
14247 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014248 NS = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014249 if (NS > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014250 throw new ParcelFormatException("File corrupt: too many services " + NS);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014251 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014252 for (int is = 0; is < NS; is++) {
14253 String servName = in.readString();
14254 Uid.Pkg.Serv s = u.getServiceStatsLocked(pkgName, servName);
14255 s.mStartTime = s.mLoadedStartTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014256 s.mStarts = s.mLoadedStarts = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014257 s.mLaunches = s.mLoadedLaunches = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014258 }
14259 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014260 }
14261 }
14262
14263 /**
14264 * Writes a summary of the statistics to a Parcel, in a format suitable to be written to
14265 * disk. This format does not allow a lossless round-trip.
14266 *
14267 * @param out the Parcel to be written to.
14268 */
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070014269 public void writeSummaryToParcel(Parcel out, boolean inclHistory) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080014270 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014271
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014272 // Pull the clock time. This may update the time and make a new history entry
14273 // if we had originally pulled a time before the RTC was set.
14274 long startClockTime = getStartClockTime();
14275
Joe Onoratoabded112016-02-08 16:49:39 -080014276 final long NOW_SYS = mClocks.uptimeMillis() * 1000;
14277 final long NOWREAL_SYS = mClocks.elapsedRealtime() * 1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014278
14279 out.writeInt(VERSION);
14280
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070014281 writeHistory(out, inclHistory, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014283 out.writeInt(mStartCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014284 out.writeLong(computeUptime(NOW_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014285 out.writeLong(computeRealtime(NOWREAL_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014286 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014287 out.writeString(mStartPlatformVersion);
14288 out.writeString(mEndPlatformVersion);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014289 mOnBatteryTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
14290 mOnBatteryScreenOffTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014291 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014292 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070014293 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014294 out.writeInt(mCurrentBatteryLevel);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014295 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070014296 out.writeInt(mMinLearnedBatteryCapacity);
14297 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborne4a59512010-12-07 11:08:07 -080014298 out.writeInt(getLowDischargeAmountSinceCharge());
14299 out.writeInt(getHighDischargeAmountSinceCharge());
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014300 out.writeInt(getDischargeAmountScreenOnSinceCharge());
14301 out.writeInt(getDischargeAmountScreenOffSinceCharge());
Mike Mac2f518a2017-09-19 16:06:03 -070014302 out.writeInt(getDischargeAmountScreenDozeSinceCharge());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014303 mDischargeStepTracker.writeToParcel(out);
14304 mChargeStepTracker.writeToParcel(out);
14305 mDailyDischargeStepTracker.writeToParcel(out);
14306 mDailyChargeStepTracker.writeToParcel(out);
Adam Lesinski67c134f2016-06-10 15:15:08 -070014307 mDischargeCounter.writeSummaryFromParcelLocked(out);
14308 mDischargeScreenOffCounter.writeSummaryFromParcelLocked(out);
Mike Mac2f518a2017-09-19 16:06:03 -070014309 mDischargeScreenDozeCounter.writeSummaryFromParcelLocked(out);
Mike Ma15313c92017-11-15 17:58:21 -080014310 mDischargeLightDozeCounter.writeSummaryFromParcelLocked(out);
14311 mDischargeDeepDozeCounter.writeSummaryFromParcelLocked(out);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014312 if (mDailyPackageChanges != null) {
14313 final int NPKG = mDailyPackageChanges.size();
14314 out.writeInt(NPKG);
14315 for (int i=0; i<NPKG; i++) {
14316 PackageChange pc = mDailyPackageChanges.get(i);
14317 out.writeString(pc.mPackageName);
14318 out.writeInt(pc.mUpdate ? 1 : 0);
Dianne Hackborn3accca02013-09-20 09:32:11 -070014319 out.writeLong(pc.mVersionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014320 }
14321 } else {
14322 out.writeInt(0);
14323 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014324 out.writeLong(mDailyStartTime);
14325 out.writeLong(mNextMinDailyDeadline);
14326 out.writeLong(mNextMaxDailyDeadline);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014327
14328 mScreenOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Mike Mac2f518a2017-09-19 16:06:03 -070014329 mScreenDozeTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070014330 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014331 mScreenBrightnessTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070014332 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070014333 mInteractiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070014334 mPowerSaveModeEnabledTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014335 out.writeLong(mLongestLightIdleTime);
14336 out.writeLong(mLongestFullIdleTime);
14337 mDeviceIdleModeLightTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14338 mDeviceIdleModeFullTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14339 mDeviceLightIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014340 mDeviceIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014341 mPhoneOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Wink Saville52840902011-02-18 12:40:47 -080014342 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014343 mPhoneSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070014344 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014345 mPhoneSignalScanningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070014346 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014347 mPhoneDataConnectionsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070014348 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014349 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014350 mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
14351 mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014352 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014353 mMobileRadioActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14354 mMobileRadioActivePerAppTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014355 mMobileRadioActiveAdjustedTime.writeSummaryFromParcelLocked(out);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080014356 mMobileRadioActiveUnknownTime.writeSummaryFromParcelLocked(out);
14357 mMobileRadioActiveUnknownCount.writeSummaryFromParcelLocked(out);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014358 mWifiMulticastWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014359 mWifiOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14360 mGlobalWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080014361 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014362 mWifiStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080014363 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014364 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
14365 mWifiSupplStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14366 }
14367 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
14368 mWifiSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14369 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014370 mWifiActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14371 mWifiActivity.writeSummaryToParcel(out);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014372 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14373 mGpsSignalQualityTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14374 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014375 mBluetoothActivity.writeSummaryToParcel(out);
14376 mModemActivity.writeSummaryToParcel(out);
14377 out.writeInt(mHasWifiReporting ? 1 : 0);
14378 out.writeInt(mHasBluetoothReporting ? 1 : 0);
14379 out.writeInt(mHasModemReporting ? 1 : 0);
14380
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014381 out.writeInt(mNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070014382 mFlashlightOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014383 mCameraOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014384 mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014385
Bookatz50df7112017-08-04 14:53:26 -070014386 out.writeInt(mRpmStats.size());
14387 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
14388 Timer rpmt = ent.getValue();
14389 if (rpmt != null) {
14390 out.writeInt(1);
14391 out.writeString(ent.getKey());
14392 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14393 } else {
14394 out.writeInt(0);
14395 }
14396 }
14397 out.writeInt(mScreenOffRpmStats.size());
14398 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
14399 Timer rpmt = ent.getValue();
14400 if (rpmt != null) {
14401 out.writeInt(1);
14402 out.writeString(ent.getKey());
14403 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14404 } else {
14405 out.writeInt(0);
14406 }
14407 }
14408
Evan Millarc64edde2009-04-18 12:26:32 -070014409 out.writeInt(mKernelWakelockStats.size());
14410 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
14411 Timer kwlt = ent.getValue();
14412 if (kwlt != null) {
14413 out.writeInt(1);
14414 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014415 kwlt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14416 } else {
14417 out.writeInt(0);
14418 }
14419 }
14420
14421 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014422 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
14423 SamplingTimer timer = ent.getValue();
14424 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014425 out.writeInt(1);
14426 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014427 timer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Evan Millarc64edde2009-04-18 12:26:32 -070014428 } else {
14429 out.writeInt(0);
14430 }
14431 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014432
James Carr3a226052016-07-01 14:49:52 -070014433 out.writeInt(mKernelMemoryStats.size());
14434 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
14435 Timer kmt = mKernelMemoryStats.valueAt(i);
14436 if (kmt != null) {
14437 out.writeInt(1);
14438 out.writeLong(mKernelMemoryStats.keyAt(i));
14439 kmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14440 } else {
14441 out.writeInt(0);
14442 }
14443 }
14444
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014445 final int NU = mUidStats.size();
14446 out.writeInt(NU);
14447 for (int iu = 0; iu < NU; iu++) {
14448 out.writeInt(mUidStats.keyAt(iu));
14449 Uid u = mUidStats.valueAt(iu);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014450
Bookatz867c0d72017-03-07 18:23:42 -080014451 u.mOnBatteryBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatzc8c44962017-05-11 12:12:54 -070014452 u.mOnBatteryScreenOffBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatz867c0d72017-03-07 18:23:42 -080014453
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014454 if (u.mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014455 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014456 u.mWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014457 } else {
14458 out.writeInt(0);
14459 }
14460 if (u.mFullWifiLockTimer != null) {
14461 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014462 u.mFullWifiLockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014463 } else {
14464 out.writeInt(0);
14465 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070014466 if (u.mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014467 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014468 u.mWifiScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014469 } else {
14470 out.writeInt(0);
14471 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070014472 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
14473 if (u.mWifiBatchedScanTimer[i] != null) {
14474 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014475 u.mWifiBatchedScanTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Robert Greenwalta029ea12013-09-25 16:38:12 -070014476 } else {
14477 out.writeInt(0);
14478 }
14479 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014480 if (u.mWifiMulticastTimer != null) {
14481 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014482 u.mWifiMulticastTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014483 } else {
14484 out.writeInt(0);
14485 }
14486 if (u.mAudioTurnedOnTimer != null) {
14487 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014488 u.mAudioTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014489 } else {
14490 out.writeInt(0);
14491 }
14492 if (u.mVideoTurnedOnTimer != null) {
14493 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014494 u.mVideoTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014495 } else {
14496 out.writeInt(0);
14497 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014498 if (u.mFlashlightTurnedOnTimer != null) {
14499 out.writeInt(1);
14500 u.mFlashlightTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14501 } else {
14502 out.writeInt(0);
14503 }
14504 if (u.mCameraTurnedOnTimer != null) {
14505 out.writeInt(1);
14506 u.mCameraTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14507 } else {
14508 out.writeInt(0);
14509 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014510 if (u.mForegroundActivityTimer != null) {
14511 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014512 u.mForegroundActivityTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014513 } else {
14514 out.writeInt(0);
14515 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070014516 if (u.mForegroundServiceTimer != null) {
14517 out.writeInt(1);
14518 u.mForegroundServiceTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14519 } else {
14520 out.writeInt(0);
14521 }
Bookatzc8c44962017-05-11 12:12:54 -070014522 if (u.mAggregatedPartialWakelockTimer != null) {
14523 out.writeInt(1);
14524 u.mAggregatedPartialWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14525 } else {
14526 out.writeInt(0);
14527 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014528 if (u.mBluetoothScanTimer != null) {
14529 out.writeInt(1);
14530 u.mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14531 } else {
14532 out.writeInt(0);
14533 }
Bookatzb1f04f32017-05-19 13:57:32 -070014534 if (u.mBluetoothUnoptimizedScanTimer != null) {
14535 out.writeInt(1);
14536 u.mBluetoothUnoptimizedScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14537 } else {
14538 out.writeInt(0);
14539 }
Bookatz956f36bf2017-04-28 09:48:17 -070014540 if (u.mBluetoothScanResultCounter != null) {
14541 out.writeInt(1);
14542 u.mBluetoothScanResultCounter.writeSummaryFromParcelLocked(out);
14543 } else {
14544 out.writeInt(0);
14545 }
Bookatzb1f04f32017-05-19 13:57:32 -070014546 if (u.mBluetoothScanResultBgCounter != null) {
14547 out.writeInt(1);
14548 u.mBluetoothScanResultBgCounter.writeSummaryFromParcelLocked(out);
14549 } else {
14550 out.writeInt(0);
14551 }
Dianne Hackborn61659e52014-07-09 16:13:01 -070014552 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
14553 if (u.mProcessStateTimer[i] != null) {
14554 out.writeInt(1);
14555 u.mProcessStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14556 } else {
14557 out.writeInt(0);
14558 }
14559 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014560 if (u.mVibratorOnTimer != null) {
14561 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014562 u.mVibratorOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014563 } else {
14564 out.writeInt(0);
14565 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014566
Dianne Hackborn617f8772009-03-31 15:04:46 -070014567 if (u.mUserActivityCounters == null) {
14568 out.writeInt(0);
14569 } else {
14570 out.writeInt(1);
14571 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
14572 u.mUserActivityCounters[i].writeSummaryFromParcelLocked(out);
14573 }
14574 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014575
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014576 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014577 out.writeInt(0);
14578 } else {
14579 out.writeInt(1);
14580 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014581 u.mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
14582 u.mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014583 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080014584 u.mMobileRadioActiveTime.writeSummaryFromParcelLocked(out);
14585 u.mMobileRadioActiveCount.writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014586 }
14587
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014588 u.mUserCpuTime.writeSummaryFromParcelLocked(out);
14589 u.mSystemCpuTime.writeSummaryFromParcelLocked(out);
14590
Sudheer Shankaaf857412017-07-21 00:14:24 -070014591 if (u.mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -070014592 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -070014593 out.writeInt(u.mCpuClusterSpeedTimesUs.length);
14594 for (LongSamplingCounter[] cpuSpeeds : u.mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -070014595 if (cpuSpeeds != null) {
14596 out.writeInt(1);
14597 out.writeInt(cpuSpeeds.length);
14598 for (LongSamplingCounter c : cpuSpeeds) {
14599 if (c != null) {
14600 out.writeInt(1);
14601 c.writeSummaryFromParcelLocked(out);
14602 } else {
14603 out.writeInt(0);
14604 }
14605 }
14606 } else {
14607 out.writeInt(0);
14608 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014609 }
Adam Lesinski6832f392015-09-05 18:05:40 -070014610 } else {
14611 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014612 }
14613
Sudheer Shanka59f5c002017-05-15 10:57:15 -070014614 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mCpuFreqTimeMs);
14615 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mScreenOffCpuFreqTimeMs);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070014616
Mike Ma3d422c32017-10-25 11:08:57 -070014617 u.mCpuActiveTimeMs.writeSummaryFromParcelLocked(out);
14618 u.mCpuClusterTimesMs.writeSummaryToParcelLocked(out);
14619
Sudheer Shankab2f83c12017-11-13 19:25:01 -080014620 if (u.mProcStateTimeMs != null) {
14621 out.writeInt(u.mProcStateTimeMs.length);
14622 for (LongSamplingCounterArray counters : u.mProcStateTimeMs) {
14623 LongSamplingCounterArray.writeSummaryToParcelLocked(out, counters);
14624 }
14625 } else {
14626 out.writeInt(0);
14627 }
14628 if (u.mProcStateScreenOffTimeMs != null) {
14629 out.writeInt(u.mProcStateScreenOffTimeMs.length);
14630 for (LongSamplingCounterArray counters : u.mProcStateScreenOffTimeMs) {
14631 LongSamplingCounterArray.writeSummaryToParcelLocked(out, counters);
14632 }
14633 } else {
14634 out.writeInt(0);
14635 }
14636
Adam Lesinski5f056f62016-07-14 16:56:08 -070014637 if (u.mMobileRadioApWakeupCount != null) {
14638 out.writeInt(1);
14639 u.mMobileRadioApWakeupCount.writeSummaryFromParcelLocked(out);
14640 } else {
14641 out.writeInt(0);
14642 }
14643
14644 if (u.mWifiRadioApWakeupCount != null) {
14645 out.writeInt(1);
14646 u.mWifiRadioApWakeupCount.writeSummaryFromParcelLocked(out);
14647 } else {
14648 out.writeInt(0);
14649 }
14650
Dianne Hackbornd953c532014-08-16 18:17:38 -070014651 final ArrayMap<String, Uid.Wakelock> wakeStats = u.mWakelockStats.getMap();
14652 int NW = wakeStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014653 out.writeInt(NW);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014654 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014655 out.writeString(wakeStats.keyAt(iw));
14656 Uid.Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014657 if (wl.mTimerFull != null) {
14658 out.writeInt(1);
14659 wl.mTimerFull.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14660 } else {
14661 out.writeInt(0);
14662 }
14663 if (wl.mTimerPartial != null) {
14664 out.writeInt(1);
14665 wl.mTimerPartial.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14666 } else {
14667 out.writeInt(0);
14668 }
14669 if (wl.mTimerWindow != null) {
14670 out.writeInt(1);
14671 wl.mTimerWindow.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14672 } else {
14673 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014674 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070014675 if (wl.mTimerDraw != null) {
Adam Lesinski9425fe22015-06-19 12:02:13 -070014676 out.writeInt(1);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070014677 wl.mTimerDraw.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9425fe22015-06-19 12:02:13 -070014678 } else {
14679 out.writeInt(0);
14680 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014681 }
14682
Bookatz2bffb5b2017-04-13 11:59:33 -070014683 final ArrayMap<String, DualTimer> syncStats = u.mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014684 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014685 out.writeInt(NS);
14686 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014687 out.writeString(syncStats.keyAt(is));
14688 syncStats.valueAt(is).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014689 }
14690
Bookatzaa4594a2017-03-24 12:39:56 -070014691 final ArrayMap<String, DualTimer> jobStats = u.mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014692 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014693 out.writeInt(NJ);
14694 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014695 out.writeString(jobStats.keyAt(ij));
14696 jobStats.valueAt(ij).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014697 }
14698
Dianne Hackborn94326cb2017-06-28 16:17:20 -070014699 u.writeJobCompletionsToParcelLocked(out);
14700
Amith Yamasani977e11f2018-02-16 11:29:54 -080014701 u.mJobsDeferredEventCount.writeSummaryFromParcelLocked(out);
14702 u.mJobsDeferredCount.writeSummaryFromParcelLocked(out);
14703 u.mJobsFreshnessTimeMs.writeSummaryFromParcelLocked(out);
14704 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
14705 if (u.mJobsFreshnessBuckets[i] != null) {
Adam Lesinski14082082018-02-23 12:35:55 -080014706 out.writeInt(1);
Amith Yamasani977e11f2018-02-16 11:29:54 -080014707 u.mJobsFreshnessBuckets[i].writeSummaryFromParcelLocked(out);
14708 } else {
14709 out.writeInt(0);
14710 }
14711 }
14712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014713 int NSE = u.mSensorStats.size();
14714 out.writeInt(NSE);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014715 for (int ise=0; ise<NSE; ise++) {
14716 out.writeInt(u.mSensorStats.keyAt(ise));
14717 Uid.Sensor se = u.mSensorStats.valueAt(ise);
14718 if (se.mTimer != null) {
14719 out.writeInt(1);
14720 se.mTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14721 } else {
14722 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014723 }
14724 }
14725
14726 int NP = u.mProcessStats.size();
14727 out.writeInt(NP);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014728 for (int ip=0; ip<NP; ip++) {
14729 out.writeString(u.mProcessStats.keyAt(ip));
14730 Uid.Proc ps = u.mProcessStats.valueAt(ip);
14731 out.writeLong(ps.mUserTime);
14732 out.writeLong(ps.mSystemTime);
14733 out.writeLong(ps.mForegroundTime);
14734 out.writeInt(ps.mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014735 out.writeInt(ps.mNumCrashes);
14736 out.writeInt(ps.mNumAnrs);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014737 ps.writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014738 }
14739
14740 NP = u.mPackageStats.size();
14741 out.writeInt(NP);
14742 if (NP > 0) {
14743 for (Map.Entry<String, BatteryStatsImpl.Uid.Pkg> ent
14744 : u.mPackageStats.entrySet()) {
14745 out.writeString(ent.getKey());
14746 Uid.Pkg ps = ent.getValue();
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014747 final int NWA = ps.mWakeupAlarms.size();
14748 out.writeInt(NWA);
14749 for (int iwa=0; iwa<NWA; iwa++) {
14750 out.writeString(ps.mWakeupAlarms.keyAt(iwa));
14751 ps.mWakeupAlarms.valueAt(iwa).writeSummaryFromParcelLocked(out);
14752 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014753 NS = ps.mServiceStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014754 out.writeInt(NS);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014755 for (int is=0; is<NS; is++) {
14756 out.writeString(ps.mServiceStats.keyAt(is));
14757 BatteryStatsImpl.Uid.Pkg.Serv ss = ps.mServiceStats.valueAt(is);
14758 long time = ss.getStartTimeToNowLocked(
14759 mOnBatteryTimeBase.getUptime(NOW_SYS));
14760 out.writeLong(time);
14761 out.writeInt(ss.mStarts);
14762 out.writeInt(ss.mLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014763 }
14764 }
14765 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014766 }
14767 }
14768
14769 public void readFromParcel(Parcel in) {
14770 readFromParcelLocked(in);
14771 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014773 void readFromParcelLocked(Parcel in) {
14774 int magic = in.readInt();
14775 if (magic != MAGIC) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014776 throw new ParcelFormatException("Bad magic number: #" + Integer.toHexString(magic));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014777 }
14778
Dianne Hackbornae384452011-06-28 12:33:48 -070014779 readHistory(in, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014781 mStartCount = in.readInt();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080014782 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014783 mStartPlatformVersion = in.readString();
14784 mEndPlatformVersion = in.readString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014785 mUptime = in.readLong();
14786 mUptimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014787 mRealtime = in.readLong();
14788 mRealtimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014789 mOnBattery = in.readInt() != 0;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014790 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070014791 mMinLearnedBatteryCapacity = in.readInt();
14792 mMaxLearnedBatteryCapacity = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014793 mOnBatteryInternal = false; // we are no longer really running.
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014794 mOnBatteryTimeBase.readFromParcel(in);
14795 mOnBatteryScreenOffTimeBase.readFromParcel(in);
14796
Jeff Browne95c3cd2014-05-02 16:59:26 -070014797 mScreenState = Display.STATE_UNKNOWN;
Joe Onoratoabded112016-02-08 16:49:39 -080014798 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070014799 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014800 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014801 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
14802 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014803 }
Dianne Hackborn29325132014-05-21 15:01:03 -070014804 mInteractive = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014805 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014806 mPhoneOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014807 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
14808 mOnBatteryTimeBase, in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014809 mLongestLightIdleTime = in.readLong();
14810 mLongestFullIdleTime = in.readLong();
Joe Onoratoabded112016-02-08 16:49:39 -080014811 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -14, null,
14812 mOnBatteryTimeBase, in);
14813 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -11, null,
14814 mOnBatteryTimeBase, in);
14815 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null,
14816 mOnBatteryTimeBase, in);
14817 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase, in);
14818 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014819 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014820 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014821 null, mOnBatteryTimeBase, in);
14822 }
Joe Onoratoabded112016-02-08 16:49:39 -080014823 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
14824 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014825 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014826 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014827 null, mOnBatteryTimeBase, in);
14828 }
14829 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
14830 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
14831 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
14832 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014833 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Joe Onoratoabded112016-02-08 16:49:39 -080014834 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null,
14835 mOnBatteryTimeBase, in);
Kweku Adams87b19ec2017-10-09 12:40:03 -070014836 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
Joe Onoratoabded112016-02-08 16:49:39 -080014837 mOnBatteryTimeBase, in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014838 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014839 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
14840 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase, in);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014841 mWifiMulticastWakelockTimer = new StopwatchTimer(mClocks, null, -4, null,
14842 mOnBatteryTimeBase, in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070014843 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014844 mWifiOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014845 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014846 mGlobalWifiRunning = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014847 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null,
14848 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014849 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014850 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014851 null, mOnBatteryTimeBase, in);
14852 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014853 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014854 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070014855 null, mOnBatteryTimeBase, in);
14856 }
14857 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014858 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070014859 null, mOnBatteryTimeBase, in);
14860 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014861 mWifiActiveTimer = new StopwatchTimer(mClocks, null, -900, null,
14862 mOnBatteryTimeBase, in);
14863 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14864 NUM_WIFI_TX_LEVELS, in);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014865 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14866 mGpsSignalQualityTimer[i] = new StopwatchTimer(mClocks, null, -1000-i,
14867 null, mOnBatteryTimeBase, in);
14868 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014869 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14870 NUM_BT_TX_LEVELS, in);
14871 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14872 ModemActivityInfo.TX_POWER_LEVELS, in);
14873 mHasWifiReporting = in.readInt() != 0;
14874 mHasBluetoothReporting = in.readInt() != 0;
14875 mHasModemReporting = in.readInt() != 0;
14876
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014877 mNumConnectivityChange = in.readInt();
14878 mLoadedNumConnectivityChange = in.readInt();
14879 mUnpluggedNumConnectivityChange = in.readInt();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014880 mAudioOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014881 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014882 mVideoOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014883 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014884 mFlashlightOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014885 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014886 mCameraOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014887 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014888 mBluetoothScanNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014889 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase, in);
Siddharth Rayf5e796a2018-01-22 18:18:17 -080014890 mIsCellularTxPowerHigh = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014891 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014892 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070014893 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014894 mCurrentBatteryLevel = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014895 mLowDischargeAmountSinceCharge = in.readInt();
14896 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014897 mDischargeAmountScreenOn = in.readInt();
14898 mDischargeAmountScreenOnSinceCharge = in.readInt();
14899 mDischargeAmountScreenOff = in.readInt();
14900 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070014901 mDischargeAmountScreenDoze = in.readInt();
14902 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014903 mDischargeStepTracker.readFromParcel(in);
14904 mChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070014905 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070014906 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase, in);
14907 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Ma15313c92017-11-15 17:58:21 -080014908 mDischargeLightDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
14909 mDischargeDeepDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014910 mLastWriteTime = in.readLong();
14911
Bookatz50df7112017-08-04 14:53:26 -070014912 mRpmStats.clear();
14913 int NRPMS = in.readInt();
14914 for (int irpm = 0; irpm < NRPMS; irpm++) {
14915 if (in.readInt() != 0) {
14916 String rpmName = in.readString();
14917 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
14918 mRpmStats.put(rpmName, rpmt);
14919 }
14920 }
14921 mScreenOffRpmStats.clear();
14922 int NSORPMS = in.readInt();
14923 for (int irpm = 0; irpm < NSORPMS; irpm++) {
14924 if (in.readInt() != 0) {
14925 String rpmName = in.readString();
14926 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
14927 mScreenOffRpmStats.put(rpmName, rpmt);
14928 }
14929 }
14930
Evan Millarc64edde2009-04-18 12:26:32 -070014931 mKernelWakelockStats.clear();
14932 int NKW = in.readInt();
14933 for (int ikw = 0; ikw < NKW; ikw++) {
14934 if (in.readInt() != 0) {
14935 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080014936 SamplingTimer kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -070014937 mKernelWakelockStats.put(wakelockName, kwlt);
14938 }
14939 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014940
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014941 mWakeupReasonStats.clear();
14942 int NWR = in.readInt();
14943 for (int iwr = 0; iwr < NWR; iwr++) {
14944 if (in.readInt() != 0) {
14945 String reasonName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080014946 SamplingTimer timer = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014947 mWakeupReasonStats.put(reasonName, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014948 }
14949 }
14950
James Carr3a226052016-07-01 14:49:52 -070014951 mKernelMemoryStats.clear();
14952 int nmt = in.readInt();
14953 for (int imt = 0; imt < nmt; imt++) {
14954 if (in.readInt() != 0) {
14955 Long bucket = in.readLong();
14956 SamplingTimer kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
14957 mKernelMemoryStats.put(bucket, kmt);
14958 }
14959 }
14960
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014961 mPartialTimers.clear();
14962 mFullTimers.clear();
14963 mWindowTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014964 mWifiRunningTimers.clear();
14965 mFullWifiLockTimers.clear();
Nick Pelly6ccaa542012-06-15 15:22:47 -070014966 mWifiScanTimers.clear();
Robert Greenwalta029ea12013-09-25 16:38:12 -070014967 mWifiBatchedScanTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014968 mWifiMulticastTimers.clear();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014969 mAudioTurnedOnTimers.clear();
14970 mVideoTurnedOnTimers.clear();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014971 mFlashlightTurnedOnTimers.clear();
14972 mCameraTurnedOnTimers.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014973
14974 int numUids = in.readInt();
14975 mUidStats.clear();
14976 for (int i = 0; i < numUids; i++) {
14977 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080014978 Uid u = new Uid(this, uid);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014979 u.readFromParcelLocked(mOnBatteryTimeBase, mOnBatteryScreenOffTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014980 mUidStats.append(uid, u);
14981 }
14982 }
14983
14984 public void writeToParcel(Parcel out, int flags) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014985 writeToParcelLocked(out, true, flags);
14986 }
14987
14988 public void writeToParcelWithoutUids(Parcel out, int flags) {
14989 writeToParcelLocked(out, false, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014990 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014991
14992 @SuppressWarnings("unused")
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014993 void writeToParcelLocked(Parcel out, boolean inclUids, int flags) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014994 // Need to update with current kernel wake lock counts.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080014995 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014996
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014997 // Pull the clock time. This may update the time and make a new history entry
14998 // if we had originally pulled a time before the RTC was set.
14999 long startClockTime = getStartClockTime();
15000
Joe Onoratoabded112016-02-08 16:49:39 -080015001 final long uSecUptime = mClocks.uptimeMillis() * 1000;
15002 final long uSecRealtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080015003 final long batteryRealtime = mOnBatteryTimeBase.getRealtime(uSecRealtime);
15004 final long batteryScreenOffRealtime = mOnBatteryScreenOffTimeBase.getRealtime(uSecRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070015005
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015006 out.writeInt(MAGIC);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070015007
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070015008 writeHistory(out, true, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070015009
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015010 out.writeInt(mStartCount);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070015011 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070015012 out.writeString(mStartPlatformVersion);
15013 out.writeString(mEndPlatformVersion);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015014 out.writeLong(mUptime);
15015 out.writeLong(mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015016 out.writeLong(mRealtime);
15017 out.writeLong(mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015018 out.writeInt(mOnBattery ? 1 : 0);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070015019 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070015020 out.writeInt(mMinLearnedBatteryCapacity);
15021 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080015022 mOnBatteryTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
15023 mOnBatteryScreenOffTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
15024
15025 mScreenOnTimer.writeToParcel(out, uSecRealtime);
Mike Mac2f518a2017-09-19 16:06:03 -070015026 mScreenDozeTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080015027 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
15028 mScreenBrightnessTimer[i].writeToParcel(out, uSecRealtime);
15029 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070015030 mInteractiveTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070015031 mPowerSaveModeEnabledTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070015032 out.writeLong(mLongestLightIdleTime);
15033 out.writeLong(mLongestFullIdleTime);
15034 mDeviceIdleModeLightTimer.writeToParcel(out, uSecRealtime);
15035 mDeviceIdleModeFullTimer.writeToParcel(out, uSecRealtime);
15036 mDeviceLightIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070015037 mDeviceIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080015038 mPhoneOnTimer.writeToParcel(out, uSecRealtime);
15039 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
15040 mPhoneSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
15041 }
15042 mPhoneSignalScanningTimer.writeToParcel(out, uSecRealtime);
15043 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
15044 mPhoneDataConnectionsTimer[i].writeToParcel(out, uSecRealtime);
15045 }
15046 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
15047 mNetworkByteActivityCounters[i].writeToParcel(out);
15048 mNetworkPacketActivityCounters[i].writeToParcel(out);
15049 }
15050 mMobileRadioActiveTimer.writeToParcel(out, uSecRealtime);
15051 mMobileRadioActivePerAppTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070015052 mMobileRadioActiveAdjustedTime.writeToParcel(out);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080015053 mMobileRadioActiveUnknownTime.writeToParcel(out);
15054 mMobileRadioActiveUnknownCount.writeToParcel(out);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080015055 mWifiMulticastWakelockTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080015056 mWifiOnTimer.writeToParcel(out, uSecRealtime);
15057 mGlobalWifiRunningTimer.writeToParcel(out, uSecRealtime);
15058 for (int i=0; i<NUM_WIFI_STATES; i++) {
15059 mWifiStateTimer[i].writeToParcel(out, uSecRealtime);
15060 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070015061 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
15062 mWifiSupplStateTimer[i].writeToParcel(out, uSecRealtime);
15063 }
15064 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
15065 mWifiSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
15066 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080015067 mWifiActiveTimer.writeToParcel(out, uSecRealtime);
15068 mWifiActivity.writeToParcel(out, 0);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080015069 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
15070 mGpsSignalQualityTimer[i].writeToParcel(out, uSecRealtime);
15071 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080015072 mBluetoothActivity.writeToParcel(out, 0);
15073 mModemActivity.writeToParcel(out, 0);
15074 out.writeInt(mHasWifiReporting ? 1 : 0);
15075 out.writeInt(mHasBluetoothReporting ? 1 : 0);
15076 out.writeInt(mHasModemReporting ? 1 : 0);
15077
Dianne Hackborn1e01d162014-12-04 17:46:42 -080015078 out.writeInt(mNumConnectivityChange);
15079 out.writeInt(mLoadedNumConnectivityChange);
15080 out.writeInt(mUnpluggedNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070015081 mFlashlightOnTimer.writeToParcel(out, uSecRealtime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070015082 mCameraOnTimer.writeToParcel(out, uSecRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080015083 mBluetoothScanTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070015084 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070015085 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070015086 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070015087 out.writeInt(mCurrentBatteryLevel);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015088 out.writeInt(mLowDischargeAmountSinceCharge);
15089 out.writeInt(mHighDischargeAmountSinceCharge);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080015090 out.writeInt(mDischargeAmountScreenOn);
15091 out.writeInt(mDischargeAmountScreenOnSinceCharge);
15092 out.writeInt(mDischargeAmountScreenOff);
15093 out.writeInt(mDischargeAmountScreenOffSinceCharge);
Mike Mac2f518a2017-09-19 16:06:03 -070015094 out.writeInt(mDischargeAmountScreenDoze);
15095 out.writeInt(mDischargeAmountScreenDozeSinceCharge);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080015096 mDischargeStepTracker.writeToParcel(out);
15097 mChargeStepTracker.writeToParcel(out);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070015098 mDischargeCounter.writeToParcel(out);
15099 mDischargeScreenOffCounter.writeToParcel(out);
Mike Mac2f518a2017-09-19 16:06:03 -070015100 mDischargeScreenDozeCounter.writeToParcel(out);
Mike Ma15313c92017-11-15 17:58:21 -080015101 mDischargeLightDozeCounter.writeToParcel(out);
15102 mDischargeDeepDozeCounter.writeToParcel(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015103 out.writeLong(mLastWriteTime);
15104
Bookatz50df7112017-08-04 14:53:26 -070015105 out.writeInt(mRpmStats.size());
15106 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
15107 SamplingTimer rpmt = ent.getValue();
15108 if (rpmt != null) {
15109 out.writeInt(1);
15110 out.writeString(ent.getKey());
15111 rpmt.writeToParcel(out, uSecRealtime);
15112 } else {
15113 out.writeInt(0);
15114 }
15115 }
15116 out.writeInt(mScreenOffRpmStats.size());
15117 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
15118 SamplingTimer rpmt = ent.getValue();
15119 if (rpmt != null) {
15120 out.writeInt(1);
15121 out.writeString(ent.getKey());
15122 rpmt.writeToParcel(out, uSecRealtime);
15123 } else {
15124 out.writeInt(0);
15125 }
15126 }
15127
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015128 if (inclUids) {
15129 out.writeInt(mKernelWakelockStats.size());
15130 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
15131 SamplingTimer kwlt = ent.getValue();
15132 if (kwlt != null) {
15133 out.writeInt(1);
15134 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070015135 kwlt.writeToParcel(out, uSecRealtime);
15136 } else {
15137 out.writeInt(0);
15138 }
15139 }
15140 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070015141 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
15142 SamplingTimer timer = ent.getValue();
15143 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070015144 out.writeInt(1);
15145 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070015146 timer.writeToParcel(out, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015147 } else {
15148 out.writeInt(0);
15149 }
Evan Millarc64edde2009-04-18 12:26:32 -070015150 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015151 } else {
Bookatzba78b2b2017-10-10 11:06:33 -070015152 out.writeInt(0);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015153 out.writeInt(0);
Evan Millarc64edde2009-04-18 12:26:32 -070015154 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070015155
James Carr3a226052016-07-01 14:49:52 -070015156 out.writeInt(mKernelMemoryStats.size());
15157 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
15158 SamplingTimer kmt = mKernelMemoryStats.valueAt(i);
15159 if (kmt != null) {
15160 out.writeInt(1);
15161 out.writeLong(mKernelMemoryStats.keyAt(i));
15162 kmt.writeToParcel(out, uSecRealtime);
15163 } else {
15164 out.writeInt(0);
15165 }
15166 }
15167
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015168 if (inclUids) {
15169 int size = mUidStats.size();
15170 out.writeInt(size);
15171 for (int i = 0; i < size; i++) {
15172 out.writeInt(mUidStats.keyAt(i));
15173 Uid uid = mUidStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015174
Bookatz867c0d72017-03-07 18:23:42 -080015175 uid.writeToParcelLocked(out, uSecUptime, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015176 }
15177 } else {
15178 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015179 }
15180 }
15181
15182 public static final Parcelable.Creator<BatteryStatsImpl> CREATOR =
15183 new Parcelable.Creator<BatteryStatsImpl>() {
15184 public BatteryStatsImpl createFromParcel(Parcel in) {
15185 return new BatteryStatsImpl(in);
15186 }
15187
15188 public BatteryStatsImpl[] newArray(int size) {
15189 return new BatteryStatsImpl[size];
15190 }
15191 };
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070015192
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070015193 public void prepareForDumpLocked() {
15194 // Need to retrieve current kernel wake lock stats before printing.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080015195 pullPendingStateUpdatesLocked();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070015196
15197 // Pull the clock time. This may update the time and make a new history entry
15198 // if we had originally pulled a time before the RTC was set.
15199 getStartClockTime();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070015200 }
15201
Dianne Hackbornc51cf032014-03-02 19:08:15 -080015202 public void dumpLocked(Context context, PrintWriter pw, int flags, int reqUid, long histStart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015203 if (DEBUG) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080015204 pw.println("mOnBatteryTimeBase:");
15205 mOnBatteryTimeBase.dump(pw, " ");
15206 pw.println("mOnBatteryScreenOffTimeBase:");
15207 mOnBatteryScreenOffTimeBase.dump(pw, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015208 Printer pr = new PrintWriterPrinter(pw);
Mike Mac2f518a2017-09-19 16:06:03 -070015209 pr.println("*** Screen on timer:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015210 mScreenOnTimer.logState(pr, " ");
Mike Mac2f518a2017-09-19 16:06:03 -070015211 pr.println("*** Screen doze timer:");
15212 mScreenDozeTimer.logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070015213 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015214 pr.println("*** Screen brightness #" + i + ":");
15215 mScreenBrightnessTimer[i].logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070015216 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070015217 pr.println("*** Interactive timer:");
15218 mInteractiveTimer.logState(pr, " ");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070015219 pr.println("*** Power save mode timer:");
15220 mPowerSaveModeEnabledTimer.logState(pr, " ");
Dianne Hackborn08c47a52015-10-15 12:38:14 -070015221 pr.println("*** Device idle mode light timer:");
15222 mDeviceIdleModeLightTimer.logState(pr, " ");
15223 pr.println("*** Device idle mode full timer:");
15224 mDeviceIdleModeFullTimer.logState(pr, " ");
15225 pr.println("*** Device light idling timer:");
15226 mDeviceLightIdlingTimer.logState(pr, " ");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070015227 pr.println("*** Device idling timer:");
15228 mDeviceIdlingTimer.logState(pr, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015229 pr.println("*** Phone timer:");
15230 mPhoneOnTimer.logState(pr, " ");
Wink Saville52840902011-02-18 12:40:47 -080015231 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3251b902014-06-20 14:40:53 -070015232 pr.println("*** Phone signal strength #" + i + ":");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015233 mPhoneSignalStrengthsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070015234 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070015235 pr.println("*** Signal scanning :");
15236 mPhoneSignalScanningTimer.logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070015237 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015238 pr.println("*** Data connection type #" + i + ":");
15239 mPhoneDataConnectionsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070015240 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070015241 pr.println("*** mMobileRadioPowerState=" + mMobileRadioPowerState);
Dianne Hackborne13c4c02014-02-11 17:18:35 -080015242 pr.println("*** Mobile network active timer:");
15243 mMobileRadioActiveTimer.logState(pr, " ");
Dianne Hackborna1bd7922014-03-21 11:07:11 -070015244 pr.println("*** Mobile network active adjusted timer:");
15245 mMobileRadioActiveAdjustedTime.logState(pr, " ");
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080015246 pr.println("*** Wifi Multicast WakeLock Timer:");
15247 mWifiMulticastWakelockTimer.logState(pr, " ");
Dianne Hackborn0c820db2015-04-14 17:47:34 -070015248 pr.println("*** mWifiRadioPowerState=" + mWifiRadioPowerState);
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015249 pr.println("*** Wifi timer:");
15250 mWifiOnTimer.logState(pr, " ");
15251 pr.println("*** WifiRunning timer:");
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070015252 mGlobalWifiRunningTimer.logState(pr, " ");
Dianne Hackbornca1bf212014-02-14 14:18:36 -080015253 for (int i=0; i<NUM_WIFI_STATES; i++) {
15254 pr.println("*** Wifi state #" + i + ":");
15255 mWifiStateTimer[i].logState(pr, " ");
15256 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070015257 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
15258 pr.println("*** Wifi suppl state #" + i + ":");
15259 mWifiSupplStateTimer[i].logState(pr, " ");
15260 }
15261 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
15262 pr.println("*** Wifi signal strength #" + i + ":");
15263 mWifiSignalStrengthsTimer[i].logState(pr, " ");
15264 }
Siddharth Ray78ccaf52017-12-23 16:16:21 -080015265 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
15266 pr.println("*** GPS signal quality #" + i + ":");
15267 mGpsSignalQualityTimer[i].logState(pr, " ");
15268 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -070015269 pr.println("*** Flashlight timer:");
15270 mFlashlightOnTimer.logState(pr, " ");
Ruben Brunk6d2c3632015-05-26 17:32:16 -070015271 pr.println("*** Camera timer:");
15272 mCameraOnTimer.logState(pr, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015273 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -080015274 super.dumpLocked(context, pw, flags, reqUid, histStart);
Sudheer Shankac20379e2018-02-15 00:06:21 -080015275 pw.print("Total cpu time reads: ");
Mike Ma234d1822018-03-13 18:53:21 -070015276 pw.println(mNumSingleUidCpuTimeReads);
Sudheer Shankac20379e2018-02-15 00:06:21 -080015277 pw.print("Batched cpu time reads: ");
Mike Ma234d1822018-03-13 18:53:21 -070015278 pw.println(mNumBatchedSingleUidCpuTimeReads);
Sudheer Shankac20379e2018-02-15 00:06:21 -080015279 pw.print("Batching Duration (min): ");
15280 pw.println((mClocks.uptimeMillis() - mCpuTimeReadsTrackingStartTime) / (60 * 1000));
Mike Ma234d1822018-03-13 18:53:21 -070015281 pw.print("All UID cpu time reads since the later of device start or stats reset: ");
15282 pw.println(mNumAllUidCpuTimeReads);
15283 pw.print("UIDs removed since the later of device start or stats reset: ");
15284 pw.println(mNumUidsRemoved);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015285 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015286}