blob: 663aac0f7cffc6786ea453e64fee73b3df0c1c4f [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006-2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.internal.os;
18
Sudheer Shanka9b735c52017-05-09 18:26:18 -070019import android.annotation.NonNull;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070020import android.annotation.Nullable;
Dianne Hackborn61659e52014-07-09 16:13:01 -070021import android.app.ActivityManager;
Adam Lesinski33dac552015-03-09 15:24:48 -070022import android.bluetooth.BluetoothActivityEnergyInfo;
Adam Lesinski50e47602015-12-04 17:04:54 -080023import android.bluetooth.UidTraffic;
Mike Mafbc01fc2018-04-02 10:28:28 -070024import android.content.BroadcastReceiver;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080025import android.content.ContentResolver;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080026import android.content.Context;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070027import android.content.Intent;
Mike Mafbc01fc2018-04-02 10:28:28 -070028import android.content.IntentFilter;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080029import android.database.ContentObserver;
Mike Mafbc01fc2018-04-02 10:28:28 -070030import android.hardware.usb.UsbManager;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070031import android.net.ConnectivityManager;
32import android.net.NetworkStats;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080033import android.net.Uri;
Adam Lesinski33dac552015-03-09 15:24:48 -070034import android.net.wifi.WifiActivityEnergyInfo;
Dianne Hackborn3251b902014-06-20 14:40:53 -070035import android.net.wifi.WifiManager;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070036import android.os.BatteryManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.os.BatteryStats;
Dianne Hackborncd0e3352014-08-07 17:08:09 -070038import android.os.Build;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070039import android.os.FileUtils;
Dianne Hackborn0d903a82010-09-07 23:51:03 -070040import android.os.Handler;
Adam Lesinskie1f480d2017-02-15 18:51:23 -080041import android.os.IBatteryPropertiesRegistrar;
Jeff Brown6f357d32014-01-15 20:40:55 -080042import android.os.Looper;
Dianne Hackborn0d903a82010-09-07 23:51:03 -070043import android.os.Message;
Bookatz1a1b0462018-01-12 11:47:03 -080044import android.os.OsProtoEnums;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.os.Parcel;
46import android.os.ParcelFormatException;
47import android.os.Parcelable;
Bookatz1a1b0462018-01-12 11:47:03 -080048import android.os.PowerManager;
Evan Millarc64edde2009-04-18 12:26:32 -070049import android.os.Process;
Adam Lesinskie1f480d2017-02-15 18:51:23 -080050import android.os.RemoteException;
51import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.os.SystemClock;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070053import android.os.UserHandle;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070054import android.os.WorkSource;
Narayan Kamath81822022017-12-08 11:56:01 +000055import android.os.WorkSource.WorkChain;
Mike Ma234d1822018-03-13 18:53:21 -070056import android.os.connectivity.CellularBatteryStats;
57import android.os.connectivity.GpsBatteryStats;
58import android.os.connectivity.WifiBatteryStats;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080059import android.provider.Settings;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070060import android.telephony.DataConnectionRealTimeInfo;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080061import android.telephony.ModemActivityInfo;
Amith Yamasanif37447b2009-10-08 18:28:01 -070062import android.telephony.ServiceState;
Wink Savillee9b06d72009-05-18 21:47:50 -070063import android.telephony.SignalStrength;
Dianne Hackborn627bba72009-03-24 22:32:56 -070064import android.telephony.TelephonyManager;
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -070065import android.text.TextUtils;
Dianne Hackborn61659e52014-07-09 16:13:01 -070066import android.util.ArrayMap;
Sudheer Shankab2f83c12017-11-13 19:25:01 -080067import android.util.IntArray;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080068import android.util.KeyValueListParser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.util.Log;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070070import android.util.LogWriter;
James Carr3a226052016-07-01 14:49:52 -070071import android.util.LongSparseArray;
72import android.util.LongSparseLongArray;
Dianne Hackbornd953c532014-08-16 18:17:38 -070073import android.util.MutableInt;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070074import android.util.Pools;
Dianne Hackborn1d442e02009-04-20 18:14:05 -070075import android.util.PrintWriterPrinter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.util.Printer;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070077import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078import android.util.SparseArray;
Dianne Hackborn099bc622014-01-22 13:39:16 -080079import android.util.SparseIntArray;
Adam Lesinskie08af192015-03-25 16:42:59 -070080import android.util.SparseLongArray;
Bookatzc1a050a2017-10-10 15:49:28 -070081import android.util.StatsLog;
Dianne Hackbornae384452011-06-28 12:33:48 -070082import android.util.TimeUtils;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080083import android.util.Xml;
Jeff Browne95c3cd2014-05-02 16:59:26 -070084import android.view.Display;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085
Adam Lesinski14ae39a2017-05-26 11:50:40 -070086import com.android.internal.annotations.GuardedBy;
Adam Lesinski98f0d462016-04-19 16:46:20 -070087import com.android.internal.annotations.VisibleForTesting;
Siddharth Ray78ccaf52017-12-23 16:16:21 -080088import com.android.internal.location.gnssmetrics.GnssMetrics;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070089import com.android.internal.net.NetworkStatsFactory;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080090import com.android.internal.util.ArrayUtils;
Dianne Hackborn8c841092013-06-24 13:46:13 -070091import com.android.internal.util.FastPrintWriter;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080092import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070093import com.android.internal.util.JournaledFile;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080094import com.android.internal.util.XmlUtils;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070095
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070096import libcore.util.EmptyArray;
Mike Ma234d1822018-03-13 18:53:21 -070097
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080098import org.xmlpull.v1.XmlPullParser;
99import org.xmlpull.v1.XmlPullParserException;
100import org.xmlpull.v1.XmlSerializer;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700101
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800102import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103import java.io.File;
104import java.io.FileInputStream;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800105import java.io.FileNotFoundException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import java.io.FileOutputStream;
107import java.io.IOException;
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700108import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100109import java.nio.charset.StandardCharsets;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import java.util.ArrayList;
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700111import java.util.Arrays;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800112import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113import java.util.HashMap;
Evan Millarc64edde2009-04-18 12:26:32 -0700114import java.util.Iterator;
Mike Ma234d1822018-03-13 18:53:21 -0700115import java.util.LinkedList;
116import java.util.List;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117import java.util.Map;
Mike Ma234d1822018-03-13 18:53:21 -0700118import java.util.Queue;
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700119import java.util.concurrent.Future;
Christopher Tate4cee7252010-03-19 14:50:40 -0700120import java.util.concurrent.atomic.AtomicInteger;
Dianne Hackbornce2ef762010-09-20 11:39:14 -0700121import java.util.concurrent.locks.ReentrantLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122
123/**
124 * All information we are collecting about things that can happen that impact
125 * battery life. All times are represented in microseconds except where indicated
126 * otherwise.
127 */
Joe Onoratoabded112016-02-08 16:49:39 -0800128public class BatteryStatsImpl extends BatteryStats {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129 private static final String TAG = "BatteryStatsImpl";
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800130 private static final boolean DEBUG = false;
Adam Lesinskia7c90c82015-06-18 14:52:24 -0700131 public static final boolean DEBUG_ENERGY = false;
Adam Lesinski50e47602015-12-04 17:04:54 -0800132 private static final boolean DEBUG_ENERGY_CPU = DEBUG_ENERGY;
James Carr3a226052016-07-01 14:49:52 -0700133 private static final boolean DEBUG_MEMORY = false;
Dianne Hackborn32907cf2010-06-10 17:50:20 -0700134 private static final boolean DEBUG_HISTORY = false;
Dianne Hackborne8c88e62011-08-17 19:09:09 -0700135 private static final boolean USE_OLD_HISTORY = false; // for debugging.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700136
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700137 // TODO: remove "tcp" from network methods, since we measure total stats.
138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139 // In-memory Parcel magic number, used to detect attempts to unmarshall bad data
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700140 private static final int MAGIC = 0xBA757475; // 'BATSTATS'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141
142 // Current on-disk Parcel version
Mike Ma561a8d92018-03-20 18:24:05 -0700143 private static final int VERSION = 177 + (USE_OLD_HISTORY ? 1000 : 0);
Amith Yamasanie43530a2009-08-21 13:11:37 -0700144
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700145 // Maximum number of items we will record in the history.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100146 private static final int MAX_HISTORY_ITEMS;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700147
Dianne Hackbornf47d8f22010-10-08 10:46:55 -0700148 // No, really, THIS is the maximum number of items we will record in the history.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100149 private static final int MAX_MAX_HISTORY_ITEMS;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -0700150
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800151 // The maximum number of names wakelocks we will keep track of
152 // per uid; once the limit is reached, we batch the remaining wakelocks
153 // in to one common name.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100154 private static final int MAX_WAKELOCKS_PER_UID;
155
156 static final int MAX_HISTORY_BUFFER; // 256KB
157 static final int MAX_MAX_HISTORY_BUFFER; // 320KB
158
159 static {
160 if (ActivityManager.isLowRamDeviceStatic()) {
161 MAX_HISTORY_ITEMS = 800;
162 MAX_MAX_HISTORY_ITEMS = 1200;
163 MAX_WAKELOCKS_PER_UID = 40;
164 MAX_HISTORY_BUFFER = 96*1024; // 96KB
165 MAX_MAX_HISTORY_BUFFER = 128*1024; // 128KB
166 } else {
Makoto Onuki44d64602018-01-18 08:44:28 -0800167 MAX_HISTORY_ITEMS = 4000;
168 MAX_MAX_HISTORY_ITEMS = 6000;
169 MAX_WAKELOCKS_PER_UID = 200;
170 MAX_HISTORY_BUFFER = 512*1024; // 512KB
171 MAX_MAX_HISTORY_BUFFER = 640*1024; // 640KB
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100172 }
173 }
Dianne Hackbornc24ab862011-10-18 15:55:03 -0700174
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800175 // Number of transmit power states the Wifi controller can be in.
176 private static final int NUM_WIFI_TX_LEVELS = 1;
177
178 // Number of transmit power states the Bluetooth controller can be in.
179 private static final int NUM_BT_TX_LEVELS = 1;
180
Sudheer Shanka38383232017-07-25 09:55:03 -0700181 /**
182 * Holding a wakelock costs more than just using the cpu.
183 * Currently, we assign only half the cpu time to an app that is running but
184 * not holding a wakelock. The apps holding wakelocks get the rest of the blame.
185 * If no app is holding a wakelock, then the distribution is normal.
186 */
187 @VisibleForTesting
188 public static final int WAKE_LOCK_WEIGHT = 50;
189
Joe Onoratoabded112016-02-08 16:49:39 -0800190 protected Clocks mClocks;
191
Dianne Hackborn1afd1c92010-03-18 22:47:17 -0700192 private final JournaledFile mFile;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700193 public final AtomicFile mCheckinFile;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800194 public final AtomicFile mDailyFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195
Sudheer Shankac57729a2018-02-09 15:44:42 -0800196 static final int MSG_REPORT_CPU_UPDATE_NEEDED = 1;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700197 static final int MSG_REPORT_POWER_CHANGE = 2;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700198 static final int MSG_REPORT_CHARGING = 3;
Fyodor Kupolov8aa51242018-04-23 12:44:51 -0700199 static final int MSG_REPORT_RESET_STATS = 4;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700200 static final long DELAY_UPDATE_WAKELOCKS = 5*1000;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700201
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700202 private final KernelWakelockReader mKernelWakelockReader = new KernelWakelockReader();
203 private final KernelWakelockStats mTmpWakelockStats = new KernelWakelockStats();
204
Sudheer Shanka38383232017-07-25 09:55:03 -0700205 @VisibleForTesting
206 protected KernelUidCpuTimeReader mKernelUidCpuTimeReader = new KernelUidCpuTimeReader();
207 @VisibleForTesting
208 protected KernelCpuSpeedReader[] mKernelCpuSpeedReaders;
209 @VisibleForTesting
210 protected KernelUidCpuFreqTimeReader mKernelUidCpuFreqTimeReader =
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700211 new KernelUidCpuFreqTimeReader();
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800212 @VisibleForTesting
Mike Ma3d422c32017-10-25 11:08:57 -0700213 protected KernelUidCpuActiveTimeReader mKernelUidCpuActiveTimeReader =
214 new KernelUidCpuActiveTimeReader();
215 @VisibleForTesting
216 protected KernelUidCpuClusterTimeReader mKernelUidCpuClusterTimeReader =
217 new KernelUidCpuClusterTimeReader();
218 @VisibleForTesting
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800219 protected KernelSingleUidTimeReader mKernelSingleUidTimeReader;
Adam Lesinski06af1fa2015-05-05 17:35:35 -0700220
James Carr3a226052016-07-01 14:49:52 -0700221 private final KernelMemoryBandwidthStats mKernelMemoryBandwidthStats
222 = new KernelMemoryBandwidthStats();
223 private final LongSparseArray<SamplingTimer> mKernelMemoryStats = new LongSparseArray<>();
224 public LongSparseArray<SamplingTimer> getKernelMemoryStats() {
225 return mKernelMemoryStats;
226 }
227
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800228 @GuardedBy("this")
229 public boolean mPerProcStateCpuTimesAvailable = true;
230
231 /**
232 * Uids for which per-procstate cpu times need to be updated.
233 *
234 * Contains uid -> procState mappings.
235 */
236 @GuardedBy("this")
237 @VisibleForTesting
238 protected final SparseIntArray mPendingUids = new SparseIntArray();
239
Sudheer Shankac20379e2018-02-15 00:06:21 -0800240 @GuardedBy("this")
Mike Ma234d1822018-03-13 18:53:21 -0700241 private long mNumSingleUidCpuTimeReads;
Sudheer Shankac20379e2018-02-15 00:06:21 -0800242 @GuardedBy("this")
Mike Ma234d1822018-03-13 18:53:21 -0700243 private long mNumBatchedSingleUidCpuTimeReads;
Sudheer Shankac20379e2018-02-15 00:06:21 -0800244 @GuardedBy("this")
245 private long mCpuTimeReadsTrackingStartTime = SystemClock.uptimeMillis();
Mike Ma234d1822018-03-13 18:53:21 -0700246 @GuardedBy("this")
247 private int mNumUidsRemoved;
248 @GuardedBy("this")
249 private int mNumAllUidCpuTimeReads;
Sudheer Shankac20379e2018-02-15 00:06:21 -0800250
Bookatz0b8a0502017-09-13 11:51:52 -0700251 /** Container for Resource Power Manager stats. Updated by updateRpmStatsLocked. */
Bookatz50df7112017-08-04 14:53:26 -0700252 private final RpmStats mTmpRpmStats = new RpmStats();
Bookatz0b8a0502017-09-13 11:51:52 -0700253 /** The soonest the RPM stats can be updated after it was last updated. */
254 private static final long RPM_STATS_UPDATE_FREQ_MS = 1000;
255 /** Last time that RPM stats were updated by updateRpmStatsLocked. */
256 private long mLastRpmStatsUpdateTimeMs = -RPM_STATS_UPDATE_FREQ_MS;
Mike Ma234d1822018-03-13 18:53:21 -0700257 /**
258 * Use a queue to delay removing UIDs from {@link KernelUidCpuTimeReader},
259 * {@link KernelUidCpuActiveTimeReader}, {@link KernelUidCpuClusterTimeReader},
260 * {@link KernelUidCpuFreqTimeReader} and from the Kernel.
261 *
262 * Isolated and invalid UID info must be removed to conserve memory. However, STATSD and
263 * Batterystats both need to access UID cpu time. To resolve this race condition, only
264 * Batterystats shall remove UIDs, and a delay {@link Constants#UID_REMOVE_DELAY_MS} is
265 * implemented so that STATSD can capture those UID times before they are deleted.
266 */
267 @GuardedBy("this")
268 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
269 protected Queue<UidToRemove> mPendingRemovedUids = new LinkedList<>();
270
271 @VisibleForTesting
272 public final class UidToRemove {
273 int startUid;
274 int endUid;
275 long timeAddedInQueue;
276
277 /** Remove just one UID */
278 public UidToRemove(int uid, long timestamp) {
279 this(uid, uid, timestamp);
280 }
281
282 /** Remove a range of UIDs, startUid must be smaller than endUid. */
283 public UidToRemove(int startUid, int endUid, long timestamp) {
284 this.startUid = startUid;
285 this.endUid = endUid;
286 timeAddedInQueue = timestamp;
287 }
288
289 void remove() {
290 if (startUid == endUid) {
291 mKernelUidCpuTimeReader.removeUid(startUid);
292 mKernelUidCpuFreqTimeReader.removeUid(startUid);
293 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
294 mKernelUidCpuActiveTimeReader.removeUid(startUid);
295 mKernelUidCpuClusterTimeReader.removeUid(startUid);
296 }
297 if (mKernelSingleUidTimeReader != null) {
298 mKernelSingleUidTimeReader.removeUid(startUid);
299 }
300 mNumUidsRemoved++;
301 } else if (startUid < endUid) {
302 mKernelUidCpuFreqTimeReader.removeUidsInRange(startUid, endUid);
303 mKernelUidCpuTimeReader.removeUidsInRange(startUid, endUid);
304 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
305 mKernelUidCpuActiveTimeReader.removeUidsInRange(startUid, endUid);
306 mKernelUidCpuClusterTimeReader.removeUidsInRange(startUid, endUid);
307 }
308 if (mKernelSingleUidTimeReader != null) {
309 mKernelSingleUidTimeReader.removeUidsInRange(startUid, endUid);
310 }
311 // Treat as one. We don't know how many uids there are in between.
312 mNumUidsRemoved++;
313 } else {
314 Slog.w(TAG, "End UID " + endUid + " is smaller than start UID " + startUid);
315 }
316 }
317 }
Bookatz50df7112017-08-04 14:53:26 -0700318
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700319 public interface BatteryCallback {
320 public void batteryNeedsCpuUpdate();
321 public void batteryPowerChanged(boolean onBattery);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700322 public void batterySendBroadcast(Intent intent);
Fyodor Kupolov8aa51242018-04-23 12:44:51 -0700323 public void batteryStatsReset();
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700324 }
325
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700326 public interface PlatformIdleStateCallback {
Bookatz50df7112017-08-04 14:53:26 -0700327 public void fillLowPowerStats(RpmStats rpmStats);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700328 public String getPlatformLowPowerStats();
Ahmed ElArabawyd8b44112017-05-23 21:25:02 +0000329 public String getSubsystemLowPowerStats();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700330 }
331
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700332 public static abstract class UserInfoProvider {
333 private int[] userIds;
334 protected abstract @Nullable int[] getUserIds();
Sudheer Shanka38383232017-07-25 09:55:03 -0700335 @VisibleForTesting
336 public final void refreshUserIds() {
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700337 userIds = getUserIds();
338 }
Sudheer Shanka38383232017-07-25 09:55:03 -0700339 @VisibleForTesting
340 public boolean exists(int userId) {
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700341 return userIds != null ? ArrayUtils.contains(userIds, userId) : true;
342 }
343 }
344
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700345 private final PlatformIdleStateCallback mPlatformIdleStateCallback;
346
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700347 final class MyHandler extends Handler {
Jeff Brown6f357d32014-01-15 20:40:55 -0800348 public MyHandler(Looper looper) {
349 super(looper, null, true);
350 }
351
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700352 @Override
353 public void handleMessage(Message msg) {
354 BatteryCallback cb = mCallback;
355 switch (msg.what) {
Sudheer Shankac57729a2018-02-09 15:44:42 -0800356 case MSG_REPORT_CPU_UPDATE_NEEDED:
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700357 if (cb != null) {
358 cb.batteryNeedsCpuUpdate();
359 }
360 break;
361 case MSG_REPORT_POWER_CHANGE:
362 if (cb != null) {
363 cb.batteryPowerChanged(msg.arg1 != 0);
364 }
365 break;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700366 case MSG_REPORT_CHARGING:
367 if (cb != null) {
368 final String action;
369 synchronized (BatteryStatsImpl.this) {
370 action = mCharging ? BatteryManager.ACTION_CHARGING
371 : BatteryManager.ACTION_DISCHARGING;
372 }
373 Intent intent = new Intent(action);
374 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
375 cb.batterySendBroadcast(intent);
376 }
377 break;
Fyodor Kupolov8aa51242018-04-23 12:44:51 -0700378 case MSG_REPORT_RESET_STATS:
379 if (cb != null) {
380 cb.batteryStatsReset();
381 }
382 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700383 }
384 }
385
Sudheer Shankac57729a2018-02-09 15:44:42 -0800386 public void postBatteryNeedsCpuUpdateMsg() {
387 mHandler.sendEmptyMessage(MSG_REPORT_CPU_UPDATE_NEEDED);
388 }
389
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800390 /**
391 * Update per-freq cpu times for all the uids in {@link #mPendingUids}.
392 */
Sudheer Shankae544d162017-12-28 17:06:20 -0800393 public void updateProcStateCpuTimes(boolean onBattery, boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800394 final SparseIntArray uidStates;
395 synchronized (BatteryStatsImpl.this) {
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800396 if (!mConstants.TRACK_CPU_TIMES_BY_PROC_STATE) {
397 return;
398 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800399 if(!initKernelSingleUidTimeReaderLocked()) {
400 return;
401 }
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800402 // If the KernelSingleUidTimeReader has stale cpu times, then we shouldn't try to
403 // compute deltas since it might result in mis-attributing cpu times to wrong states.
404 if (mKernelSingleUidTimeReader.hasStaleData()) {
405 mPendingUids.clear();
406 return;
407 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800408
409 if (mPendingUids.size() == 0) {
410 return;
411 }
412 uidStates = mPendingUids.clone();
413 mPendingUids.clear();
414 }
415 for (int i = uidStates.size() - 1; i >= 0; --i) {
416 final int uid = uidStates.keyAt(i);
417 final int procState = uidStates.valueAt(i);
418 final int[] isolatedUids;
419 final Uid u;
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800420 synchronized (BatteryStatsImpl.this) {
421 // It's possible that uid no longer exists and any internal references have
422 // already been deleted, so using {@link #getAvailableUidStatsLocked} to avoid
423 // creating an UidStats object if it doesn't already exist.
424 u = getAvailableUidStatsLocked(uid);
425 if (u == null) {
426 continue;
427 }
428 if (u.mChildUids == null) {
429 isolatedUids = null;
430 } else {
431 isolatedUids = u.mChildUids.toArray();
432 for (int j = isolatedUids.length - 1; j >= 0; --j) {
433 isolatedUids[j] = u.mChildUids.get(j);
434 }
435 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800436 }
437 long[] cpuTimesMs = mKernelSingleUidTimeReader.readDeltaMs(uid);
438 if (isolatedUids != null) {
439 for (int j = isolatedUids.length - 1; j >= 0; --j) {
440 cpuTimesMs = addCpuTimes(cpuTimesMs,
441 mKernelSingleUidTimeReader.readDeltaMs(isolatedUids[j]));
442 }
443 }
444 if (onBattery && cpuTimesMs != null) {
445 synchronized (BatteryStatsImpl.this) {
Sudheer Shankae544d162017-12-28 17:06:20 -0800446 u.addProcStateTimesMs(procState, cpuTimesMs, onBattery);
447 u.addProcStateScreenOffTimesMs(procState, cpuTimesMs, onBatteryScreenOff);
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800448 }
449 }
450 }
451 }
452
Mike Ma234d1822018-03-13 18:53:21 -0700453 public void clearPendingRemovedUids() {
454 long cutOffTime = mClocks.elapsedRealtime() - mConstants.UID_REMOVE_DELAY_MS;
455 while (!mPendingRemovedUids.isEmpty()
456 && mPendingRemovedUids.peek().timeAddedInQueue < cutOffTime) {
457 mPendingRemovedUids.poll().remove();
458 }
459 }
460
Sudheer Shankae544d162017-12-28 17:06:20 -0800461 public void copyFromAllUidsCpuTimes() {
462 synchronized (BatteryStatsImpl.this) {
463 copyFromAllUidsCpuTimes(
464 mOnBatteryTimeBase.isRunning(), mOnBatteryScreenOffTimeBase.isRunning());
465 }
466 }
467
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800468 /**
469 * When the battery/screen state changes, we don't attribute the cpu times to any process
470 * but we still need to snapshots of all uids to get correct deltas later on. Since we
471 * already read this data for updating per-freq cpu times, we can use the same data for
472 * per-procstate cpu times.
473 */
Sudheer Shankae544d162017-12-28 17:06:20 -0800474 public void copyFromAllUidsCpuTimes(boolean onBattery, boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800475 synchronized (BatteryStatsImpl.this) {
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800476 if (!mConstants.TRACK_CPU_TIMES_BY_PROC_STATE) {
477 return;
478 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800479 if(!initKernelSingleUidTimeReaderLocked()) {
480 return;
481 }
482
483 final SparseArray<long[]> allUidCpuFreqTimesMs =
484 mKernelUidCpuFreqTimeReader.getAllUidCpuFreqTimeMs();
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800485 // If the KernelSingleUidTimeReader has stale cpu times, then we shouldn't try to
486 // compute deltas since it might result in mis-attributing cpu times to wrong states.
487 if (mKernelSingleUidTimeReader.hasStaleData()) {
488 mKernelSingleUidTimeReader.setAllUidsCpuTimesMs(allUidCpuFreqTimesMs);
489 mKernelSingleUidTimeReader.markDataAsStale(false);
490 mPendingUids.clear();
491 return;
492 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800493 for (int i = allUidCpuFreqTimesMs.size() - 1; i >= 0; --i) {
494 final int uid = allUidCpuFreqTimesMs.keyAt(i);
495 final Uid u = getAvailableUidStatsLocked(mapUid(uid));
496 if (u == null) {
497 continue;
498 }
499 final long[] cpuTimesMs = allUidCpuFreqTimesMs.valueAt(i);
500 if (cpuTimesMs == null) {
501 continue;
502 }
503 final long[] deltaTimesMs = mKernelSingleUidTimeReader.computeDelta(
504 uid, cpuTimesMs.clone());
Sudheer Shankae544d162017-12-28 17:06:20 -0800505 if (onBattery && deltaTimesMs != null) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800506 final int procState;
507 final int idx = mPendingUids.indexOfKey(uid);
508 if (idx >= 0) {
509 procState = mPendingUids.valueAt(idx);
510 mPendingUids.removeAt(idx);
511 } else {
512 procState = u.mProcessState;
513 }
514 if (procState >= 0 && procState < Uid.NUM_PROCESS_STATE) {
Sudheer Shankae544d162017-12-28 17:06:20 -0800515 u.addProcStateTimesMs(procState, deltaTimesMs, onBattery);
516 u.addProcStateScreenOffTimesMs(procState, deltaTimesMs, onBatteryScreenOff);
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800517 }
518 }
519 }
520 }
521 }
522
523 @VisibleForTesting
524 public long[] addCpuTimes(long[] timesA, long[] timesB) {
525 if (timesA != null && timesB != null) {
526 for (int i = timesA.length - 1; i >= 0; --i) {
527 timesA[i] += timesB[i];
528 }
529 return timesA;
530 }
531 return timesA == null ? (timesB == null ? null : timesB) : timesA;
532 }
533
534 @GuardedBy("this")
535 private boolean initKernelSingleUidTimeReaderLocked() {
536 if (mKernelSingleUidTimeReader == null) {
537 if (mPowerProfile == null) {
538 return false;
539 }
540 if (mCpuFreqs == null) {
541 mCpuFreqs = mKernelUidCpuFreqTimeReader.readFreqs(mPowerProfile);
542 }
543 if (mCpuFreqs != null) {
544 mKernelSingleUidTimeReader = new KernelSingleUidTimeReader(mCpuFreqs.length);
545 } else {
546 mPerProcStateCpuTimesAvailable = mKernelUidCpuFreqTimeReader.allUidTimesAvailable();
547 return false;
548 }
549 }
550 mPerProcStateCpuTimesAvailable = mKernelUidCpuFreqTimeReader.allUidTimesAvailable()
551 && mKernelSingleUidTimeReader.singleUidCpuTimesAvailable();
552 return true;
553 }
554
Joe Onoratoabded112016-02-08 16:49:39 -0800555 public interface Clocks {
556 public long elapsedRealtime();
557 public long uptimeMillis();
558 }
559
560 public static class SystemClocks implements Clocks {
561 public long elapsedRealtime() {
562 return SystemClock.elapsedRealtime();
563 }
564
565 public long uptimeMillis() {
566 return SystemClock.uptimeMillis();
567 }
568 }
569
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700570 public interface ExternalStatsSync {
Adam Lesinski14ae39a2017-05-26 11:50:40 -0700571 int UPDATE_CPU = 0x01;
572 int UPDATE_WIFI = 0x02;
573 int UPDATE_RADIO = 0x04;
574 int UPDATE_BT = 0x08;
Bookatz50df7112017-08-04 14:53:26 -0700575 int UPDATE_RPM = 0x10; // 16
576 int UPDATE_ALL = UPDATE_CPU | UPDATE_WIFI | UPDATE_RADIO | UPDATE_BT | UPDATE_RPM;
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800577
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700578 Future<?> scheduleSync(String reason, int flags);
579 Future<?> scheduleCpuSyncDueToRemovedUid(int uid);
Sudheer Shankac20379e2018-02-15 00:06:21 -0800580 Future<?> scheduleReadProcStateCpuTimes(boolean onBattery, boolean onBatteryScreenOff,
581 long delayMillis);
Sudheer Shankae544d162017-12-28 17:06:20 -0800582 Future<?> scheduleCopyFromAllUidsCpuTimes(boolean onBattery, boolean onBatteryScreenOff);
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800583 Future<?> scheduleCpuSyncDueToSettingChange();
Sudheer Shankac57729a2018-02-09 15:44:42 -0800584 Future<?> scheduleCpuSyncDueToScreenStateChange(boolean onBattery,
585 boolean onBatteryScreenOff);
586 Future<?> scheduleCpuSyncDueToWakelockChange(long delayMillis);
587 void cancelCpuSyncDueToWakelockChange();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700588 }
589
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800590 public Handler mHandler;
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700591 private ExternalStatsSync mExternalSync = null;
Sudheer Shanka38383232017-07-25 09:55:03 -0700592 @VisibleForTesting
593 protected UserInfoProvider mUserInfoProvider = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700594
595 private BatteryCallback mCallback;
596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800597 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -0800598 * Mapping isolated uids to the actual owning app uid.
599 */
600 final SparseIntArray mIsolatedUids = new SparseIntArray();
601
602 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800603 * The statistics we have collected organized by uids.
604 */
Adam Lesinski50e47602015-12-04 17:04:54 -0800605 final SparseArray<BatteryStatsImpl.Uid> mUidStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606
607 // A set of pools of currently active timers. When a timer is queried, we will divide the
608 // elapsed time by the number of active timers to arrive at that timer's share of the time.
609 // In order to do this, we must refresh each timer whenever the number of active timers
610 // changes.
Sudheer Shanka38383232017-07-25 09:55:03 -0700611 @VisibleForTesting
612 protected ArrayList<StopwatchTimer> mPartialTimers = new ArrayList<>();
Adam Lesinskie08af192015-03-25 16:42:59 -0700613 final ArrayList<StopwatchTimer> mFullTimers = new ArrayList<>();
614 final ArrayList<StopwatchTimer> mWindowTimers = new ArrayList<>();
Jeff Brown6a8bd7b2015-06-19 15:07:51 -0700615 final ArrayList<StopwatchTimer> mDrawTimers = new ArrayList<>();
Adam Lesinskie08af192015-03-25 16:42:59 -0700616 final SparseArray<ArrayList<StopwatchTimer>> mSensorTimers = new SparseArray<>();
617 final ArrayList<StopwatchTimer> mWifiRunningTimers = new ArrayList<>();
618 final ArrayList<StopwatchTimer> mFullWifiLockTimers = new ArrayList<>();
619 final ArrayList<StopwatchTimer> mWifiMulticastTimers = new ArrayList<>();
620 final ArrayList<StopwatchTimer> mWifiScanTimers = new ArrayList<>();
621 final SparseArray<ArrayList<StopwatchTimer>> mWifiBatchedScanTimers = new SparseArray<>();
622 final ArrayList<StopwatchTimer> mAudioTurnedOnTimers = new ArrayList<>();
623 final ArrayList<StopwatchTimer> mVideoTurnedOnTimers = new ArrayList<>();
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700624 final ArrayList<StopwatchTimer> mFlashlightTurnedOnTimers = new ArrayList<>();
625 final ArrayList<StopwatchTimer> mCameraTurnedOnTimers = new ArrayList<>();
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800626 final ArrayList<StopwatchTimer> mBluetoothScanOnTimers = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700628 // Last partial timers we use for distributing CPU usage.
Sudheer Shanka38383232017-07-25 09:55:03 -0700629 @VisibleForTesting
630 protected ArrayList<StopwatchTimer> mLastPartialTimers = new ArrayList<>();
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 // These are the objects that will want to do something when the device
633 // is unplugged from power.
Joe Onoratoabded112016-02-08 16:49:39 -0800634 protected final TimeBase mOnBatteryTimeBase = new TimeBase();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800635
636 // These are the objects that will want to do something when the device
Mike Mac2f518a2017-09-19 16:06:03 -0700637 // is unplugged from power *and* the screen is off or doze.
638 protected final TimeBase mOnBatteryScreenOffTimeBase = new TimeBase();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800639
640 // Set to true when we want to distribute CPU across wakelocks for the next
641 // CPU update, even if we aren't currently running wake locks.
642 boolean mDistributeWakelockCpu;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700643
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700644 boolean mShuttingDown;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700645
Dianne Hackborn37de0982014-05-09 09:32:18 -0700646 final HistoryEventTracker mActiveEvents = new HistoryEventTracker();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800647
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700648 long mHistoryBaseTime;
Narayan Kamath695cf722017-12-21 18:32:47 +0000649 protected boolean mHaveBatteryLevel = false;
650 protected boolean mRecordingHistory = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700651 int mNumHistoryItems;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700652
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700653 final Parcel mHistoryBuffer = Parcel.obtain();
654 final HistoryItem mHistoryLastWritten = new HistoryItem();
655 final HistoryItem mHistoryLastLastWritten = new HistoryItem();
Dianne Hackborn1fadab52011-04-14 17:57:33 -0700656 final HistoryItem mHistoryReadTmp = new HistoryItem();
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700657 final HistoryItem mHistoryAddTmp = new HistoryItem();
Adam Lesinskie08af192015-03-25 16:42:59 -0700658 final HashMap<HistoryTag, Integer> mHistoryTagPool = new HashMap<>();
Dianne Hackborn099bc622014-01-22 13:39:16 -0800659 String[] mReadHistoryStrings;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -0800660 int[] mReadHistoryUids;
661 int mReadHistoryChars;
662 int mNextHistoryTagIdx = 0;
663 int mNumHistoryTagChars = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700664 int mHistoryBufferLastPos = -1;
665 boolean mHistoryOverflow = false;
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700666 int mActiveHistoryStates = 0xffffffff;
667 int mActiveHistoryStates2 = 0xffffffff;
Dianne Hackborn40c87252014-03-19 16:55:40 -0700668 long mLastHistoryElapsedRealtime = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700669 long mTrackRunningHistoryElapsedRealtime = 0;
670 long mTrackRunningHistoryUptime = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700671
672 final HistoryItem mHistoryCur = new HistoryItem();
673
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700674 HistoryItem mHistory;
675 HistoryItem mHistoryEnd;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700676 HistoryItem mHistoryLastEnd;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700677 HistoryItem mHistoryCache;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700678
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800679 // Used by computeHistoryStepDetails
680 HistoryStepDetails mLastHistoryStepDetails = null;
681 byte mLastHistoryStepLevel = 0;
682 final HistoryStepDetails mCurHistoryStepDetails = new HistoryStepDetails();
683 final HistoryStepDetails mReadHistoryStepDetails = new HistoryStepDetails();
684 final HistoryStepDetails mTmpHistoryStepDetails = new HistoryStepDetails();
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700685
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800686 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700687 * Total time (in milliseconds) spent executing in user code.
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800688 */
689 long mLastStepCpuUserTime;
690 long mCurStepCpuUserTime;
691 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700692 * Total time (in milliseconds) spent executing in kernel code.
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800693 */
694 long mLastStepCpuSystemTime;
695 long mCurStepCpuSystemTime;
696 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700697 * Times from /proc/stat (but measured in milliseconds).
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800698 */
699 long mLastStepStatUserTime;
700 long mLastStepStatSystemTime;
701 long mLastStepStatIOWaitTime;
702 long mLastStepStatIrqTime;
703 long mLastStepStatSoftIrqTime;
704 long mLastStepStatIdleTime;
705 long mCurStepStatUserTime;
706 long mCurStepStatSystemTime;
707 long mCurStepStatIOWaitTime;
708 long mCurStepStatIrqTime;
709 long mCurStepStatSoftIrqTime;
710 long mCurStepStatIdleTime;
711
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700712 private HistoryItem mHistoryIterator;
713 private boolean mReadOverflow;
714 private boolean mIteratingHistory;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 int mStartCount;
717
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -0800718 long mStartClockTime;
Dianne Hackborncd0e3352014-08-07 17:08:09 -0700719 String mStartPlatformVersion;
720 String mEndPlatformVersion;
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -0800721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 long mUptime;
723 long mUptimeStart;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 long mRealtime;
725 long mRealtimeStart;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700726
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800727 int mWakeLockNesting;
728 boolean mWakeLockImportant;
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700729 public boolean mRecordAllHistory;
Dianne Hackborn9a755432014-05-15 17:05:22 -0700730 boolean mNoAutoReset;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800731
Mike Mac2f518a2017-09-19 16:06:03 -0700732 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
733 protected int mScreenState = Display.STATE_UNKNOWN;
734 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
735 protected StopwatchTimer mScreenOnTimer;
736 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
737 protected StopwatchTimer mScreenDozeTimer;
Amith Yamasani3718aaa2009-06-09 06:32:35 -0700738
Dianne Hackborn617f8772009-03-31 15:04:46 -0700739 int mScreenBrightnessBin = -1;
Evan Millarc64edde2009-04-18 12:26:32 -0700740 final StopwatchTimer[] mScreenBrightnessTimer = new StopwatchTimer[NUM_SCREEN_BRIGHTNESS_BINS];
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700741
Amith Yamasani674c9bb2017-02-01 09:45:17 -0800742 boolean mPretendScreenOff;
743
Jeff Browne95c3cd2014-05-02 16:59:26 -0700744 boolean mInteractive;
745 StopwatchTimer mInteractiveTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700746
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700747 boolean mPowerSaveModeEnabled;
748 StopwatchTimer mPowerSaveModeEnabledTimer;
749
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700750 boolean mDeviceIdling;
751 StopwatchTimer mDeviceIdlingTimer;
752
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700753 boolean mDeviceLightIdling;
754 StopwatchTimer mDeviceLightIdlingTimer;
755
756 int mDeviceIdleMode;
757 long mLastIdleTimeStart;
758 long mLongestLightIdleTime;
759 long mLongestFullIdleTime;
760 StopwatchTimer mDeviceIdleModeLightTimer;
761 StopwatchTimer mDeviceIdleModeFullTimer;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800763 boolean mPhoneOn;
Evan Millarc64edde2009-04-18 12:26:32 -0700764 StopwatchTimer mPhoneOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700765
Dianne Hackborn10eaa852014-07-22 22:54:55 -0700766 int mAudioOnNesting;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700767 StopwatchTimer mAudioOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700768
Dianne Hackborn10eaa852014-07-22 22:54:55 -0700769 int mVideoOnNesting;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700770 StopwatchTimer mVideoOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700771
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700772 int mFlashlightOnNesting;
Dianne Hackbornabc7c492014-06-30 16:57:46 -0700773 StopwatchTimer mFlashlightOnTimer;
774
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700775 int mCameraOnNesting;
776 StopwatchTimer mCameraOnTimer;
777
Mike Mafbc01fc2018-04-02 10:28:28 -0700778 private static final int USB_DATA_UNKNOWN = 0;
779 private static final int USB_DATA_DISCONNECTED = 1;
780 private static final int USB_DATA_CONNECTED = 2;
781 int mUsbDataState = USB_DATA_UNKNOWN;
Mike Ma926a97c2018-03-25 02:32:35 -0700782
Siddharth Ray78ccaf52017-12-23 16:16:21 -0800783 int mGpsSignalQualityBin = -1;
Narayan Kamathefa0fe62018-02-05 16:04:43 +0000784 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
785 protected final StopwatchTimer[] mGpsSignalQualityTimer =
Siddharth Ray78ccaf52017-12-23 16:16:21 -0800786 new StopwatchTimer[GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS];
787
Dianne Hackborn627bba72009-03-24 22:32:56 -0700788 int mPhoneSignalStrengthBin = -1;
Dianne Hackborne4a59512010-12-07 11:08:07 -0800789 int mPhoneSignalStrengthBinRaw = -1;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700790 final StopwatchTimer[] mPhoneSignalStrengthsTimer =
Wink Saville52840902011-02-18 12:40:47 -0800791 new StopwatchTimer[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
Amith Yamasanif37447b2009-10-08 18:28:01 -0700792
793 StopwatchTimer mPhoneSignalScanningTimer;
794
Dianne Hackborn627bba72009-03-24 22:32:56 -0700795 int mPhoneDataConnectionType = -1;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700796 final StopwatchTimer[] mPhoneDataConnectionsTimer =
Evan Millarc64edde2009-04-18 12:26:32 -0700797 new StopwatchTimer[NUM_DATA_CONNECTION_TYPES];
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700798
Dianne Hackborn57ed6a62013-12-09 18:15:56 -0800799 final LongSamplingCounter[] mNetworkByteActivityCounters =
800 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
801 final LongSamplingCounter[] mNetworkPacketActivityCounters =
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700802 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
803
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800804 /**
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -0800805 * The WiFi Overall wakelock timer
806 * This timer tracks the actual aggregate time for which MC wakelocks are enabled
807 * since addition of per UID timers would not result in an accurate value due to overlapp of
808 * per uid wakelock timers
809 */
810 StopwatchTimer mWifiMulticastWakelockTimer;
811
812 /**
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800813 * The WiFi controller activity (time in tx, rx, idle, and power consumed) for the device.
814 */
815 ControllerActivityCounterImpl mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -0700816
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800817 /**
818 * The Bluetooth controller activity (time in tx, rx, idle, and power consumed) for the device.
819 */
820 ControllerActivityCounterImpl mBluetoothActivity;
821
822 /**
823 * The Modem controller activity (time in tx, rx, idle, and power consumed) for the device.
824 */
825 ControllerActivityCounterImpl mModemActivity;
826
827 /**
828 * Whether the device supports WiFi controller energy reporting. This is set to true on
829 * the first WiFi energy report. See {@link #mWifiActivity}.
830 */
831 boolean mHasWifiReporting = false;
832
833 /**
834 * Whether the device supports Bluetooth controller energy reporting. This is set to true on
835 * the first Bluetooth energy report. See {@link #mBluetoothActivity}.
836 */
837 boolean mHasBluetoothReporting = false;
838
839 /**
840 * Whether the device supports Modem controller energy reporting. This is set to true on
841 * the first Modem energy report. See {@link #mModemActivity}.
842 */
843 boolean mHasModemReporting = false;
Adam Lesinski33dac552015-03-09 15:24:48 -0700844
The Android Open Source Project10592532009-03-18 17:39:46 -0700845 boolean mWifiOn;
Evan Millarc64edde2009-04-18 12:26:32 -0700846 StopwatchTimer mWifiOnTimer;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -0700847
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700848 boolean mGlobalWifiRunning;
849 StopwatchTimer mGlobalWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700850
Dianne Hackbornca1bf212014-02-14 14:18:36 -0800851 int mWifiState = -1;
852 final StopwatchTimer[] mWifiStateTimer = new StopwatchTimer[NUM_WIFI_STATES];
853
Dianne Hackborn3251b902014-06-20 14:40:53 -0700854 int mWifiSupplState = -1;
855 final StopwatchTimer[] mWifiSupplStateTimer = new StopwatchTimer[NUM_WIFI_SUPPL_STATES];
856
857 int mWifiSignalStrengthBin = -1;
858 final StopwatchTimer[] mWifiSignalStrengthsTimer =
859 new StopwatchTimer[NUM_WIFI_SIGNAL_STRENGTH_BINS];
860
Siddharth Rayb50a6842017-12-14 15:15:28 -0800861 StopwatchTimer mWifiActiveTimer;
862
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800863 int mBluetoothScanNesting;
Bookatz867c0d72017-03-07 18:23:42 -0800864 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
865 protected StopwatchTimer mBluetoothScanTimer;
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800866
Siddharth Rayf5e796a2018-01-22 18:18:17 -0800867 boolean mIsCellularTxPowerHigh = false;
868
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700869 int mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackbornf7097a52014-05-13 09:56:14 -0700870 long mMobileRadioActiveStartTime;
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800871 StopwatchTimer mMobileRadioActiveTimer;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800872 StopwatchTimer mMobileRadioActivePerAppTimer;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700873 LongSamplingCounter mMobileRadioActiveAdjustedTime;
Dianne Hackbornd45665b2014-02-26 12:35:32 -0800874 LongSamplingCounter mMobileRadioActiveUnknownTime;
875 LongSamplingCounter mMobileRadioActiveUnknownCount;
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800876
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700877 int mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 /**
880 * These provide time bases that discount the time the device is plugged
881 * in to power.
882 */
883 boolean mOnBattery;
Sudheer Shanka38383232017-07-25 09:55:03 -0700884 @VisibleForTesting
885 protected boolean mOnBatteryInternal;
Amith Yamasani3718aaa2009-06-09 06:32:35 -0700886
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700887 /**
888 * External reporting of whether the device is actually charging.
889 */
890 boolean mCharging = true;
891 int mLastChargingStateLevel;
892
The Android Open Source Project10592532009-03-18 17:39:46 -0700893 /*
894 * These keep track of battery levels (1-100) at the last plug event and the last unplug event.
895 */
Evan Millar633a1742009-04-02 16:36:33 -0700896 int mDischargeStartLevel;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700897 int mDischargeUnplugLevel;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700898 int mDischargePlugLevel;
Evan Millar633a1742009-04-02 16:36:33 -0700899 int mDischargeCurrentLevel;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700900 int mCurrentBatteryLevel;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -0700901 int mLowDischargeAmountSinceCharge;
902 int mHighDischargeAmountSinceCharge;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -0800903 int mDischargeScreenOnUnplugLevel;
904 int mDischargeScreenOffUnplugLevel;
Mike Mac2f518a2017-09-19 16:06:03 -0700905 int mDischargeScreenDozeUnplugLevel;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -0800906 int mDischargeAmountScreenOn;
907 int mDischargeAmountScreenOnSinceCharge;
908 int mDischargeAmountScreenOff;
909 int mDischargeAmountScreenOffSinceCharge;
Mike Mac2f518a2017-09-19 16:06:03 -0700910 int mDischargeAmountScreenDoze;
911 int mDischargeAmountScreenDozeSinceCharge;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700912
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700913 private LongSamplingCounter mDischargeScreenOffCounter;
Mike Mac2f518a2017-09-19 16:06:03 -0700914 private LongSamplingCounter mDischargeScreenDozeCounter;
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700915 private LongSamplingCounter mDischargeCounter;
Mike Ma15313c92017-11-15 17:58:21 -0800916 private LongSamplingCounter mDischargeLightDozeCounter;
917 private LongSamplingCounter mDischargeDeepDozeCounter;
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700918
Dianne Hackborncd0e3352014-08-07 17:08:09 -0700919 static final int MAX_LEVEL_STEPS = 200;
Dianne Hackborn260c5022014-04-29 11:23:16 -0700920
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700921 int mInitStepMode = 0;
922 int mCurStepMode = 0;
923 int mModStepMode = 0;
924
Dianne Hackborn260c5022014-04-29 11:23:16 -0700925 int mLastDischargeStepLevel;
Dianne Hackborn29325132014-05-21 15:01:03 -0700926 int mMinDischargeStepLevel;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800927 final LevelStepTracker mDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS);
928 final LevelStepTracker mDailyDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700929 ArrayList<PackageChange> mDailyPackageChanges;
Dianne Hackborn260c5022014-04-29 11:23:16 -0700930
931 int mLastChargeStepLevel;
Dianne Hackborn29325132014-05-21 15:01:03 -0700932 int mMaxChargeStepLevel;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800933 final LevelStepTracker mChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS);
934 final LevelStepTracker mDailyChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2);
935
936 static final int MAX_DAILY_ITEMS = 10;
937
938 long mDailyStartTime = 0;
939 long mNextMinDailyDeadline = 0;
940 long mNextMaxDailyDeadline = 0;
941
942 final ArrayList<DailyItem> mDailyItems = new ArrayList<>();
Dianne Hackborn260c5022014-04-29 11:23:16 -0700943
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800944 long mLastWriteTime = 0; // Milliseconds
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700945
Amith Yamasanif37447b2009-10-08 18:28:01 -0700946 private int mPhoneServiceState = -1;
Dianne Hackborne4a59512010-12-07 11:08:07 -0800947 private int mPhoneServiceStateRaw = -1;
948 private int mPhoneSimStateRaw = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -0700949
Dianne Hackborn1e01d162014-12-04 17:46:42 -0800950 private int mNumConnectivityChange;
951 private int mLoadedNumConnectivityChange;
952 private int mUnpluggedNumConnectivityChange;
953
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700954 private int mEstimatedBatteryCapacity = -1;
955
Jocelyn Dangc627d102017-04-14 13:15:14 -0700956 private int mMinLearnedBatteryCapacity = -1;
957 private int mMaxLearnedBatteryCapacity = -1;
Adam Lesinski041d9172016-12-12 12:03:56 -0800958
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700959 private long[] mCpuFreqs;
960
Sudheer Shanka38383232017-07-25 09:55:03 -0700961 @VisibleForTesting
962 protected PowerProfile mPowerProfile;
Adam Lesinskie08af192015-03-25 16:42:59 -0700963
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800964 @GuardedBy("this")
965 private final Constants mConstants;
966
Evan Millarc64edde2009-04-18 12:26:32 -0700967 /*
Bookatz50df7112017-08-04 14:53:26 -0700968 * Holds a SamplingTimer associated with each Resource Power Manager state and voter,
969 * recording their times when on-battery (regardless of screen state).
970 */
971 private final HashMap<String, SamplingTimer> mRpmStats = new HashMap<>();
972 /** Times for each Resource Power Manager state and voter when screen-off and on-battery. */
973 private final HashMap<String, SamplingTimer> mScreenOffRpmStats = new HashMap<>();
974
975 @Override
976 public Map<String, ? extends Timer> getRpmStats() {
977 return mRpmStats;
978 }
979
Bookatz82b341172017-09-07 19:06:08 -0700980 // TODO: Note: screenOffRpmStats has been disabled via SCREEN_OFF_RPM_STATS_ENABLED.
Bookatz50df7112017-08-04 14:53:26 -0700981 @Override
982 public Map<String, ? extends Timer> getScreenOffRpmStats() {
983 return mScreenOffRpmStats;
984 }
985
986 /*
Evan Millarc64edde2009-04-18 12:26:32 -0700987 * Holds a SamplingTimer associated with each kernel wakelock name being tracked.
988 */
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700989 private final HashMap<String, SamplingTimer> mKernelWakelockStats = new HashMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700990
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700991 public Map<String, ? extends Timer> getKernelWakelockStats() {
Evan Millarc64edde2009-04-18 12:26:32 -0700992 return mKernelWakelockStats;
993 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700994
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700995 String mLastWakeupReason = null;
996 long mLastWakeupUptimeMs = 0;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -0700997 private final HashMap<String, SamplingTimer> mWakeupReasonStats = new HashMap<>();
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700998
Dianne Hackbornc3940bc2014-09-05 15:50:25 -0700999 public Map<String, ? extends Timer> getWakeupReasonStats() {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001000 return mWakeupReasonStats;
1001 }
1002
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001003 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -07001004 public long getUahDischarge(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -07001005 return mDischargeCounter.getCountLocked(which);
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001006 }
1007
1008 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -07001009 public long getUahDischargeScreenOff(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -07001010 return mDischargeScreenOffCounter.getCountLocked(which);
1011 }
1012
1013 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -07001014 public long getUahDischargeScreenDoze(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -07001015 return mDischargeScreenDozeCounter.getCountLocked(which);
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001016 }
1017
Adam Lesinskif9b20a92016-06-17 17:30:01 -07001018 @Override
Mike Ma15313c92017-11-15 17:58:21 -08001019 public long getUahDischargeLightDoze(int which) {
1020 return mDischargeLightDozeCounter.getCountLocked(which);
1021 }
1022
1023 @Override
1024 public long getUahDischargeDeepDoze(int which) {
1025 return mDischargeDeepDozeCounter.getCountLocked(which);
1026 }
1027
1028 @Override
Adam Lesinskif9b20a92016-06-17 17:30:01 -07001029 public int getEstimatedBatteryCapacity() {
1030 return mEstimatedBatteryCapacity;
1031 }
1032
Jocelyn Dangc627d102017-04-14 13:15:14 -07001033 @Override
1034 public int getMinLearnedBatteryCapacity() {
1035 return mMinLearnedBatteryCapacity;
1036 }
1037
1038 @Override
1039 public int getMaxLearnedBatteryCapacity() {
1040 return mMaxLearnedBatteryCapacity;
1041 }
1042
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043 public BatteryStatsImpl() {
Joe Onoratoabded112016-02-08 16:49:39 -08001044 this(new SystemClocks());
1045 }
1046
1047 public BatteryStatsImpl(Clocks clocks) {
1048 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07001049 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07001050 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08001051 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001052 mHandler = null;
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07001053 mPlatformIdleStateCallback = null;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -07001054 mUserInfoProvider = null;
Sudheer Shanka5c19b892018-01-05 17:25:46 -08001055 mConstants = new Constants(mHandler);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07001056 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 }
1058
Joe Onoratoabded112016-02-08 16:49:39 -08001059 private void init(Clocks clocks) {
1060 mClocks = clocks;
Joe Onoratoabded112016-02-08 16:49:39 -08001061 }
1062
Adam Lesinski14ae39a2017-05-26 11:50:40 -07001063 public interface TimeBaseObs {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001064 void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime);
1065 void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime);
1066 }
1067
Joe Onoratoabded112016-02-08 16:49:39 -08001068 // methods are protected not private to be VisibleForTesting
1069 public static class TimeBase {
1070 protected final ArrayList<TimeBaseObs> mObservers = new ArrayList<>();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001071
Joe Onoratoabded112016-02-08 16:49:39 -08001072 protected long mUptime;
1073 protected long mRealtime;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001074
Joe Onoratoabded112016-02-08 16:49:39 -08001075 protected boolean mRunning;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001076
Joe Onoratoabded112016-02-08 16:49:39 -08001077 protected long mPastUptime;
1078 protected long mUptimeStart;
1079 protected long mPastRealtime;
1080 protected long mRealtimeStart;
1081 protected long mUnpluggedUptime;
1082 protected long mUnpluggedRealtime;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001083
1084 public void dump(PrintWriter pw, String prefix) {
1085 StringBuilder sb = new StringBuilder(128);
1086 pw.print(prefix); pw.print("mRunning="); pw.println(mRunning);
1087 sb.setLength(0);
1088 sb.append(prefix);
1089 sb.append("mUptime=");
Dianne Hackborn4590e522014-03-24 13:36:46 -07001090 formatTimeMs(sb, mUptime / 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001091 pw.println(sb.toString());
1092 sb.setLength(0);
1093 sb.append(prefix);
1094 sb.append("mRealtime=");
Dianne Hackborn4590e522014-03-24 13:36:46 -07001095 formatTimeMs(sb, mRealtime / 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001096 pw.println(sb.toString());
1097 sb.setLength(0);
1098 sb.append(prefix);
1099 sb.append("mPastUptime=");
1100 formatTimeMs(sb, mPastUptime / 1000); sb.append("mUptimeStart=");
1101 formatTimeMs(sb, mUptimeStart / 1000);
1102 sb.append("mUnpluggedUptime="); formatTimeMs(sb, mUnpluggedUptime / 1000);
1103 pw.println(sb.toString());
1104 sb.setLength(0);
1105 sb.append(prefix);
1106 sb.append("mPastRealtime=");
1107 formatTimeMs(sb, mPastRealtime / 1000); sb.append("mRealtimeStart=");
1108 formatTimeMs(sb, mRealtimeStart / 1000);
1109 sb.append("mUnpluggedRealtime="); formatTimeMs(sb, mUnpluggedRealtime / 1000);
1110 pw.println(sb.toString());
1111 }
1112
1113 public void add(TimeBaseObs observer) {
1114 mObservers.add(observer);
1115 }
1116
1117 public void remove(TimeBaseObs observer) {
1118 if (!mObservers.remove(observer)) {
1119 Slog.wtf(TAG, "Removed unknown observer: " + observer);
1120 }
1121 }
1122
Joe Onoratoabded112016-02-08 16:49:39 -08001123 public boolean hasObserver(TimeBaseObs observer) {
1124 return mObservers.contains(observer);
1125 }
1126
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001127 public void init(long uptime, long realtime) {
1128 mRealtime = 0;
1129 mUptime = 0;
1130 mPastUptime = 0;
1131 mPastRealtime = 0;
1132 mUptimeStart = uptime;
1133 mRealtimeStart = realtime;
1134 mUnpluggedUptime = getUptime(mUptimeStart);
1135 mUnpluggedRealtime = getRealtime(mRealtimeStart);
1136 }
1137
1138 public void reset(long uptime, long realtime) {
1139 if (!mRunning) {
1140 mPastUptime = 0;
1141 mPastRealtime = 0;
1142 } else {
1143 mUptimeStart = uptime;
1144 mRealtimeStart = realtime;
Joe Onoratoabded112016-02-08 16:49:39 -08001145 // TODO: Since mUptimeStart was just reset and we are running, getUptime will
1146 // just return mPastUptime. Also, are we sure we don't want to reset that?
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001147 mUnpluggedUptime = getUptime(uptime);
Joe Onoratoabded112016-02-08 16:49:39 -08001148 // TODO: likewise.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001149 mUnpluggedRealtime = getRealtime(realtime);
1150 }
1151 }
1152
1153 public long computeUptime(long curTime, int which) {
1154 switch (which) {
1155 case STATS_SINCE_CHARGED:
1156 return mUptime + getUptime(curTime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001157 case STATS_CURRENT:
1158 return getUptime(curTime);
1159 case STATS_SINCE_UNPLUGGED:
1160 return getUptime(curTime) - mUnpluggedUptime;
1161 }
1162 return 0;
1163 }
1164
1165 public long computeRealtime(long curTime, int which) {
1166 switch (which) {
1167 case STATS_SINCE_CHARGED:
1168 return mRealtime + getRealtime(curTime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001169 case STATS_CURRENT:
1170 return getRealtime(curTime);
1171 case STATS_SINCE_UNPLUGGED:
1172 return getRealtime(curTime) - mUnpluggedRealtime;
1173 }
1174 return 0;
1175 }
1176
1177 public long getUptime(long curTime) {
1178 long time = mPastUptime;
1179 if (mRunning) {
1180 time += curTime - mUptimeStart;
1181 }
1182 return time;
1183 }
1184
1185 public long getRealtime(long curTime) {
1186 long time = mPastRealtime;
1187 if (mRunning) {
1188 time += curTime - mRealtimeStart;
1189 }
1190 return time;
1191 }
1192
1193 public long getUptimeStart() {
1194 return mUptimeStart;
1195 }
1196
1197 public long getRealtimeStart() {
1198 return mRealtimeStart;
1199 }
1200
1201 public boolean isRunning() {
1202 return mRunning;
1203 }
1204
1205 public boolean setRunning(boolean running, long uptime, long realtime) {
1206 if (mRunning != running) {
1207 mRunning = running;
1208 if (running) {
1209 mUptimeStart = uptime;
1210 mRealtimeStart = realtime;
1211 long batteryUptime = mUnpluggedUptime = getUptime(uptime);
1212 long batteryRealtime = mUnpluggedRealtime = getRealtime(realtime);
1213
1214 for (int i = mObservers.size() - 1; i >= 0; i--) {
1215 mObservers.get(i).onTimeStarted(realtime, batteryUptime, batteryRealtime);
1216 }
1217 } else {
1218 mPastUptime += uptime - mUptimeStart;
1219 mPastRealtime += realtime - mRealtimeStart;
1220
1221 long batteryUptime = getUptime(uptime);
1222 long batteryRealtime = getRealtime(realtime);
1223
1224 for (int i = mObservers.size() - 1; i >= 0; i--) {
1225 mObservers.get(i).onTimeStopped(realtime, batteryUptime, batteryRealtime);
1226 }
1227 }
1228 return true;
1229 }
1230 return false;
1231 }
1232
1233 public void readSummaryFromParcel(Parcel in) {
1234 mUptime = in.readLong();
1235 mRealtime = in.readLong();
1236 }
1237
1238 public void writeSummaryToParcel(Parcel out, long uptime, long realtime) {
1239 out.writeLong(computeUptime(uptime, STATS_SINCE_CHARGED));
1240 out.writeLong(computeRealtime(realtime, STATS_SINCE_CHARGED));
1241 }
1242
1243 public void readFromParcel(Parcel in) {
1244 mRunning = false;
1245 mUptime = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001246 mPastUptime = in.readLong();
1247 mUptimeStart = in.readLong();
Dianne Hackbornef640cd2014-03-25 14:41:05 -07001248 mRealtime = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001249 mPastRealtime = in.readLong();
1250 mRealtimeStart = in.readLong();
1251 mUnpluggedUptime = in.readLong();
1252 mUnpluggedRealtime = in.readLong();
1253 }
1254
1255 public void writeToParcel(Parcel out, long uptime, long realtime) {
1256 final long runningUptime = getUptime(uptime);
1257 final long runningRealtime = getRealtime(realtime);
1258 out.writeLong(mUptime);
1259 out.writeLong(runningUptime);
1260 out.writeLong(mUptimeStart);
Dianne Hackbornef640cd2014-03-25 14:41:05 -07001261 out.writeLong(mRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001262 out.writeLong(runningRealtime);
1263 out.writeLong(mRealtimeStart);
1264 out.writeLong(mUnpluggedUptime);
1265 out.writeLong(mUnpluggedRealtime);
1266 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001267 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 /**
Dianne Hackborn617f8772009-03-31 15:04:46 -07001270 * State for keeping track of counting information.
1271 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001272 public static class Counter extends BatteryStats.Counter implements TimeBaseObs {
Christopher Tate4cee7252010-03-19 14:50:40 -07001273 final AtomicInteger mCount = new AtomicInteger();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001274 final TimeBase mTimeBase;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001275 int mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001276 int mUnpluggedCount;
1277 int mPluggedCount;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001278
Bookatz8c6f3c52017-05-24 12:00:17 -07001279 public Counter(TimeBase timeBase, Parcel in) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001280 mTimeBase = timeBase;
Christopher Tate4cee7252010-03-19 14:50:40 -07001281 mPluggedCount = in.readInt();
1282 mCount.set(mPluggedCount);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001283 mLoadedCount = in.readInt();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001284 mUnpluggedCount = in.readInt();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001285 timeBase.add(this);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001286 }
1287
Bookatz8c6f3c52017-05-24 12:00:17 -07001288 public Counter(TimeBase timeBase) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001289 mTimeBase = timeBase;
1290 timeBase.add(this);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001291 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001292
Dianne Hackborn617f8772009-03-31 15:04:46 -07001293 public void writeToParcel(Parcel out) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001294 out.writeInt(mCount.get());
Dianne Hackborn617f8772009-03-31 15:04:46 -07001295 out.writeInt(mLoadedCount);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001296 out.writeInt(mUnpluggedCount);
1297 }
1298
Bookatz8c6f3c52017-05-24 12:00:17 -07001299 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001300 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001301 mUnpluggedCount = mPluggedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001302 }
1303
Bookatz8c6f3c52017-05-24 12:00:17 -07001304 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001305 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001306 mPluggedCount = mCount.get();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001307 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001308
Dianne Hackborn617f8772009-03-31 15:04:46 -07001309 /**
1310 * Writes a possibly null Counter to a Parcel.
1311 *
1312 * @param out the Parcel to be written to.
1313 * @param counter a Counter, or null.
1314 */
Amith Yamasani977e11f2018-02-16 11:29:54 -08001315 public static void writeCounterToParcel(Parcel out, @Nullable Counter counter) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07001316 if (counter == null) {
1317 out.writeInt(0); // indicates null
1318 return;
1319 }
1320 out.writeInt(1); // indicates non-null
1321
1322 counter.writeToParcel(out);
1323 }
1324
Amith Yamasani977e11f2018-02-16 11:29:54 -08001325 /**
1326 * Reads a Counter that was written using {@link #writeCounterToParcel(Parcel, Counter)}.
1327 * @param timeBase the timebase to assign to the Counter
1328 * @param in the parcel to read from
1329 * @return the Counter or null.
1330 */
1331 public static @Nullable Counter readCounterFromParcel(TimeBase timeBase, Parcel in) {
1332 if (in.readInt() == 0) {
1333 return null;
1334 }
1335 return new Counter(timeBase, in);
1336 }
1337
Dianne Hackborn617f8772009-03-31 15:04:46 -07001338 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001339 public int getCountLocked(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001340 int val = mCount.get();
1341 if (which == STATS_SINCE_UNPLUGGED) {
1342 val -= mUnpluggedCount;
1343 } else if (which != STATS_SINCE_CHARGED) {
1344 val -= mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001345 }
1346
1347 return val;
1348 }
1349
1350 public void logState(Printer pw, String prefix) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001351 pw.println(prefix + "mCount=" + mCount.get()
Bookatz8c6f3c52017-05-24 12:00:17 -07001352 + " mLoadedCount=" + mLoadedCount
Dianne Hackborn617f8772009-03-31 15:04:46 -07001353 + " mUnpluggedCount=" + mUnpluggedCount
1354 + " mPluggedCount=" + mPluggedCount);
1355 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001356
Bookatz8c6f3c52017-05-24 12:00:17 -07001357 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1358 public void stepAtomic() {
1359 if (mTimeBase.isRunning()) {
1360 mCount.incrementAndGet();
1361 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001362 }
1363
Bookatz4ebc0642017-05-11 12:21:19 -07001364 void addAtomic(int delta) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001365 if (mTimeBase.isRunning()) {
1366 mCount.addAndGet(delta);
1367 }
Bookatz4ebc0642017-05-11 12:21:19 -07001368 }
1369
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001370 /**
1371 * Clear state of this counter.
1372 */
1373 void reset(boolean detachIfReset) {
1374 mCount.set(0);
Bookatz8c6f3c52017-05-24 12:00:17 -07001375 mLoadedCount = mPluggedCount = mUnpluggedCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001376 if (detachIfReset) {
1377 detach();
1378 }
1379 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001380
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001381 void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001382 mTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001383 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001384
Bookatz8c6f3c52017-05-24 12:00:17 -07001385 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1386 public void writeSummaryFromParcelLocked(Parcel out) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001387 int count = mCount.get();
1388 out.writeInt(count);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001389 }
1390
Bookatz8c6f3c52017-05-24 12:00:17 -07001391 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1392 public void readSummaryFromParcelLocked(Parcel in) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001393 mLoadedCount = in.readInt();
1394 mCount.set(mLoadedCount);
Christopher Tate4cee7252010-03-19 14:50:40 -07001395 mUnpluggedCount = mPluggedCount = mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001396 }
1397 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07001398
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001399 @VisibleForTesting
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001400 public static class LongSamplingCounterArray extends LongCounterArray implements TimeBaseObs {
1401 final TimeBase mTimeBase;
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001402 public long[] mCounts;
1403 public long[] mLoadedCounts;
1404 public long[] mUnpluggedCounts;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001405
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001406 private LongSamplingCounterArray(TimeBase timeBase, Parcel in) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001407 mTimeBase = timeBase;
Sudheer Shankae544d162017-12-28 17:06:20 -08001408 mCounts = in.createLongArray();
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001409 mLoadedCounts = in.createLongArray();
1410 mUnpluggedCounts = in.createLongArray();
1411 timeBase.add(this);
1412 }
1413
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001414 public LongSamplingCounterArray(TimeBase timeBase) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001415 mTimeBase = timeBase;
1416 timeBase.add(this);
1417 }
1418
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001419 private void writeToParcel(Parcel out) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001420 out.writeLongArray(mCounts);
1421 out.writeLongArray(mLoadedCounts);
1422 out.writeLongArray(mUnpluggedCounts);
1423 }
1424
1425 @Override
1426 public void onTimeStarted(long elapsedRealTime, long baseUptime, long baseRealtime) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001427 mUnpluggedCounts = copyArray(mCounts, mUnpluggedCounts);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001428 }
1429
1430 @Override
1431 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001432 }
1433
1434 @Override
1435 public long[] getCountsLocked(int which) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001436 long[] val = copyArray(mCounts, null);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001437 if (which == STATS_SINCE_UNPLUGGED) {
1438 subtract(val, mUnpluggedCounts);
1439 } else if (which != STATS_SINCE_CHARGED) {
1440 subtract(val, mLoadedCounts);
1441 }
1442 return val;
1443 }
1444
1445 @Override
1446 public void logState(Printer pw, String prefix) {
1447 pw.println(prefix + "mCounts=" + Arrays.toString(mCounts)
1448 + " mLoadedCounts=" + Arrays.toString(mLoadedCounts)
Sudheer Shankae544d162017-12-28 17:06:20 -08001449 + " mUnpluggedCounts=" + Arrays.toString(mUnpluggedCounts));
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001450 }
1451
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001452 public void addCountLocked(long[] counts) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001453 addCountLocked(counts, mTimeBase.isRunning());
1454 }
1455
1456 public void addCountLocked(long[] counts, boolean isRunning) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001457 if (counts == null) {
1458 return;
1459 }
Sudheer Shankae544d162017-12-28 17:06:20 -08001460 if (isRunning) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001461 if (mCounts == null) {
1462 mCounts = new long[counts.length];
1463 }
1464 for (int i = 0; i < counts.length; ++i) {
1465 mCounts[i] += counts[i];
1466 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001467 }
1468 }
1469
Sudheer Shankab8ad5942017-08-08 12:16:09 -07001470 public int getSize() {
1471 return mCounts == null ? 0 : mCounts.length;
1472 }
1473
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001474 /**
1475 * Clear state of this counter.
1476 */
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001477 public void reset(boolean detachIfReset) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001478 fillArray(mCounts, 0);
1479 fillArray(mLoadedCounts, 0);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001480 fillArray(mUnpluggedCounts, 0);
1481 if (detachIfReset) {
1482 detach();
1483 }
1484 }
1485
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001486 public void detach() {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001487 mTimeBase.remove(this);
1488 }
1489
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001490 private void writeSummaryToParcelLocked(Parcel out) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001491 out.writeLongArray(mCounts);
1492 }
1493
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001494 private void readSummaryFromParcelLocked(Parcel in) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001495 mCounts = in.createLongArray();
1496 mLoadedCounts = copyArray(mCounts, mLoadedCounts);
1497 mUnpluggedCounts = copyArray(mCounts, mUnpluggedCounts);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001498 }
1499
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001500 public static void writeToParcel(Parcel out, LongSamplingCounterArray counterArray) {
1501 if (counterArray != null) {
1502 out.writeInt(1);
1503 counterArray.writeToParcel(out);
1504 } else {
1505 out.writeInt(0);
1506 }
1507 }
1508
1509 public static LongSamplingCounterArray readFromParcel(Parcel in, TimeBase timeBase) {
1510 if (in.readInt() != 0) {
1511 return new LongSamplingCounterArray(timeBase, in);
1512 } else {
1513 return null;
1514 }
1515 }
1516
1517 public static void writeSummaryToParcelLocked(Parcel out,
1518 LongSamplingCounterArray counterArray) {
1519 if (counterArray != null) {
1520 out.writeInt(1);
1521 counterArray.writeSummaryToParcelLocked(out);
1522 } else {
1523 out.writeInt(0);
1524 }
1525 }
1526
1527 public static LongSamplingCounterArray readSummaryFromParcelLocked(Parcel in,
1528 TimeBase timeBase) {
1529 if (in.readInt() != 0) {
1530 final LongSamplingCounterArray counterArray
1531 = new LongSamplingCounterArray(timeBase);
1532 counterArray.readSummaryFromParcelLocked(in);
1533 return counterArray;
1534 } else {
1535 return null;
1536 }
1537 }
1538
Bookatz8c6f3c52017-05-24 12:00:17 -07001539 private static void fillArray(long[] a, long val) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001540 if (a != null) {
1541 Arrays.fill(a, val);
1542 }
1543 }
1544
Bookatz8c6f3c52017-05-24 12:00:17 -07001545 private static void subtract(@NonNull long[] val, long[] toSubtract) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001546 if (toSubtract == null) {
1547 return;
1548 }
1549 for (int i = 0; i < val.length; i++) {
1550 val[i] -= toSubtract[i];
1551 }
1552 }
1553
Bookatz8c6f3c52017-05-24 12:00:17 -07001554 private static long[] copyArray(long[] src, long[] dest) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001555 if (src == null) {
1556 return null;
1557 } else {
1558 if (dest == null) {
1559 dest = new long[src.length];
1560 }
1561 System.arraycopy(src, 0, dest, 0, src.length);
1562 return dest;
1563 }
1564 }
1565 }
1566
Mike Ma561a8d92018-03-20 18:24:05 -07001567 @VisibleForTesting
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001568 public static class LongSamplingCounter extends LongCounter implements TimeBaseObs {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001569 final TimeBase mTimeBase;
Mike Ma561a8d92018-03-20 18:24:05 -07001570 public long mCount;
1571 public long mCurrentCount;
1572 public long mLoadedCount;
1573 public long mUnpluggedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001574
Mike Ma561a8d92018-03-20 18:24:05 -07001575 public LongSamplingCounter(TimeBase timeBase, Parcel in) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001576 mTimeBase = timeBase;
Sudheer Shankac57729a2018-02-09 15:44:42 -08001577 mCount = in.readLong();
Mike Ma561a8d92018-03-20 18:24:05 -07001578 mCurrentCount = in.readLong();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001579 mLoadedCount = in.readLong();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001580 mUnpluggedCount = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001581 timeBase.add(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001582 }
1583
Mike Ma561a8d92018-03-20 18:24:05 -07001584 public LongSamplingCounter(TimeBase timeBase) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001585 mTimeBase = timeBase;
1586 timeBase.add(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001587 }
1588
1589 public void writeToParcel(Parcel out) {
1590 out.writeLong(mCount);
Mike Ma561a8d92018-03-20 18:24:05 -07001591 out.writeLong(mCurrentCount);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001592 out.writeLong(mLoadedCount);
1593 out.writeLong(mUnpluggedCount);
1594 }
1595
1596 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001597 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Sudheer Shankac57729a2018-02-09 15:44:42 -08001598 mUnpluggedCount = mCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001599 }
1600
1601 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001602 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001603 }
1604
1605 public long getCountLocked(int which) {
Sudheer Shankac57729a2018-02-09 15:44:42 -08001606 long val = mCount;
Dianne Hackborn4590e522014-03-24 13:36:46 -07001607 if (which == STATS_SINCE_UNPLUGGED) {
1608 val -= mUnpluggedCount;
1609 } else if (which != STATS_SINCE_CHARGED) {
1610 val -= mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001611 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001612 return val;
1613 }
1614
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001615 @Override
1616 public void logState(Printer pw, String prefix) {
1617 pw.println(prefix + "mCount=" + mCount
Mike Ma561a8d92018-03-20 18:24:05 -07001618 + " mCurrentCount=" + mCurrentCount
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001619 + " mLoadedCount=" + mLoadedCount
Sudheer Shankac57729a2018-02-09 15:44:42 -08001620 + " mUnpluggedCount=" + mUnpluggedCount);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001621 }
1622
Mike Ma561a8d92018-03-20 18:24:05 -07001623 public void addCountLocked(long count) {
1624 update(mCurrentCount + count, mTimeBase.isRunning());
Sudheer Shankac57729a2018-02-09 15:44:42 -08001625 }
1626
Mike Ma561a8d92018-03-20 18:24:05 -07001627 public void addCountLocked(long count, boolean isRunning) {
1628 update(mCurrentCount + count, isRunning);
1629 }
1630
1631 public void update(long count) {
1632 update(count, mTimeBase.isRunning());
1633 }
1634
1635 public void update(long count, boolean isRunning) {
1636 if (count < mCurrentCount) {
1637 mCurrentCount = 0;
Bookatz8c6f3c52017-05-24 12:00:17 -07001638 }
Mike Ma561a8d92018-03-20 18:24:05 -07001639 if (isRunning) {
1640 mCount += count - mCurrentCount;
1641 }
1642 mCurrentCount = count;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001643 }
1644
1645 /**
1646 * Clear state of this counter.
1647 */
Mike Ma561a8d92018-03-20 18:24:05 -07001648 public void reset(boolean detachIfReset) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001649 mCount = 0;
Sudheer Shankac57729a2018-02-09 15:44:42 -08001650 mLoadedCount = mUnpluggedCount = 0;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001651 if (detachIfReset) {
1652 detach();
1653 }
1654 }
1655
Mike Ma561a8d92018-03-20 18:24:05 -07001656 public void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001657 mTimeBase.remove(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001658 }
1659
Mike Ma561a8d92018-03-20 18:24:05 -07001660 public void writeSummaryFromParcelLocked(Parcel out) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001661 out.writeLong(mCount);
1662 }
1663
Mike Ma561a8d92018-03-20 18:24:05 -07001664 public void readSummaryFromParcelLocked(Parcel in) {
1665 mCount = mUnpluggedCount= mLoadedCount = in.readLong();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001666 }
1667 }
1668
Dianne Hackborn617f8772009-03-31 15:04:46 -07001669 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 * State for keeping track of timing information.
1671 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001672 public static abstract class Timer extends BatteryStats.Timer implements TimeBaseObs {
Joe Onoratoabded112016-02-08 16:49:39 -08001673 protected final Clocks mClocks;
1674 protected final int mType;
1675 protected final TimeBase mTimeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001676
Joe Onoratoabded112016-02-08 16:49:39 -08001677 protected int mCount;
1678 protected int mLoadedCount;
1679 protected int mLastCount;
1680 protected int mUnpluggedCount;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001681
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 // Times are in microseconds for better accuracy when dividing by the
1683 // lock count, and are in "battery realtime" units.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001684
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 /**
1686 * The total time we have accumulated since the start of the original
1687 * boot, to the last time something interesting happened in the
1688 * current run.
1689 */
Joe Onoratoabded112016-02-08 16:49:39 -08001690 protected long mTotalTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 /**
1693 * The total time we loaded for the previous runs. Subtract this from
1694 * mTotalTime to find the time for the current run of the system.
1695 */
Joe Onoratoabded112016-02-08 16:49:39 -08001696 protected long mLoadedTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 /**
1699 * The run time of the last run of the system, as loaded from the
1700 * saved data.
1701 */
Joe Onoratoabded112016-02-08 16:49:39 -08001702 protected long mLastTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 /**
1705 * The value of mTotalTime when unplug() was last called. Subtract
1706 * this from mTotalTime to find the time since the last unplug from
1707 * power.
1708 */
Joe Onoratoabded112016-02-08 16:49:39 -08001709 protected long mUnpluggedTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001710
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001711 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07001712 * The total time this timer has been running until the latest mark has been set.
1713 * Subtract this from mTotalTime to get the time spent running since the mark was set.
1714 */
Joe Onoratoabded112016-02-08 16:49:39 -08001715 protected long mTimeBeforeMark;
Adam Lesinskie08af192015-03-25 16:42:59 -07001716
1717 /**
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001718 * Constructs from a parcel.
1719 * @param type
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001720 * @param timeBase
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001721 * @param in
1722 */
Joe Onoratoabded112016-02-08 16:49:39 -08001723 public Timer(Clocks clocks, int type, TimeBase timeBase, Parcel in) {
1724 mClocks = clocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 mType = type;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001726 mTimeBase = timeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001727
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001728 mCount = in.readInt();
1729 mLoadedCount = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001730 mLastCount = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001731 mUnpluggedCount = in.readInt();
1732 mTotalTime = in.readLong();
1733 mLoadedTime = in.readLong();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001734 mLastTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 mUnpluggedTime = in.readLong();
Adam Lesinskie08af192015-03-25 16:42:59 -07001736 mTimeBeforeMark = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001737 timeBase.add(this);
Dianne Hackborn29325132014-05-21 15:01:03 -07001738 if (DEBUG) Log.i(TAG, "**** READ TIMER #" + mType + ": mTotalTime=" + mTotalTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739 }
1740
Joe Onoratoabded112016-02-08 16:49:39 -08001741 public Timer(Clocks clocks, int type, TimeBase timeBase) {
1742 mClocks = clocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 mType = type;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001744 mTimeBase = timeBase;
1745 timeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001746 }
Evan Millarc64edde2009-04-18 12:26:32 -07001747
1748 protected abstract long computeRunTimeLocked(long curBatteryRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001749
Evan Millarc64edde2009-04-18 12:26:32 -07001750 protected abstract int computeCurrentCountLocked();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001751
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001752 /**
1753 * Clear state of this timer. Returns true if the timer is inactive
1754 * so can be completely dropped.
1755 */
Joe Onoratoabded112016-02-08 16:49:39 -08001756 public boolean reset(boolean detachIfReset) {
Adam Lesinskie08af192015-03-25 16:42:59 -07001757 mTotalTime = mLoadedTime = mLastTime = mTimeBeforeMark = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001758 mCount = mLoadedCount = mLastCount = 0;
1759 if (detachIfReset) {
1760 detach();
1761 }
1762 return true;
1763 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001764
Joe Onoratoabded112016-02-08 16:49:39 -08001765 public void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001766 mTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001767 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001768
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001769 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
Dianne Hackborn29325132014-05-21 15:01:03 -07001770 if (DEBUG) Log.i(TAG, "**** WRITING TIMER #" + mType + ": mTotalTime="
1771 + computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)));
Adam Lesinski98f0d462016-04-19 16:46:20 -07001772 out.writeInt(computeCurrentCountLocked());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001773 out.writeInt(mLoadedCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 out.writeInt(mUnpluggedCount);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001775 out.writeLong(computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776 out.writeLong(mLoadedTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 out.writeLong(mUnpluggedTime);
Adam Lesinskie08af192015-03-25 16:42:59 -07001778 out.writeLong(mTimeBeforeMark);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001779 }
1780
Adam Lesinskie08af192015-03-25 16:42:59 -07001781 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001782 public void onTimeStarted(long elapsedRealtime, long timeBaseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783 if (DEBUG && mType < 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001784 Log.v(TAG, "unplug #" + mType + ": realtime=" + baseRealtime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 + " old mUnpluggedTime=" + mUnpluggedTime
1786 + " old mUnpluggedCount=" + mUnpluggedCount);
1787 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001788 mUnpluggedTime = computeRunTimeLocked(baseRealtime);
Adam Lesinski98f0d462016-04-19 16:46:20 -07001789 mUnpluggedCount = computeCurrentCountLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 if (DEBUG && mType < 0) {
1791 Log.v(TAG, "unplug #" + mType
1792 + ": new mUnpluggedTime=" + mUnpluggedTime
1793 + " new mUnpluggedCount=" + mUnpluggedCount);
1794 }
1795 }
1796
Adam Lesinskie08af192015-03-25 16:42:59 -07001797 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001798 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Evan Millarc64edde2009-04-18 12:26:32 -07001799 if (DEBUG && mType < 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001800 Log.v(TAG, "plug #" + mType + ": realtime=" + baseRealtime
Evan Millarc64edde2009-04-18 12:26:32 -07001801 + " old mTotalTime=" + mTotalTime);
1802 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001803 mTotalTime = computeRunTimeLocked(baseRealtime);
Evan Millarc64edde2009-04-18 12:26:32 -07001804 mCount = computeCurrentCountLocked();
1805 if (DEBUG && mType < 0) {
1806 Log.v(TAG, "plug #" + mType
1807 + ": new mTotalTime=" + mTotalTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001808 }
1809 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 /**
1812 * Writes a possibly null Timer to a Parcel.
1813 *
1814 * @param out the Parcel to be written to.
1815 * @param timer a Timer, or null.
1816 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001817 public static void writeTimerToParcel(Parcel out, Timer timer, long elapsedRealtimeUs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001818 if (timer == null) {
1819 out.writeInt(0); // indicates null
1820 return;
1821 }
1822 out.writeInt(1); // indicates non-null
1823
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001824 timer.writeToParcel(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825 }
1826
1827 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001828 public long getTotalTimeLocked(long elapsedRealtimeUs, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001829 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1830 if (which == STATS_SINCE_UNPLUGGED) {
1831 val -= mUnpluggedTime;
1832 } else if (which != STATS_SINCE_CHARGED) {
1833 val -= mLoadedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 }
1835
1836 return val;
1837 }
1838
1839 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001840 public int getCountLocked(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001841 int val = computeCurrentCountLocked();
1842 if (which == STATS_SINCE_UNPLUGGED) {
1843 val -= mUnpluggedCount;
1844 } else if (which != STATS_SINCE_CHARGED) {
1845 val -= mLoadedCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 }
1847
1848 return val;
1849 }
1850
Adam Lesinskie08af192015-03-25 16:42:59 -07001851 @Override
1852 public long getTimeSinceMarkLocked(long elapsedRealtimeUs) {
1853 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1854 return val - mTimeBeforeMark;
1855 }
1856
1857 @Override
Dianne Hackborn627bba72009-03-24 22:32:56 -07001858 public void logState(Printer pw, String prefix) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07001859 pw.println(prefix + "mCount=" + mCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 + " mLoadedCount=" + mLoadedCount + " mLastCount=" + mLastCount
1861 + " mUnpluggedCount=" + mUnpluggedCount);
Dianne Hackborn627bba72009-03-24 22:32:56 -07001862 pw.println(prefix + "mTotalTime=" + mTotalTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001863 + " mLoadedTime=" + mLoadedTime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07001864 pw.println(prefix + "mLastTime=" + mLastTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 + " mUnpluggedTime=" + mUnpluggedTime);
Evan Millarc64edde2009-04-18 12:26:32 -07001866 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001867
1868
Joe Onoratoabded112016-02-08 16:49:39 -08001869 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001870 long runTime = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1871 out.writeLong(runTime);
Adam Lesinski98f0d462016-04-19 16:46:20 -07001872 out.writeInt(computeCurrentCountLocked());
Evan Millarc64edde2009-04-18 12:26:32 -07001873 }
1874
Joe Onoratoabded112016-02-08 16:49:39 -08001875 public void readSummaryFromParcelLocked(Parcel in) {
Evan Millarc64edde2009-04-18 12:26:32 -07001876 // Multiply by 1000 for backwards compatibility
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001877 mTotalTime = mLoadedTime = in.readLong();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001878 mLastTime = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001879 mUnpluggedTime = mTotalTime;
1880 mCount = mLoadedCount = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001881 mLastCount = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001882 mUnpluggedCount = mCount;
Adam Lesinskie08af192015-03-25 16:42:59 -07001883
1884 // When reading the summary, we set the mark to be the latest information.
1885 mTimeBeforeMark = mTotalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001886 }
1887 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001888
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001889 /**
1890 * A counter meant to accept monotonically increasing values to its {@link #update(long, int)}
1891 * method. The state of the timer according to its {@link TimeBase} will determine how much
1892 * of the value is recorded.
1893 *
1894 * If the value being recorded resets, {@link #endSample()} can be called in order to
1895 * account for the change. If the value passed in to {@link #update(long, int)} decreased
1896 * between calls, the {@link #endSample()} is automatically called and the new value is
1897 * expected to increase monotonically from that point on.
1898 */
Joe Onoratoabded112016-02-08 16:49:39 -08001899 public static class SamplingTimer extends Timer {
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001900
Evan Millarc64edde2009-04-18 12:26:32 -07001901 /**
1902 * The most recent reported count from /proc/wakelocks.
1903 */
1904 int mCurrentReportedCount;
1905
1906 /**
1907 * The reported count from /proc/wakelocks when unplug() was last
1908 * called.
1909 */
1910 int mUnpluggedReportedCount;
1911
1912 /**
1913 * The most recent reported total_time from /proc/wakelocks.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001914 */
Evan Millarc64edde2009-04-18 12:26:32 -07001915 long mCurrentReportedTotalTime;
1916
1917
1918 /**
1919 * The reported total_time from /proc/wakelocks when unplug() was last
1920 * called.
1921 */
1922 long mUnpluggedReportedTotalTime;
1923
1924 /**
1925 * Whether we are currently in a discharge cycle.
1926 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001927 boolean mTimeBaseRunning;
Evan Millarc64edde2009-04-18 12:26:32 -07001928
1929 /**
1930 * Whether we are currently recording reported values.
1931 */
1932 boolean mTrackingReportedValues;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001933
Evan Millarc64edde2009-04-18 12:26:32 -07001934 /*
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001935 * A sequence counter, incremented once for each update of the stats.
Evan Millarc64edde2009-04-18 12:26:32 -07001936 */
1937 int mUpdateVersion;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001938
Adam Lesinski98f0d462016-04-19 16:46:20 -07001939 @VisibleForTesting
1940 public SamplingTimer(Clocks clocks, TimeBase timeBase, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08001941 super(clocks, 0, timeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -07001942 mCurrentReportedCount = in.readInt();
1943 mUnpluggedReportedCount = in.readInt();
1944 mCurrentReportedTotalTime = in.readLong();
1945 mUnpluggedReportedTotalTime = in.readLong();
1946 mTrackingReportedValues = in.readInt() == 1;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001947 mTimeBaseRunning = timeBase.isRunning();
Evan Millarc64edde2009-04-18 12:26:32 -07001948 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001949
Adam Lesinski98f0d462016-04-19 16:46:20 -07001950 @VisibleForTesting
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001951 public SamplingTimer(Clocks clocks, TimeBase timeBase) {
Joe Onoratoabded112016-02-08 16:49:39 -08001952 super(clocks, 0, timeBase);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001953 mTrackingReportedValues = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001954 mTimeBaseRunning = timeBase.isRunning();
Evan Millarc64edde2009-04-18 12:26:32 -07001955 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001956
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001957 /**
1958 * Ends the current sample, allowing subsequent values to {@link #update(long, int)} to
1959 * be less than the values used for a previous invocation.
1960 */
1961 public void endSample() {
1962 mTotalTime = computeRunTimeLocked(0 /* unused by us */);
1963 mCount = computeCurrentCountLocked();
1964 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime = 0;
1965 mUnpluggedReportedCount = mCurrentReportedCount = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001966 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001967
Evan Millarc64edde2009-04-18 12:26:32 -07001968 public void setUpdateVersion(int version) {
1969 mUpdateVersion = version;
1970 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001971
Evan Millarc64edde2009-04-18 12:26:32 -07001972 public int getUpdateVersion() {
1973 return mUpdateVersion;
1974 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001975
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001976 /**
1977 * Updates the current recorded values. These are meant to be monotonically increasing
1978 * and cumulative. If you are dealing with deltas, use {@link #add(long, int)}.
1979 *
1980 * If the values being recorded have been reset, the monotonically increasing requirement
1981 * will be broken. In this case, {@link #endSample()} is automatically called and
1982 * the total value of totalTime and count are recorded, starting a new monotonically
1983 * increasing sample.
1984 *
1985 * @param totalTime total time of sample in microseconds.
1986 * @param count total number of times the event being sampled occurred.
1987 */
1988 public void update(long totalTime, int count) {
1989 if (mTimeBaseRunning && !mTrackingReportedValues) {
Evan Millarc64edde2009-04-18 12:26:32 -07001990 // Updating the reported value for the first time.
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001991 mUnpluggedReportedTotalTime = totalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001992 mUnpluggedReportedCount = count;
Evan Millarc64edde2009-04-18 12:26:32 -07001993 }
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001994
1995 mTrackingReportedValues = true;
1996
1997 if (totalTime < mCurrentReportedTotalTime || count < mCurrentReportedCount) {
1998 endSample();
1999 }
2000
2001 mCurrentReportedTotalTime = totalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07002002 mCurrentReportedCount = count;
2003 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002004
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002005 /**
2006 * Adds deltaTime and deltaCount to the current sample.
2007 *
2008 * @param deltaTime additional time recorded since the last sampled event, in microseconds.
2009 * @param deltaCount additional number of times the event being sampled occurred.
2010 */
2011 public void add(long deltaTime, int deltaCount) {
2012 update(mCurrentReportedTotalTime + deltaTime, mCurrentReportedCount + deltaCount);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002013 }
2014
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002015 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002016 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
2017 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime);
Evan Millarc64edde2009-04-18 12:26:32 -07002018 if (mTrackingReportedValues) {
2019 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime;
2020 mUnpluggedReportedCount = mCurrentReportedCount;
2021 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002022 mTimeBaseRunning = true;
Evan Millarc64edde2009-04-18 12:26:32 -07002023 }
2024
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002025 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002026 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
2027 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
2028 mTimeBaseRunning = false;
Evan Millarc64edde2009-04-18 12:26:32 -07002029 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002030
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002031 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07002032 public void logState(Printer pw, String prefix) {
2033 super.logState(pw, prefix);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002034 pw.println(prefix + "mCurrentReportedCount=" + mCurrentReportedCount
Evan Millarc64edde2009-04-18 12:26:32 -07002035 + " mUnpluggedReportedCount=" + mUnpluggedReportedCount
2036 + " mCurrentReportedTotalTime=" + mCurrentReportedTotalTime
2037 + " mUnpluggedReportedTotalTime=" + mUnpluggedReportedTotalTime);
2038 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002039
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002040 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07002041 protected long computeRunTimeLocked(long curBatteryRealtime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002042 return mTotalTime + (mTimeBaseRunning && mTrackingReportedValues
Evan Millarc64edde2009-04-18 12:26:32 -07002043 ? mCurrentReportedTotalTime - mUnpluggedReportedTotalTime : 0);
2044 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002045
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002046 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07002047 protected int computeCurrentCountLocked() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002048 return mCount + (mTimeBaseRunning && mTrackingReportedValues
Evan Millarc64edde2009-04-18 12:26:32 -07002049 ? mCurrentReportedCount - mUnpluggedReportedCount : 0);
2050 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002051
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002052 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002053 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2054 super.writeToParcel(out, elapsedRealtimeUs);
Evan Millarc64edde2009-04-18 12:26:32 -07002055 out.writeInt(mCurrentReportedCount);
2056 out.writeInt(mUnpluggedReportedCount);
2057 out.writeLong(mCurrentReportedTotalTime);
2058 out.writeLong(mUnpluggedReportedTotalTime);
2059 out.writeInt(mTrackingReportedValues ? 1 : 0);
2060 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002061
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002062 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002063 public boolean reset(boolean detachIfReset) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002064 super.reset(detachIfReset);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002065 mTrackingReportedValues = false;
2066 mUnpluggedReportedTotalTime = 0;
2067 mUnpluggedReportedCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002068 return true;
2069 }
Evan Millarc64edde2009-04-18 12:26:32 -07002070 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002071
Evan Millarc64edde2009-04-18 12:26:32 -07002072 /**
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002073 * A timer that increments in batches. It does not run for durations, but just jumps
2074 * for a pre-determined amount.
2075 */
Joe Onoratoabded112016-02-08 16:49:39 -08002076 public static class BatchTimer extends Timer {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002077 final Uid mUid;
2078
2079 /**
2080 * The last time at which we updated the timer. This is in elapsed realtime microseconds.
2081 */
2082 long mLastAddedTime;
2083
2084 /**
2085 * The last duration that we added to the timer. This is in microseconds.
2086 */
2087 long mLastAddedDuration;
2088
2089 /**
2090 * Whether we are currently in a discharge cycle.
2091 */
2092 boolean mInDischarge;
2093
Joe Onoratoabded112016-02-08 16:49:39 -08002094 BatchTimer(Clocks clocks, Uid uid, int type, TimeBase timeBase, Parcel in) {
2095 super(clocks, type, timeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002096 mUid = uid;
2097 mLastAddedTime = in.readLong();
2098 mLastAddedDuration = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002099 mInDischarge = timeBase.isRunning();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002100 }
2101
Joe Onoratoabded112016-02-08 16:49:39 -08002102 BatchTimer(Clocks clocks, Uid uid, int type, TimeBase timeBase) {
2103 super(clocks, type, timeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002104 mUid = uid;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002105 mInDischarge = timeBase.isRunning();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002106 }
2107
2108 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002109 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2110 super.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002111 out.writeLong(mLastAddedTime);
2112 out.writeLong(mLastAddedDuration);
2113 }
2114
2115 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002116 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Joe Onoratoabded112016-02-08 16:49:39 -08002117 recomputeLastDuration(mClocks.elapsedRealtime() * 1000, false);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002118 mInDischarge = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002119 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002120 }
2121
2122 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002123 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002124 recomputeLastDuration(elapsedRealtime, false);
2125 mInDischarge = true;
2126 // If we are still within the last added duration, then re-added whatever remains.
2127 if (mLastAddedTime == elapsedRealtime) {
2128 mTotalTime += mLastAddedDuration;
2129 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002130 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002131 }
2132
2133 @Override
2134 public void logState(Printer pw, String prefix) {
2135 super.logState(pw, prefix);
2136 pw.println(prefix + "mLastAddedTime=" + mLastAddedTime
2137 + " mLastAddedDuration=" + mLastAddedDuration);
2138 }
2139
2140 private long computeOverage(long curTime) {
2141 if (mLastAddedTime > 0) {
2142 return mLastTime + mLastAddedDuration - curTime;
2143 }
2144 return 0;
2145 }
2146
2147 private void recomputeLastDuration(long curTime, boolean abort) {
2148 final long overage = computeOverage(curTime);
2149 if (overage > 0) {
2150 // Aborting before the duration ran out -- roll back the remaining
2151 // duration. Only do this if currently discharging; otherwise we didn't
2152 // actually add the time.
2153 if (mInDischarge) {
2154 mTotalTime -= overage;
2155 }
2156 if (abort) {
2157 mLastAddedTime = 0;
2158 } else {
2159 mLastAddedTime = curTime;
2160 mLastAddedDuration -= overage;
2161 }
2162 }
2163 }
2164
2165 public void addDuration(BatteryStatsImpl stats, long durationMillis) {
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 mLastAddedTime = now;
2169 mLastAddedDuration = durationMillis * 1000;
2170 if (mInDischarge) {
2171 mTotalTime += mLastAddedDuration;
2172 mCount++;
2173 }
2174 }
2175
2176 public void abortLastDuration(BatteryStatsImpl stats) {
Joe Onoratoabded112016-02-08 16:49:39 -08002177 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002178 recomputeLastDuration(now, true);
2179 }
2180
2181 @Override
2182 protected int computeCurrentCountLocked() {
2183 return mCount;
2184 }
2185
2186 @Override
2187 protected long computeRunTimeLocked(long curBatteryRealtime) {
Joe Onoratoabded112016-02-08 16:49:39 -08002188 final long overage = computeOverage(mClocks.elapsedRealtime() * 1000);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002189 if (overage > 0) {
2190 return mTotalTime = overage;
2191 }
2192 return mTotalTime;
2193 }
2194
2195 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002196 public boolean reset(boolean detachIfReset) {
2197 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002198 recomputeLastDuration(now, true);
2199 boolean stillActive = mLastAddedTime == now;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002200 super.reset(!stillActive && detachIfReset);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002201 return !stillActive;
2202 }
2203 }
2204
Joe Onorato92fd23f2016-07-25 11:18:42 -07002205
2206 /**
2207 * A StopwatchTimer that also tracks the total and max individual
2208 * time spent active according to the given timebase. Whereas
2209 * StopwatchTimer apportions the time amongst all in the pool,
2210 * the total and max durations are not apportioned.
2211 */
2212 public static class DurationTimer extends StopwatchTimer {
2213 /**
2214 * The time (in ms) that the timer was last acquired or the time base
2215 * last (re-)started. Increasing the nesting depth does not reset this time.
2216 *
2217 * -1 if the timer is currently not running or the time base is not running.
2218 *
2219 * If written to a parcel, the start time is reset, as is mNesting in the base class
2220 * StopwatchTimer.
2221 */
2222 long mStartTimeMs = -1;
2223
2224 /**
Bookatz867c0d72017-03-07 18:23:42 -08002225 * The longest time period (in ms) that the timer has been active. Not pooled.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002226 */
2227 long mMaxDurationMs;
2228
2229 /**
Bookatz867c0d72017-03-07 18:23:42 -08002230 * The time (in ms) that that the timer has been active since most recent
2231 * stopRunningLocked() or reset(). Not pooled.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002232 */
2233 long mCurrentDurationMs;
2234
Bookatz867c0d72017-03-07 18:23:42 -08002235 /**
2236 * The total time (in ms) that that the timer has been active since most recent reset()
2237 * prior to the current startRunningLocked. This is the sum of all past currentDurations
2238 * (but not including the present currentDuration) since reset. Not pooled.
2239 */
2240 long mTotalDurationMs;
2241
Joe Onorato92fd23f2016-07-25 11:18:42 -07002242 public DurationTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2243 TimeBase timeBase, Parcel in) {
2244 super(clocks, uid, type, timerPool, timeBase, in);
2245 mMaxDurationMs = in.readLong();
Bookatz867c0d72017-03-07 18:23:42 -08002246 mTotalDurationMs = in.readLong();
jackqdyulei610a0a02017-08-09 14:02:01 -07002247 mCurrentDurationMs = in.readLong();
Joe Onorato92fd23f2016-07-25 11:18:42 -07002248 }
2249
2250 public DurationTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2251 TimeBase timeBase) {
2252 super(clocks, uid, type, timerPool, timeBase);
2253 }
2254
2255 @Override
2256 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2257 super.writeToParcel(out, elapsedRealtimeUs);
Kweku Adams47db5a82016-12-09 19:04:50 -08002258 out.writeLong(getMaxDurationMsLocked(elapsedRealtimeUs / 1000));
jackqdyulei610a0a02017-08-09 14:02:01 -07002259 out.writeLong(mTotalDurationMs);
2260 out.writeLong(getCurrentDurationMsLocked(elapsedRealtimeUs / 1000));
Joe Onorato92fd23f2016-07-25 11:18:42 -07002261 }
2262
2263 /**
2264 * Write the summary to the parcel.
2265 *
2266 * Since the time base is probably meaningless after we come back, reading
2267 * from this will have the effect of stopping the timer. So here all we write
Bookatz867c0d72017-03-07 18:23:42 -08002268 * is the max and total durations.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002269 */
2270 @Override
2271 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
2272 super.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
Kweku Adams47db5a82016-12-09 19:04:50 -08002273 out.writeLong(getMaxDurationMsLocked(elapsedRealtimeUs / 1000));
Bookatz867c0d72017-03-07 18:23:42 -08002274 out.writeLong(getTotalDurationMsLocked(elapsedRealtimeUs / 1000));
Joe Onorato92fd23f2016-07-25 11:18:42 -07002275 }
2276
2277 /**
2278 * Read the summary parcel.
2279 *
2280 * Has the side effect of stopping the timer.
2281 */
2282 @Override
2283 public void readSummaryFromParcelLocked(Parcel in) {
2284 super.readSummaryFromParcelLocked(in);
2285 mMaxDurationMs = in.readLong();
Bookatz867c0d72017-03-07 18:23:42 -08002286 mTotalDurationMs = in.readLong();
Joe Onorato92fd23f2016-07-25 11:18:42 -07002287 mStartTimeMs = -1;
2288 mCurrentDurationMs = 0;
2289 }
2290
2291 /**
2292 * The TimeBase time started (again).
2293 *
2294 * If the timer is also running, store the start time.
2295 */
2296 public void onTimeStarted(long elapsedRealtimeUs, long baseUptime, long baseRealtime) {
2297 super.onTimeStarted(elapsedRealtimeUs, baseUptime, baseRealtime);
2298 if (mNesting > 0) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002299 mStartTimeMs = baseRealtime / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002300 }
2301 }
2302
2303 /**
2304 * The TimeBase stopped running.
2305 *
2306 * If the timer is running, add the duration into mCurrentDurationMs.
2307 */
2308 @Override
Kweku Adams47db5a82016-12-09 19:04:50 -08002309 public void onTimeStopped(long elapsedRealtimeUs, long baseUptime, long baseRealtimeUs) {
2310 super.onTimeStopped(elapsedRealtimeUs, baseUptime, baseRealtimeUs);
Joe Onorato92fd23f2016-07-25 11:18:42 -07002311 if (mNesting > 0) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002312 // baseRealtimeUs has already been converted to the timebase's realtime.
2313 mCurrentDurationMs += (baseRealtimeUs / 1000) - mStartTimeMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002314 }
2315 mStartTimeMs = -1;
2316 }
2317
2318 @Override
2319 public void logState(Printer pw, String prefix) {
2320 super.logState(pw, prefix);
2321 }
2322
2323 @Override
2324 public void startRunningLocked(long elapsedRealtimeMs) {
2325 super.startRunningLocked(elapsedRealtimeMs);
2326 if (mNesting == 1 && mTimeBase.isRunning()) {
2327 // Just started
Kweku Adams47db5a82016-12-09 19:04:50 -08002328 mStartTimeMs = mTimeBase.getRealtime(elapsedRealtimeMs * 1000) / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002329 }
2330 }
2331
2332 /**
2333 * Decrements the mNesting ref-count on this timer.
2334 *
2335 * If it actually stopped (mNesting went to 0), then possibly update
2336 * mMaxDuration if the current duration was the longest ever.
2337 */
2338 @Override
2339 public void stopRunningLocked(long elapsedRealtimeMs) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002340 if (mNesting == 1) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07002341 final long durationMs = getCurrentDurationMsLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002342 mTotalDurationMs += durationMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002343 if (durationMs > mMaxDurationMs) {
2344 mMaxDurationMs = durationMs;
2345 }
2346 mStartTimeMs = -1;
2347 mCurrentDurationMs = 0;
2348 }
Kweku Adams47db5a82016-12-09 19:04:50 -08002349 // super method decrements mNesting, which getCurrentDurationMsLocked relies on,
2350 // so call super.stopRunningLocked after calling getCurrentDurationMsLocked.
2351 super.stopRunningLocked(elapsedRealtimeMs);
Joe Onorato92fd23f2016-07-25 11:18:42 -07002352 }
2353
2354 @Override
2355 public boolean reset(boolean detachIfReset) {
2356 boolean result = super.reset(detachIfReset);
2357 mMaxDurationMs = 0;
Bookatz867c0d72017-03-07 18:23:42 -08002358 mTotalDurationMs = 0;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002359 mCurrentDurationMs = 0;
2360 if (mNesting > 0) {
2361 mStartTimeMs = mTimeBase.getRealtime(mClocks.elapsedRealtime()*1000) / 1000;
2362 } else {
2363 mStartTimeMs = -1;
2364 }
2365 return result;
2366 }
2367
2368 /**
2369 * Returns the max duration that this timer has ever seen.
2370 *
2371 * Note that this time is NOT split between the timers in the timer group that
2372 * this timer is attached to. It is the TOTAL time.
2373 */
2374 @Override
2375 public long getMaxDurationMsLocked(long elapsedRealtimeMs) {
2376 if (mNesting > 0) {
2377 final long durationMs = getCurrentDurationMsLocked(elapsedRealtimeMs);
2378 if (durationMs > mMaxDurationMs) {
2379 return durationMs;
2380 }
2381 }
2382 return mMaxDurationMs;
2383 }
2384
2385 /**
2386 * Returns the time since the timer was started.
Bookatz867c0d72017-03-07 18:23:42 -08002387 * Returns 0 if the timer is not currently running.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002388 *
2389 * Note that this time is NOT split between the timers in the timer group that
2390 * this timer is attached to. It is the TOTAL time.
jackqdyulei610a0a02017-08-09 14:02:01 -07002391 *
2392 * Note that if running timer is parceled and unparceled, this method will return
2393 * current duration value at the time of parceling even though timer may not be
2394 * currently running.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002395 */
2396 @Override
2397 public long getCurrentDurationMsLocked(long elapsedRealtimeMs) {
2398 long durationMs = mCurrentDurationMs;
Kweku Adams47db5a82016-12-09 19:04:50 -08002399 if (mNesting > 0 && mTimeBase.isRunning()) {
2400 durationMs += (mTimeBase.getRealtime(elapsedRealtimeMs*1000)/1000)
2401 - mStartTimeMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002402 }
2403 return durationMs;
2404 }
Bookatz867c0d72017-03-07 18:23:42 -08002405
2406 /**
2407 * Returns the total cumulative duration that this timer has been on since reset().
2408 * If mTimerPool == null, this should be the same
2409 * as getTotalTimeLocked(elapsedRealtimeMs*1000, STATS_SINCE_CHARGED)/1000.
2410 *
2411 * Note that this time is NOT split between the timers in the timer group that
2412 * this timer is attached to. It is the TOTAL time. For this reason, if mTimerPool != null,
2413 * the result will not be equivalent to getTotalTimeLocked.
2414 */
2415 @Override
2416 public long getTotalDurationMsLocked(long elapsedRealtimeMs) {
2417 return mTotalDurationMs + getCurrentDurationMsLocked(elapsedRealtimeMs);
2418 }
Joe Onorato92fd23f2016-07-25 11:18:42 -07002419 }
2420
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002421 /**
Evan Millarc64edde2009-04-18 12:26:32 -07002422 * State for keeping track of timing information.
2423 */
Joe Onoratoabded112016-02-08 16:49:39 -08002424 public static class StopwatchTimer extends Timer {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002425 final Uid mUid;
Evan Millarc64edde2009-04-18 12:26:32 -07002426 final ArrayList<StopwatchTimer> mTimerPool;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002427
Evan Millarc64edde2009-04-18 12:26:32 -07002428 int mNesting;
2429
Evan Millarc64edde2009-04-18 12:26:32 -07002430 /**
2431 * The last time at which we updated the timer. If mNesting is > 0,
2432 * subtract this from the current battery time to find the amount of
2433 * time we have been running since we last computed an update.
2434 */
2435 long mUpdateTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002436
Evan Millarc64edde2009-04-18 12:26:32 -07002437 /**
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002438 * The total time at which the timer was acquired, to determine if it
Bookatzceebafe2017-04-06 11:59:13 -07002439 * was actually held for an interesting duration. If time base was not running when timer
2440 * was acquired, will be -1.
Evan Millarc64edde2009-04-18 12:26:32 -07002441 */
Bookatzceebafe2017-04-06 11:59:13 -07002442 long mAcquireTime = -1;
Evan Millarc64edde2009-04-18 12:26:32 -07002443
Amith Yamasanif37447b2009-10-08 18:28:01 -07002444 long mTimeout;
2445
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002446 /**
2447 * For partial wake locks, keep track of whether we are in the list
2448 * to consume CPU cycles.
2449 */
Sudheer Shanka38383232017-07-25 09:55:03 -07002450 @VisibleForTesting
2451 public boolean mInList;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002452
Joe Onoratoabded112016-02-08 16:49:39 -08002453 public StopwatchTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002454 TimeBase timeBase, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08002455 super(clocks, type, timeBase, in);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002456 mUid = uid;
Evan Millarc64edde2009-04-18 12:26:32 -07002457 mTimerPool = timerPool;
2458 mUpdateTime = in.readLong();
2459 }
2460
Joe Onoratoabded112016-02-08 16:49:39 -08002461 public StopwatchTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002462 TimeBase timeBase) {
Joe Onoratoabded112016-02-08 16:49:39 -08002463 super(clocks, type, timeBase);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002464 mUid = uid;
Evan Millarc64edde2009-04-18 12:26:32 -07002465 mTimerPool = timerPool;
2466 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002467
Joe Onoratoabded112016-02-08 16:49:39 -08002468 public void setTimeout(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07002469 mTimeout = timeout;
2470 }
2471
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002472 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2473 super.writeToParcel(out, elapsedRealtimeUs);
Evan Millarc64edde2009-04-18 12:26:32 -07002474 out.writeLong(mUpdateTime);
2475 }
2476
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002477 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Evan Millarc64edde2009-04-18 12:26:32 -07002478 if (mNesting > 0) {
2479 if (DEBUG && mType < 0) {
2480 Log.v(TAG, "old mUpdateTime=" + mUpdateTime);
2481 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002482 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
2483 mUpdateTime = baseRealtime;
Evan Millarc64edde2009-04-18 12:26:32 -07002484 if (DEBUG && mType < 0) {
2485 Log.v(TAG, "new mUpdateTime=" + mUpdateTime);
2486 }
2487 }
2488 }
2489
2490 public void logState(Printer pw, String prefix) {
2491 super.logState(pw, prefix);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07002492 pw.println(prefix + "mNesting=" + mNesting + " mUpdateTime=" + mUpdateTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002493 + " mAcquireTime=" + mAcquireTime);
2494 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002495
Joe Onoratoabded112016-02-08 16:49:39 -08002496 public void startRunningLocked(long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002497 if (mNesting++ == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002498 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002499 mUpdateTime = batteryRealtime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002500 if (mTimerPool != null) {
2501 // Accumulate time to all currently active timers before adding
2502 // this new one to the pool.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002503 refreshTimersLocked(batteryRealtime, mTimerPool, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002504 // Add this timer to the active pool
2505 mTimerPool.add(this);
2506 }
Bookatzceebafe2017-04-06 11:59:13 -07002507 if (mTimeBase.isRunning()) {
2508 // Increment the count
2509 mCount++;
2510 mAcquireTime = mTotalTime;
2511 } else {
2512 mAcquireTime = -1;
2513 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514 if (DEBUG && mType < 0) {
2515 Log.v(TAG, "start #" + mType + ": mUpdateTime=" + mUpdateTime
2516 + " mTotalTime=" + mTotalTime + " mCount=" + mCount
2517 + " mAcquireTime=" + mAcquireTime);
2518 }
2519 }
2520 }
2521
Joe Onoratoabded112016-02-08 16:49:39 -08002522 public boolean isRunningLocked() {
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002523 return mNesting > 0;
2524 }
2525
Joe Onoratoabded112016-02-08 16:49:39 -08002526 public void stopRunningLocked(long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527 // Ignore attempt to stop a timer that isn't running
2528 if (mNesting == 0) {
2529 return;
2530 }
2531 if (--mNesting == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002532 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002533 if (mTimerPool != null) {
2534 // Accumulate time to all active counters, scaled by the total
2535 // active in the pool, before taking this one out of the pool.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002536 refreshTimersLocked(batteryRealtime, mTimerPool, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537 // Remove this timer from the active pool
2538 mTimerPool.remove(this);
2539 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002540 mNesting = 1;
2541 mTotalTime = computeRunTimeLocked(batteryRealtime);
2542 mNesting = 0;
2543 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002544
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002545 if (DEBUG && mType < 0) {
2546 Log.v(TAG, "stop #" + mType + ": mUpdateTime=" + mUpdateTime
2547 + " mTotalTime=" + mTotalTime + " mCount=" + mCount
2548 + " mAcquireTime=" + mAcquireTime);
2549 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002550
Bookatzceebafe2017-04-06 11:59:13 -07002551 if (mAcquireTime >= 0 && mTotalTime == mAcquireTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002552 // If there was no change in the time, then discard this
2553 // count. A somewhat cheezy strategy, but hey.
2554 mCount--;
2555 }
2556 }
2557 }
2558
Joe Onoratoabded112016-02-08 16:49:39 -08002559 public void stopAllRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07002560 if (mNesting > 0) {
2561 mNesting = 1;
2562 stopRunningLocked(elapsedRealtimeMs);
2563 }
2564 }
2565
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566 // Update the total time for all other running Timers with the same type as this Timer
2567 // due to a change in timer count
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002568 private static long refreshTimersLocked(long batteryRealtime,
2569 final ArrayList<StopwatchTimer> pool, StopwatchTimer self) {
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002570 long selfTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002571 final int N = pool.size();
2572 for (int i=N-1; i>= 0; i--) {
Evan Millarc64edde2009-04-18 12:26:32 -07002573 final StopwatchTimer t = pool.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 long heldTime = batteryRealtime - t.mUpdateTime;
2575 if (heldTime > 0) {
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002576 final long myTime = heldTime / N;
2577 if (t == self) {
2578 selfTime = myTime;
2579 }
2580 t.mTotalTime += myTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002581 }
2582 t.mUpdateTime = batteryRealtime;
2583 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002584 return selfTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002585 }
2586
Evan Millarc64edde2009-04-18 12:26:32 -07002587 @Override
2588 protected long computeRunTimeLocked(long curBatteryRealtime) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07002589 if (mTimeout > 0 && curBatteryRealtime > mUpdateTime + mTimeout) {
2590 curBatteryRealtime = mUpdateTime + mTimeout;
2591 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002592 return mTotalTime + (mNesting > 0
2593 ? (curBatteryRealtime - mUpdateTime)
2594 / (mTimerPool != null ? mTimerPool.size() : 1)
2595 : 0);
2596 }
2597
Evan Millarc64edde2009-04-18 12:26:32 -07002598 @Override
2599 protected int computeCurrentCountLocked() {
2600 return mCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002601 }
2602
Adam Lesinskie08af192015-03-25 16:42:59 -07002603 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002604 public boolean reset(boolean detachIfReset) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002605 boolean canDetach = mNesting <= 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002606 super.reset(canDetach && detachIfReset);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002607 if (mNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08002608 mUpdateTime = mTimeBase.getRealtime(mClocks.elapsedRealtime() * 1000);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002609 }
Bookatzceebafe2017-04-06 11:59:13 -07002610 mAcquireTime = -1; // to ensure mCount isn't decreased to -1 if timer is stopped later.
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002611 return canDetach;
2612 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002613
Adam Lesinskie08af192015-03-25 16:42:59 -07002614 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002615 public void detach() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002616 super.detach();
2617 if (mTimerPool != null) {
2618 mTimerPool.remove(this);
2619 }
2620 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002621
Adam Lesinskie08af192015-03-25 16:42:59 -07002622 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002623 public void readSummaryFromParcelLocked(Parcel in) {
Evan Millarc64edde2009-04-18 12:26:32 -07002624 super.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002625 mNesting = 0;
2626 }
Adam Lesinskie08af192015-03-25 16:42:59 -07002627
2628 /**
2629 * Set the mark so that we can query later for the total time the timer has
2630 * accumulated since this point. The timer can be running or not.
2631 *
2632 * @param elapsedRealtimeMs the current elapsed realtime in milliseconds.
2633 */
2634 public void setMark(long elapsedRealtimeMs) {
2635 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
2636 if (mNesting > 0) {
2637 // We are running.
2638 if (mTimerPool != null) {
2639 refreshTimersLocked(batteryRealtime, mTimerPool, this);
2640 } else {
2641 mTotalTime += batteryRealtime - mUpdateTime;
2642 mUpdateTime = batteryRealtime;
2643 }
2644 }
2645 mTimeBeforeMark = mTotalTime;
2646 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002647 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002648
Bookatz867c0d72017-03-07 18:23:42 -08002649 /**
2650 * State for keeping track of two DurationTimers with different TimeBases, presumably where one
2651 * TimeBase is effectively a subset of the other.
2652 */
Bookatzaa4594a2017-03-24 12:39:56 -07002653 public static class DualTimer extends DurationTimer {
2654 // This class both is a DurationTimer and also holds a second DurationTimer.
2655 // The main timer (this) typically tracks the total time. It may be pooled (but since it's a
2656 // durationTimer, it also has the unpooled getTotalDurationMsLocked() for
2657 // STATS_SINCE_CHARGED).
Bookatz867c0d72017-03-07 18:23:42 -08002658 // mSubTimer typically tracks only part of the total time, such as background time, as
2659 // determined by a subTimeBase. It is NOT pooled.
2660 private final DurationTimer mSubTimer;
2661
2662 /**
Bookatzaa4594a2017-03-24 12:39:56 -07002663 * Creates a DualTimer to hold a main timer (this) and a mSubTimer.
2664 * The main timer (this) is based on the given timeBase and timerPool.
Bookatz867c0d72017-03-07 18:23:42 -08002665 * The mSubTimer is based on the given subTimeBase. The mSubTimer is not pooled, even if
Bookatzaa4594a2017-03-24 12:39:56 -07002666 * the main timer is.
Bookatz867c0d72017-03-07 18:23:42 -08002667 */
2668 public DualTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2669 TimeBase timeBase, TimeBase subTimeBase, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07002670 super(clocks, uid, type, timerPool, timeBase, in);
Bookatz867c0d72017-03-07 18:23:42 -08002671 mSubTimer = new DurationTimer(clocks, uid, type, null, subTimeBase, in);
2672 }
2673
2674 /**
Bookatzaa4594a2017-03-24 12:39:56 -07002675 * Creates a DualTimer to hold a main timer (this) and a mSubTimer.
2676 * The main timer (this) is based on the given timeBase and timerPool.
Bookatz867c0d72017-03-07 18:23:42 -08002677 * The mSubTimer is based on the given subTimeBase. The mSubTimer is not pooled, even if
Bookatzaa4594a2017-03-24 12:39:56 -07002678 * the main timer is.
Bookatz867c0d72017-03-07 18:23:42 -08002679 */
2680 public DualTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2681 TimeBase timeBase, TimeBase subTimeBase) {
Bookatzaa4594a2017-03-24 12:39:56 -07002682 super(clocks, uid, type, timerPool, timeBase);
Bookatz867c0d72017-03-07 18:23:42 -08002683 mSubTimer = new DurationTimer(clocks, uid, type, null, subTimeBase);
2684 }
2685
Bookatz867c0d72017-03-07 18:23:42 -08002686 /** Get the secondary timer. */
Bookatzaa4594a2017-03-24 12:39:56 -07002687 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002688 public DurationTimer getSubTimer() {
2689 return mSubTimer;
2690 }
2691
Bookatzaa4594a2017-03-24 12:39:56 -07002692 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002693 public void startRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002694 super.startRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002695 mSubTimer.startRunningLocked(elapsedRealtimeMs);
2696 }
2697
Bookatzaa4594a2017-03-24 12:39:56 -07002698 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002699 public void stopRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002700 super.stopRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002701 mSubTimer.stopRunningLocked(elapsedRealtimeMs);
2702 }
2703
Bookatzaa4594a2017-03-24 12:39:56 -07002704 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002705 public void stopAllRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002706 super.stopAllRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002707 mSubTimer.stopAllRunningLocked(elapsedRealtimeMs);
2708 }
2709
Bookatzaa4594a2017-03-24 12:39:56 -07002710 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002711 public boolean reset(boolean detachIfReset) {
2712 boolean active = false;
Bookatz4a3eda92017-04-10 13:10:46 -07002713 // Do not detach the subTimer explicitly since that'll be done by DualTimer.detach().
2714 active |= !mSubTimer.reset(false);
Bookatzaa4594a2017-03-24 12:39:56 -07002715 active |= !super.reset(detachIfReset);
Bookatz867c0d72017-03-07 18:23:42 -08002716 return !active;
2717 }
2718
Bookatzaa4594a2017-03-24 12:39:56 -07002719 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002720 public void detach() {
Bookatz867c0d72017-03-07 18:23:42 -08002721 mSubTimer.detach();
Bookatz4a3eda92017-04-10 13:10:46 -07002722 super.detach();
Bookatz867c0d72017-03-07 18:23:42 -08002723 }
2724
Bookatzaa4594a2017-03-24 12:39:56 -07002725 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002726 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002727 super.writeToParcel(out, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08002728 mSubTimer.writeToParcel(out, elapsedRealtimeUs);
2729 }
2730
Bookatzaa4594a2017-03-24 12:39:56 -07002731 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002732 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002733 super.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08002734 mSubTimer.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
2735 }
2736
Bookatzaa4594a2017-03-24 12:39:56 -07002737 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002738 public void readSummaryFromParcelLocked(Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07002739 super.readSummaryFromParcelLocked(in);
Bookatz867c0d72017-03-07 18:23:42 -08002740 mSubTimer.readSummaryFromParcelLocked(in);
2741 }
2742 }
2743
2744
Dianne Hackbornd953c532014-08-16 18:17:38 -07002745 public abstract class OverflowArrayMap<T> {
2746 private static final String OVERFLOW_NAME = "*overflow*";
2747
Dianne Hackborn657153b2016-07-29 14:54:14 -07002748 final int mUid;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002749 final ArrayMap<String, T> mMap = new ArrayMap<>();
2750 T mCurOverflow;
2751 ArrayMap<String, MutableInt> mActiveOverflow;
Dianne Hackborn657153b2016-07-29 14:54:14 -07002752 long mLastOverflowTime;
2753 long mLastOverflowFinishTime;
2754 long mLastClearTime;
2755 long mLastCleanupTime;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002756
Dianne Hackborn657153b2016-07-29 14:54:14 -07002757 public OverflowArrayMap(int uid) {
2758 mUid = uid;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002759 }
2760
2761 public ArrayMap<String, T> getMap() {
2762 return mMap;
2763 }
2764
2765 public void clear() {
Dianne Hackborn657153b2016-07-29 14:54:14 -07002766 mLastClearTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002767 mMap.clear();
2768 mCurOverflow = null;
2769 mActiveOverflow = null;
2770 }
2771
2772 public void add(String name, T obj) {
Joe Onorato388fc332016-04-12 17:06:47 -07002773 if (name == null) {
2774 name = "";
2775 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002776 mMap.put(name, obj);
2777 if (OVERFLOW_NAME.equals(name)) {
2778 mCurOverflow = obj;
2779 }
2780 }
2781
2782 public void cleanup() {
Dianne Hackborn657153b2016-07-29 14:54:14 -07002783 mLastCleanupTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002784 if (mActiveOverflow != null) {
2785 if (mActiveOverflow.size() == 0) {
2786 mActiveOverflow = null;
2787 }
2788 }
2789 if (mActiveOverflow == null) {
2790 // There is no currently active overflow, so we should no longer have
2791 // an overflow entry.
2792 if (mMap.containsKey(OVERFLOW_NAME)) {
2793 Slog.wtf(TAG, "Cleaning up with no active overflow, but have overflow entry "
2794 + mMap.get(OVERFLOW_NAME));
2795 mMap.remove(OVERFLOW_NAME);
2796 }
2797 mCurOverflow = null;
2798 } else {
2799 // There is currently active overflow, so we should still have an overflow entry.
2800 if (mCurOverflow == null || !mMap.containsKey(OVERFLOW_NAME)) {
2801 Slog.wtf(TAG, "Cleaning up with active overflow, but no overflow entry: cur="
2802 + mCurOverflow + " map=" + mMap.get(OVERFLOW_NAME));
2803 }
2804 }
2805 }
2806
2807 public T startObject(String name) {
Joe Onorato388fc332016-04-12 17:06:47 -07002808 if (name == null) {
2809 name = "";
2810 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002811 T obj = mMap.get(name);
2812 if (obj != null) {
2813 return obj;
2814 }
2815
2816 // No object exists for the given name, but do we currently have it
2817 // running as part of the overflow?
2818 if (mActiveOverflow != null) {
2819 MutableInt over = mActiveOverflow.get(name);
2820 if (over != null) {
2821 // We are already actively counting this name in the overflow object.
2822 obj = mCurOverflow;
2823 if (obj == null) {
2824 // Shouldn't be here, but we'll try to recover.
2825 Slog.wtf(TAG, "Have active overflow " + name + " but null overflow");
2826 obj = mCurOverflow = instantiateObject();
2827 mMap.put(OVERFLOW_NAME, obj);
2828 }
2829 over.value++;
2830 return obj;
2831 }
2832 }
2833
2834 // No object exists for given name nor in the overflow; we need to make
2835 // a new one.
2836 final int N = mMap.size();
2837 if (N >= MAX_WAKELOCKS_PER_UID) {
2838 // Went over the limit on number of objects to track; this one goes
2839 // in to the overflow.
2840 obj = mCurOverflow;
2841 if (obj == null) {
2842 // Need to start overflow now...
2843 obj = mCurOverflow = instantiateObject();
2844 mMap.put(OVERFLOW_NAME, obj);
2845 }
2846 if (mActiveOverflow == null) {
2847 mActiveOverflow = new ArrayMap<>();
2848 }
2849 mActiveOverflow.put(name, new MutableInt(1));
Dianne Hackborn657153b2016-07-29 14:54:14 -07002850 mLastOverflowTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002851 return obj;
2852 }
2853
2854 // Normal case where we just need to make a new object.
2855 obj = instantiateObject();
2856 mMap.put(name, obj);
2857 return obj;
2858 }
2859
2860 public T stopObject(String name) {
Joe Onorato388fc332016-04-12 17:06:47 -07002861 if (name == null) {
2862 name = "";
2863 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002864 T obj = mMap.get(name);
2865 if (obj != null) {
2866 return obj;
2867 }
2868
2869 // No object exists for the given name, but do we currently have it
2870 // running as part of the overflow?
2871 if (mActiveOverflow != null) {
2872 MutableInt over = mActiveOverflow.get(name);
2873 if (over != null) {
2874 // We are already actively counting this name in the overflow object.
2875 obj = mCurOverflow;
2876 if (obj != null) {
2877 over.value--;
2878 if (over.value <= 0) {
2879 mActiveOverflow.remove(name);
Dianne Hackborn657153b2016-07-29 14:54:14 -07002880 mLastOverflowFinishTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002881 }
2882 return obj;
2883 }
2884 }
2885 }
2886
2887 // Huh, they are stopping an active operation but we can't find one!
2888 // That's not good.
Dianne Hackborn657153b2016-07-29 14:54:14 -07002889 StringBuilder sb = new StringBuilder();
2890 sb.append("Unable to find object for ");
2891 sb.append(name);
2892 sb.append(" in uid ");
2893 sb.append(mUid);
2894 sb.append(" mapsize=");
2895 sb.append(mMap.size());
2896 sb.append(" activeoverflow=");
2897 sb.append(mActiveOverflow);
2898 sb.append(" curoverflow=");
2899 sb.append(mCurOverflow);
2900 long now = SystemClock.elapsedRealtime();
2901 if (mLastOverflowTime != 0) {
2902 sb.append(" lastOverflowTime=");
2903 TimeUtils.formatDuration(mLastOverflowTime-now, sb);
2904 }
2905 if (mLastOverflowFinishTime != 0) {
2906 sb.append(" lastOverflowFinishTime=");
2907 TimeUtils.formatDuration(mLastOverflowFinishTime-now, sb);
2908 }
2909 if (mLastClearTime != 0) {
2910 sb.append(" lastClearTime=");
2911 TimeUtils.formatDuration(mLastClearTime-now, sb);
2912 }
2913 if (mLastCleanupTime != 0) {
2914 sb.append(" lastCleanupTime=");
2915 TimeUtils.formatDuration(mLastCleanupTime-now, sb);
2916 }
2917 Slog.wtf(TAG, sb.toString());
Dianne Hackbornd953c532014-08-16 18:17:38 -07002918 return null;
2919 }
2920
2921 public abstract T instantiateObject();
2922 }
2923
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002924 public static class ControllerActivityCounterImpl extends ControllerActivityCounter
2925 implements Parcelable {
2926 private final LongSamplingCounter mIdleTimeMillis;
Siddharth Rayb50a6842017-12-14 15:15:28 -08002927 private final LongSamplingCounter mScanTimeMillis;
Siddharth Rayed754702018-02-15 12:44:37 -08002928 private final LongSamplingCounter mSleepTimeMillis;
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002929 private final LongSamplingCounter mRxTimeMillis;
2930 private final LongSamplingCounter[] mTxTimeMillis;
2931 private final LongSamplingCounter mPowerDrainMaMs;
2932
2933 public ControllerActivityCounterImpl(TimeBase timeBase, int numTxStates) {
2934 mIdleTimeMillis = new LongSamplingCounter(timeBase);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002935 mScanTimeMillis = new LongSamplingCounter(timeBase);
Siddharth Rayed754702018-02-15 12:44:37 -08002936 mSleepTimeMillis = new LongSamplingCounter(timeBase);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002937 mRxTimeMillis = new LongSamplingCounter(timeBase);
2938 mTxTimeMillis = new LongSamplingCounter[numTxStates];
2939 for (int i = 0; i < numTxStates; i++) {
2940 mTxTimeMillis[i] = new LongSamplingCounter(timeBase);
2941 }
2942 mPowerDrainMaMs = new LongSamplingCounter(timeBase);
2943 }
2944
2945 public ControllerActivityCounterImpl(TimeBase timeBase, int numTxStates, Parcel in) {
2946 mIdleTimeMillis = new LongSamplingCounter(timeBase, in);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002947 mScanTimeMillis = new LongSamplingCounter(timeBase, in);
Siddharth Rayed754702018-02-15 12:44:37 -08002948 mSleepTimeMillis = new LongSamplingCounter(timeBase, in);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002949 mRxTimeMillis = new LongSamplingCounter(timeBase, in);
2950 final int recordedTxStates = in.readInt();
2951 if (recordedTxStates != numTxStates) {
2952 throw new ParcelFormatException("inconsistent tx state lengths");
2953 }
2954
2955 mTxTimeMillis = new LongSamplingCounter[numTxStates];
2956 for (int i = 0; i < numTxStates; i++) {
2957 mTxTimeMillis[i] = new LongSamplingCounter(timeBase, in);
2958 }
2959 mPowerDrainMaMs = new LongSamplingCounter(timeBase, in);
2960 }
2961
2962 public void readSummaryFromParcel(Parcel in) {
2963 mIdleTimeMillis.readSummaryFromParcelLocked(in);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002964 mScanTimeMillis.readSummaryFromParcelLocked(in);
Siddharth Rayed754702018-02-15 12:44:37 -08002965 mSleepTimeMillis.readSummaryFromParcelLocked(in);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002966 mRxTimeMillis.readSummaryFromParcelLocked(in);
2967 final int recordedTxStates = in.readInt();
2968 if (recordedTxStates != mTxTimeMillis.length) {
2969 throw new ParcelFormatException("inconsistent tx state lengths");
2970 }
2971 for (LongSamplingCounter counter : mTxTimeMillis) {
2972 counter.readSummaryFromParcelLocked(in);
2973 }
2974 mPowerDrainMaMs.readSummaryFromParcelLocked(in);
2975 }
2976
2977 @Override
2978 public int describeContents() {
2979 return 0;
2980 }
2981
2982 public void writeSummaryToParcel(Parcel dest) {
2983 mIdleTimeMillis.writeSummaryFromParcelLocked(dest);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002984 mScanTimeMillis.writeSummaryFromParcelLocked(dest);
Siddharth Rayed754702018-02-15 12:44:37 -08002985 mSleepTimeMillis.writeSummaryFromParcelLocked(dest);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002986 mRxTimeMillis.writeSummaryFromParcelLocked(dest);
2987 dest.writeInt(mTxTimeMillis.length);
2988 for (LongSamplingCounter counter : mTxTimeMillis) {
2989 counter.writeSummaryFromParcelLocked(dest);
2990 }
2991 mPowerDrainMaMs.writeSummaryFromParcelLocked(dest);
2992 }
2993
2994 @Override
2995 public void writeToParcel(Parcel dest, int flags) {
2996 mIdleTimeMillis.writeToParcel(dest);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002997 mScanTimeMillis.writeToParcel(dest);
Siddharth Rayed754702018-02-15 12:44:37 -08002998 mSleepTimeMillis.writeToParcel(dest);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002999 mRxTimeMillis.writeToParcel(dest);
3000 dest.writeInt(mTxTimeMillis.length);
3001 for (LongSamplingCounter counter : mTxTimeMillis) {
3002 counter.writeToParcel(dest);
3003 }
3004 mPowerDrainMaMs.writeToParcel(dest);
3005 }
3006
3007 public void reset(boolean detachIfReset) {
3008 mIdleTimeMillis.reset(detachIfReset);
Siddharth Rayb50a6842017-12-14 15:15:28 -08003009 mScanTimeMillis.reset(detachIfReset);
Siddharth Rayed754702018-02-15 12:44:37 -08003010 mSleepTimeMillis.reset(detachIfReset);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08003011 mRxTimeMillis.reset(detachIfReset);
3012 for (LongSamplingCounter counter : mTxTimeMillis) {
3013 counter.reset(detachIfReset);
3014 }
3015 mPowerDrainMaMs.reset(detachIfReset);
3016 }
3017
3018 public void detach() {
3019 mIdleTimeMillis.detach();
Siddharth Rayb50a6842017-12-14 15:15:28 -08003020 mScanTimeMillis.detach();
Siddharth Rayed754702018-02-15 12:44:37 -08003021 mSleepTimeMillis.detach();
Adam Lesinski21f76aa2016-01-25 12:27:06 -08003022 mRxTimeMillis.detach();
3023 for (LongSamplingCounter counter : mTxTimeMillis) {
3024 counter.detach();
3025 }
3026 mPowerDrainMaMs.detach();
3027 }
3028
3029 /**
3030 * @return a LongSamplingCounter, measuring time spent in the idle state in
3031 * milliseconds.
3032 */
3033 @Override
3034 public LongSamplingCounter getIdleTimeCounter() {
Roshan Pius81643302016-03-14 16:45:55 -07003035 return mIdleTimeMillis;
Adam Lesinski21f76aa2016-01-25 12:27:06 -08003036 }
3037
3038 /**
Siddharth Rayb50a6842017-12-14 15:15:28 -08003039 * @return a LongSamplingCounter, measuring time spent in the scan state in
3040 * milliseconds.
3041 */
3042 @Override
3043 public LongSamplingCounter getScanTimeCounter() {
3044 return mScanTimeMillis;
3045 }
3046
3047 /**
Siddharth Rayed754702018-02-15 12:44:37 -08003048 * @return a LongSamplingCounter, measuring time spent in the sleep state in
3049 * milliseconds.
3050 */
3051 @Override
3052 public LongSamplingCounter getSleepTimeCounter() {
3053 return mSleepTimeMillis;
3054 }
3055
3056 /**
Adam Lesinski21f76aa2016-01-25 12:27:06 -08003057 * @return a LongSamplingCounter, measuring time spent in the receive state in
3058 * milliseconds.
3059 */
3060 @Override
3061 public LongSamplingCounter getRxTimeCounter() {
3062 return mRxTimeMillis;
3063 }
3064
3065 /**
3066 * @return a LongSamplingCounter[], measuring time spent in various transmit states in
3067 * milliseconds.
3068 */
3069 @Override
3070 public LongSamplingCounter[] getTxTimeCounters() {
3071 return mTxTimeMillis;
3072 }
3073
3074 /**
3075 * @return a LongSamplingCounter, measuring power use in milli-ampere milliseconds (mAmS).
3076 */
3077 @Override
3078 public LongSamplingCounter getPowerCounter() {
3079 return mPowerDrainMaMs;
3080 }
3081 }
3082
Bookatz50df7112017-08-04 14:53:26 -07003083 /** Get Resource Power Manager stats. Create a new one if it doesn't already exist. */
3084 public SamplingTimer getRpmTimerLocked(String name) {
3085 SamplingTimer rpmt = mRpmStats.get(name);
3086 if (rpmt == null) {
3087 rpmt = new SamplingTimer(mClocks, mOnBatteryTimeBase);
3088 mRpmStats.put(name, rpmt);
3089 }
3090 return rpmt;
3091 }
3092
3093 /** Get Screen-off Resource Power Manager stats. Create new one if it doesn't already exist. */
3094 public SamplingTimer getScreenOffRpmTimerLocked(String name) {
3095 SamplingTimer rpmt = mScreenOffRpmStats.get(name);
3096 if (rpmt == null) {
3097 rpmt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
3098 mScreenOffRpmStats.put(name, rpmt);
3099 }
3100 return rpmt;
3101 }
3102
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003103 /*
3104 * Get the wakeup reason counter, and create a new one if one
3105 * doesn't already exist.
3106 */
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07003107 public SamplingTimer getWakeupReasonTimerLocked(String name) {
3108 SamplingTimer timer = mWakeupReasonStats.get(name);
3109 if (timer == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07003110 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07003111 mWakeupReasonStats.put(name, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003112 }
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07003113 return timer;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003114 }
3115
Evan Millarc64edde2009-04-18 12:26:32 -07003116 /*
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003117 * Get the KernelWakelockTimer associated with name, and create a new one if one
Evan Millarc64edde2009-04-18 12:26:32 -07003118 * doesn't already exist.
3119 */
3120 public SamplingTimer getKernelWakelockTimerLocked(String name) {
3121 SamplingTimer kwlt = mKernelWakelockStats.get(name);
3122 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07003123 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Evan Millarc64edde2009-04-18 12:26:32 -07003124 mKernelWakelockStats.put(name, kwlt);
3125 }
3126 return kwlt;
3127 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07003128
James Carr3a226052016-07-01 14:49:52 -07003129 public SamplingTimer getKernelMemoryTimerLocked(long bucket) {
3130 SamplingTimer kmt = mKernelMemoryStats.get(bucket);
3131 if (kmt == null) {
3132 kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase);
3133 mKernelMemoryStats.put(bucket, kmt);
3134 }
3135 return kmt;
3136 }
3137
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003138 private int writeHistoryTag(HistoryTag tag) {
3139 Integer idxObj = mHistoryTagPool.get(tag);
3140 int idx;
3141 if (idxObj != null) {
3142 idx = idxObj;
3143 } else {
3144 idx = mNextHistoryTagIdx;
3145 HistoryTag key = new HistoryTag();
3146 key.setTo(tag);
3147 tag.poolIdx = idx;
3148 mHistoryTagPool.put(key, idx);
3149 mNextHistoryTagIdx++;
3150 mNumHistoryTagChars += key.string.length() + 1;
3151 }
3152 return idx;
3153 }
3154
3155 private void readHistoryTag(int index, HistoryTag tag) {
3156 tag.string = mReadHistoryStrings[index];
3157 tag.uid = mReadHistoryUids[index];
3158 tag.poolIdx = index;
3159 }
3160
Adam Lesinski926969b2016-04-28 17:31:12 -07003161 /*
3162 The history delta format uses flags to denote further data in subsequent ints in the parcel.
3163
3164 There is always the first token, which may contain the delta time, or an indicator of
3165 the length of the time (int or long) following this token.
3166
3167 First token: always present,
3168 31 23 15 7 0
3169 â–ˆ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â–ˆ
3170
3171 T: the delta time if it is <= 0x7fffd. Otherwise 0x7fffe indicates an int immediately
3172 follows containing the time, and 0x7ffff indicates a long immediately follows with the
3173 delta time.
3174 A: battery level changed and an int follows with battery data.
3175 B: state changed and an int follows with state change data.
3176 C: state2 has changed and an int follows with state2 change data.
3177 D: wakelock/wakereason has changed and an wakelock/wakereason struct follows.
3178 E: event data has changed and an event struct follows.
3179 F: battery charge in coulombs has changed and an int with the charge follows.
3180 G: state flag denoting that the mobile radio was active.
3181 H: state flag denoting that the wifi radio was active.
3182 I: state flag denoting that a wifi scan occurred.
3183 J: state flag denoting that a wifi full lock was held.
3184 K: state flag denoting that the gps was on.
3185 L: state flag denoting that a wakelock was held.
3186 M: state flag denoting that the cpu was running.
3187
3188 Time int/long: if T in the first token is 0x7ffff or 0x7fffe, then an int or long follows
3189 with the time delta.
3190
3191 Battery level int: if A in the first token is set,
3192 31 23 15 7 0
3193 â–ˆ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â–ˆ
3194
3195 D: indicates that extra history details follow.
3196 V: the battery voltage.
3197 T: the battery temperature.
3198 L: the battery level (out of 100).
3199
3200 State change int: if B in the first token is set,
3201 31 23 15 7 0
3202 â–ˆS|S|S|H|H|H|P|Pâ–ˆF|E|D|C|B| | |Aâ–ˆ | | | | | | | â–ˆ | | | | | | | â–ˆ
3203
3204 A: wifi multicast was on.
3205 B: battery was plugged in.
3206 C: screen was on.
3207 D: phone was scanning for signal.
3208 E: audio was on.
3209 F: a sensor was active.
3210
3211 State2 change int: if C in the first token is set,
3212 31 23 15 7 0
3213 â–ˆM|L|K|J|I|H|H|Gâ–ˆF|E|D|C| | | | â–ˆ | | | | | | | â–ˆ |B|B|B|A|A|A|Aâ–ˆ
3214
3215 A: 4 bits indicating the wifi supplicant state: {@link BatteryStats#WIFI_SUPPL_STATE_NAMES}.
3216 B: 3 bits indicating the wifi signal strength: 0, 1, 2, 3, 4.
3217 C: a bluetooth scan was active.
3218 D: the camera was active.
3219 E: bluetooth was on.
3220 F: a phone call was active.
3221 G: the device was charging.
3222 H: 2 bits indicating the device-idle (doze) state: off, light, full
3223 I: the flashlight was on.
3224 J: wifi was on.
3225 K: wifi was running.
3226 L: video was playing.
3227 M: power save mode was on.
3228
3229 Wakelock/wakereason struct: if D in the first token is set,
3230 TODO(adamlesinski): describe wakelock/wakereason struct.
3231
3232 Event struct: if E in the first token is set,
3233 TODO(adamlesinski): describe the event struct.
3234
3235 History step details struct: if D in the battery level int is set,
3236 TODO(adamlesinski): describe the history step details struct.
3237
3238 Battery charge int: if F in the first token is set, an int representing the battery charge
3239 in coulombs follows.
3240 */
3241
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003242 // Part of initial delta int that specifies the time delta.
Dianne Hackborne13c4c02014-02-11 17:18:35 -08003243 static final int DELTA_TIME_MASK = 0x7ffff;
3244 static final int DELTA_TIME_LONG = 0x7ffff; // The delta is a following long
3245 static final int DELTA_TIME_INT = 0x7fffe; // The delta is a following int
3246 static final int DELTA_TIME_ABS = 0x7fffd; // Following is an entire abs update.
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003247 // Flag in delta int: a new battery level int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003248 static final int DELTA_BATTERY_LEVEL_FLAG = 0x00080000;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003249 // Flag in delta int: a new full state and battery status int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003250 static final int DELTA_STATE_FLAG = 0x00100000;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08003251 // Flag in delta int: a new full state2 int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003252 static final int DELTA_STATE2_FLAG = 0x00200000;
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003253 // Flag in delta int: contains a wakelock or wakeReason tag.
Adam Lesinski926969b2016-04-28 17:31:12 -07003254 static final int DELTA_WAKELOCK_FLAG = 0x00400000;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003255 // Flag in delta int: contains an event description.
Adam Lesinski926969b2016-04-28 17:31:12 -07003256 static final int DELTA_EVENT_FLAG = 0x00800000;
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003257 // Flag in delta int: contains the battery charge count in uAh.
3258 static final int DELTA_BATTERY_CHARGE_FLAG = 0x01000000;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003259 // These upper bits are the frequently changing state bits.
Adam Lesinski926969b2016-04-28 17:31:12 -07003260 static final int DELTA_STATE_MASK = 0xfe000000;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003261
3262 // These are the pieces of battery state that are packed in to the upper bits of
3263 // the state int that have been packed in to the first delta int. They must fit
Adam Lesinski926969b2016-04-28 17:31:12 -07003264 // in STATE_BATTERY_MASK.
3265 static final int STATE_BATTERY_MASK = 0xff000000;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003266 static final int STATE_BATTERY_STATUS_MASK = 0x00000007;
3267 static final int STATE_BATTERY_STATUS_SHIFT = 29;
3268 static final int STATE_BATTERY_HEALTH_MASK = 0x00000007;
3269 static final int STATE_BATTERY_HEALTH_SHIFT = 26;
3270 static final int STATE_BATTERY_PLUG_MASK = 0x00000003;
3271 static final int STATE_BATTERY_PLUG_SHIFT = 24;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003272
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003273 // We use the low bit of the battery state int to indicate that we have full details
3274 // from a battery level change.
3275 static final int BATTERY_DELTA_LEVEL_FLAG = 0x00000001;
3276
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003277 public void writeHistoryDelta(Parcel dest, HistoryItem cur, HistoryItem last) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003278 if (last == null || cur.cmd != HistoryItem.CMD_UPDATE) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003279 dest.writeInt(DELTA_TIME_ABS);
3280 cur.writeToParcel(dest, 0);
3281 return;
3282 }
3283
3284 final long deltaTime = cur.time - last.time;
3285 final int lastBatteryLevelInt = buildBatteryLevelInt(last);
3286 final int lastStateInt = buildStateInt(last);
3287
3288 int deltaTimeToken;
3289 if (deltaTime < 0 || deltaTime > Integer.MAX_VALUE) {
3290 deltaTimeToken = DELTA_TIME_LONG;
3291 } else if (deltaTime >= DELTA_TIME_ABS) {
3292 deltaTimeToken = DELTA_TIME_INT;
3293 } else {
3294 deltaTimeToken = (int)deltaTime;
3295 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003296 int firstToken = deltaTimeToken | (cur.states&DELTA_STATE_MASK);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003297 final int includeStepDetails = mLastHistoryStepLevel > cur.batteryLevel
3298 ? BATTERY_DELTA_LEVEL_FLAG : 0;
3299 final boolean computeStepDetails = includeStepDetails != 0
3300 || mLastHistoryStepDetails == null;
3301 final int batteryLevelInt = buildBatteryLevelInt(cur) | includeStepDetails;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003302 final boolean batteryLevelIntChanged = batteryLevelInt != lastBatteryLevelInt;
3303 if (batteryLevelIntChanged) {
3304 firstToken |= DELTA_BATTERY_LEVEL_FLAG;
3305 }
3306 final int stateInt = buildStateInt(cur);
3307 final boolean stateIntChanged = stateInt != lastStateInt;
3308 if (stateIntChanged) {
3309 firstToken |= DELTA_STATE_FLAG;
3310 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003311 final boolean state2IntChanged = cur.states2 != last.states2;
3312 if (state2IntChanged) {
3313 firstToken |= DELTA_STATE2_FLAG;
3314 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003315 if (cur.wakelockTag != null || cur.wakeReasonTag != null) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003316 firstToken |= DELTA_WAKELOCK_FLAG;
3317 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003318 if (cur.eventCode != HistoryItem.EVENT_NONE) {
3319 firstToken |= DELTA_EVENT_FLAG;
3320 }
Adam Lesinski926969b2016-04-28 17:31:12 -07003321
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003322 final boolean batteryChargeChanged = cur.batteryChargeUAh != last.batteryChargeUAh;
3323 if (batteryChargeChanged) {
3324 firstToken |= DELTA_BATTERY_CHARGE_FLAG;
Adam Lesinski926969b2016-04-28 17:31:12 -07003325 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003326 dest.writeInt(firstToken);
3327 if (DEBUG) Slog.i(TAG, "WRITE DELTA: firstToken=0x" + Integer.toHexString(firstToken)
3328 + " deltaTime=" + deltaTime);
3329
3330 if (deltaTimeToken >= DELTA_TIME_INT) {
3331 if (deltaTimeToken == DELTA_TIME_INT) {
3332 if (DEBUG) Slog.i(TAG, "WRITE DELTA: int deltaTime=" + (int)deltaTime);
3333 dest.writeInt((int)deltaTime);
3334 } else {
3335 if (DEBUG) Slog.i(TAG, "WRITE DELTA: long deltaTime=" + deltaTime);
3336 dest.writeLong(deltaTime);
3337 }
3338 }
3339 if (batteryLevelIntChanged) {
3340 dest.writeInt(batteryLevelInt);
3341 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryToken=0x"
3342 + Integer.toHexString(batteryLevelInt)
3343 + " batteryLevel=" + cur.batteryLevel
3344 + " batteryTemp=" + cur.batteryTemperature
3345 + " batteryVolt=" + (int)cur.batteryVoltage);
3346 }
3347 if (stateIntChanged) {
3348 dest.writeInt(stateInt);
3349 if (DEBUG) Slog.i(TAG, "WRITE DELTA: stateToken=0x"
3350 + Integer.toHexString(stateInt)
3351 + " batteryStatus=" + cur.batteryStatus
3352 + " batteryHealth=" + cur.batteryHealth
3353 + " batteryPlugType=" + cur.batteryPlugType
3354 + " states=0x" + Integer.toHexString(cur.states));
3355 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003356 if (state2IntChanged) {
3357 dest.writeInt(cur.states2);
3358 if (DEBUG) Slog.i(TAG, "WRITE DELTA: states2=0x"
3359 + Integer.toHexString(cur.states2));
3360 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003361 if (cur.wakelockTag != null || cur.wakeReasonTag != null) {
3362 int wakeLockIndex;
3363 int wakeReasonIndex;
3364 if (cur.wakelockTag != null) {
3365 wakeLockIndex = writeHistoryTag(cur.wakelockTag);
3366 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx
3367 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string);
3368 } else {
3369 wakeLockIndex = 0xffff;
3370 }
3371 if (cur.wakeReasonTag != null) {
3372 wakeReasonIndex = writeHistoryTag(cur.wakeReasonTag);
3373 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx
3374 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string);
3375 } else {
3376 wakeReasonIndex = 0xffff;
3377 }
3378 dest.writeInt((wakeReasonIndex<<16) | wakeLockIndex);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003379 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003380 if (cur.eventCode != HistoryItem.EVENT_NONE) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003381 int index = writeHistoryTag(cur.eventTag);
3382 int codeAndIndex = (cur.eventCode&0xffff) | (index<<16);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003383 dest.writeInt(codeAndIndex);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003384 if (DEBUG) Slog.i(TAG, "WRITE DELTA: event=" + cur.eventCode + " tag=#"
3385 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":"
3386 + cur.eventTag.string);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003387 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003388 if (computeStepDetails) {
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07003389 if (mPlatformIdleStateCallback != null) {
3390 mCurHistoryStepDetails.statPlatformIdleState =
3391 mPlatformIdleStateCallback.getPlatformLowPowerStats();
3392 if (DEBUG) Slog.i(TAG, "WRITE PlatformIdleState:" +
3393 mCurHistoryStepDetails.statPlatformIdleState);
Ahmed ElArabawyd8b44112017-05-23 21:25:02 +00003394
3395 mCurHistoryStepDetails.statSubsystemPowerState =
3396 mPlatformIdleStateCallback.getSubsystemLowPowerStats();
3397 if (DEBUG) Slog.i(TAG, "WRITE SubsystemPowerState:" +
3398 mCurHistoryStepDetails.statSubsystemPowerState);
3399
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07003400 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003401 computeHistoryStepDetails(mCurHistoryStepDetails, mLastHistoryStepDetails);
3402 if (includeStepDetails != 0) {
3403 mCurHistoryStepDetails.writeToParcel(dest);
3404 }
3405 cur.stepDetails = mCurHistoryStepDetails;
3406 mLastHistoryStepDetails = mCurHistoryStepDetails;
3407 } else {
3408 cur.stepDetails = null;
3409 }
3410 if (mLastHistoryStepLevel < cur.batteryLevel) {
3411 mLastHistoryStepDetails = null;
3412 }
3413 mLastHistoryStepLevel = cur.batteryLevel;
Adam Lesinski926969b2016-04-28 17:31:12 -07003414
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003415 if (batteryChargeChanged) {
3416 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryChargeUAh=" + cur.batteryChargeUAh);
3417 dest.writeInt(cur.batteryChargeUAh);
Adam Lesinski926969b2016-04-28 17:31:12 -07003418 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003419 }
3420
3421 private int buildBatteryLevelInt(HistoryItem h) {
3422 return ((((int)h.batteryLevel)<<25)&0xfe000000)
Adam Lesinski3944c812015-11-13 15:54:59 -08003423 | ((((int)h.batteryTemperature)<<15)&0x01ff8000)
3424 | ((((int)h.batteryVoltage)<<1)&0x00007ffe);
3425 }
3426
3427 private void readBatteryLevelInt(int batteryLevelInt, HistoryItem out) {
3428 out.batteryLevel = (byte)((batteryLevelInt & 0xfe000000) >>> 25);
3429 out.batteryTemperature = (short)((batteryLevelInt & 0x01ff8000) >>> 15);
3430 out.batteryVoltage = (char)((batteryLevelInt & 0x00007ffe) >>> 1);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003431 }
3432
3433 private int buildStateInt(HistoryItem h) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003434 int plugType = 0;
3435 if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_AC) != 0) {
3436 plugType = 1;
3437 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_USB) != 0) {
3438 plugType = 2;
3439 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_WIRELESS) != 0) {
3440 plugType = 3;
3441 }
3442 return ((h.batteryStatus&STATE_BATTERY_STATUS_MASK)<<STATE_BATTERY_STATUS_SHIFT)
3443 | ((h.batteryHealth&STATE_BATTERY_HEALTH_MASK)<<STATE_BATTERY_HEALTH_SHIFT)
3444 | ((plugType&STATE_BATTERY_PLUG_MASK)<<STATE_BATTERY_PLUG_SHIFT)
Adam Lesinski926969b2016-04-28 17:31:12 -07003445 | (h.states&(~STATE_BATTERY_MASK));
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003446 }
3447
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003448 private void computeHistoryStepDetails(final HistoryStepDetails out,
3449 final HistoryStepDetails last) {
3450 final HistoryStepDetails tmp = last != null ? mTmpHistoryStepDetails : out;
3451
3452 // Perform a CPU update right after we do this collection, so we have started
3453 // collecting good data for the next step.
3454 requestImmediateCpuUpdate();
3455
3456 if (last == null) {
3457 // We are not generating a delta, so all we need to do is reset the stats
3458 // we will later be doing a delta from.
3459 final int NU = mUidStats.size();
3460 for (int i=0; i<NU; i++) {
3461 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
3462 uid.mLastStepUserTime = uid.mCurStepUserTime;
3463 uid.mLastStepSystemTime = uid.mCurStepSystemTime;
3464 }
3465 mLastStepCpuUserTime = mCurStepCpuUserTime;
3466 mLastStepCpuSystemTime = mCurStepCpuSystemTime;
3467 mLastStepStatUserTime = mCurStepStatUserTime;
3468 mLastStepStatSystemTime = mCurStepStatSystemTime;
3469 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime;
3470 mLastStepStatIrqTime = mCurStepStatIrqTime;
3471 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime;
3472 mLastStepStatIdleTime = mCurStepStatIdleTime;
3473 tmp.clear();
3474 return;
3475 }
3476 if (DEBUG) {
3477 Slog.d(TAG, "Step stats last: user=" + mLastStepCpuUserTime + " sys="
3478 + mLastStepStatSystemTime + " io=" + mLastStepStatIOWaitTime
3479 + " irq=" + mLastStepStatIrqTime + " sirq="
3480 + mLastStepStatSoftIrqTime + " idle=" + mLastStepStatIdleTime);
3481 Slog.d(TAG, "Step stats cur: user=" + mCurStepCpuUserTime + " sys="
3482 + mCurStepStatSystemTime + " io=" + mCurStepStatIOWaitTime
3483 + " irq=" + mCurStepStatIrqTime + " sirq="
3484 + mCurStepStatSoftIrqTime + " idle=" + mCurStepStatIdleTime);
3485 }
3486 out.userTime = (int)(mCurStepCpuUserTime - mLastStepCpuUserTime);
3487 out.systemTime = (int)(mCurStepCpuSystemTime - mLastStepCpuSystemTime);
3488 out.statUserTime = (int)(mCurStepStatUserTime - mLastStepStatUserTime);
3489 out.statSystemTime = (int)(mCurStepStatSystemTime - mLastStepStatSystemTime);
3490 out.statIOWaitTime = (int)(mCurStepStatIOWaitTime - mLastStepStatIOWaitTime);
3491 out.statIrqTime = (int)(mCurStepStatIrqTime - mLastStepStatIrqTime);
3492 out.statSoftIrqTime = (int)(mCurStepStatSoftIrqTime - mLastStepStatSoftIrqTime);
3493 out.statIdlTime = (int)(mCurStepStatIdleTime - mLastStepStatIdleTime);
3494 out.appCpuUid1 = out.appCpuUid2 = out.appCpuUid3 = -1;
3495 out.appCpuUTime1 = out.appCpuUTime2 = out.appCpuUTime3 = 0;
3496 out.appCpuSTime1 = out.appCpuSTime2 = out.appCpuSTime3 = 0;
3497 final int NU = mUidStats.size();
3498 for (int i=0; i<NU; i++) {
3499 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
3500 final int totalUTime = (int)(uid.mCurStepUserTime - uid.mLastStepUserTime);
3501 final int totalSTime = (int)(uid.mCurStepSystemTime - uid.mLastStepSystemTime);
3502 final int totalTime = totalUTime + totalSTime;
3503 uid.mLastStepUserTime = uid.mCurStepUserTime;
3504 uid.mLastStepSystemTime = uid.mCurStepSystemTime;
3505 if (totalTime <= (out.appCpuUTime3+out.appCpuSTime3)) {
3506 continue;
3507 }
3508 if (totalTime <= (out.appCpuUTime2+out.appCpuSTime2)) {
3509 out.appCpuUid3 = uid.mUid;
3510 out.appCpuUTime3 = totalUTime;
3511 out.appCpuSTime3 = totalSTime;
3512 } else {
3513 out.appCpuUid3 = out.appCpuUid2;
3514 out.appCpuUTime3 = out.appCpuUTime2;
3515 out.appCpuSTime3 = out.appCpuSTime2;
3516 if (totalTime <= (out.appCpuUTime1+out.appCpuSTime1)) {
3517 out.appCpuUid2 = uid.mUid;
3518 out.appCpuUTime2 = totalUTime;
3519 out.appCpuSTime2 = totalSTime;
3520 } else {
3521 out.appCpuUid2 = out.appCpuUid1;
3522 out.appCpuUTime2 = out.appCpuUTime1;
3523 out.appCpuSTime2 = out.appCpuSTime1;
3524 out.appCpuUid1 = uid.mUid;
3525 out.appCpuUTime1 = totalUTime;
3526 out.appCpuSTime1 = totalSTime;
3527 }
3528 }
3529 }
3530 mLastStepCpuUserTime = mCurStepCpuUserTime;
3531 mLastStepCpuSystemTime = mCurStepCpuSystemTime;
3532 mLastStepStatUserTime = mCurStepStatUserTime;
3533 mLastStepStatSystemTime = mCurStepStatSystemTime;
3534 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime;
3535 mLastStepStatIrqTime = mCurStepStatIrqTime;
3536 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime;
3537 mLastStepStatIdleTime = mCurStepStatIdleTime;
3538 }
3539
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003540 public void readHistoryDelta(Parcel src, HistoryItem cur) {
3541 int firstToken = src.readInt();
3542 int deltaTimeToken = firstToken&DELTA_TIME_MASK;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003543 cur.cmd = HistoryItem.CMD_UPDATE;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003544 cur.numReadInts = 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003545 if (DEBUG) Slog.i(TAG, "READ DELTA: firstToken=0x" + Integer.toHexString(firstToken)
3546 + " deltaTimeToken=" + deltaTimeToken);
3547
3548 if (deltaTimeToken < DELTA_TIME_ABS) {
3549 cur.time += deltaTimeToken;
3550 } else if (deltaTimeToken == DELTA_TIME_ABS) {
3551 cur.time = src.readLong();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003552 cur.numReadInts += 2;
3553 if (DEBUG) Slog.i(TAG, "READ DELTA: ABS time=" + cur.time);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003554 cur.readFromParcel(src);
3555 return;
3556 } else if (deltaTimeToken == DELTA_TIME_INT) {
3557 int delta = src.readInt();
3558 cur.time += delta;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003559 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003560 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time);
3561 } else {
3562 long delta = src.readLong();
3563 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time);
3564 cur.time += delta;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003565 cur.numReadInts += 2;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003566 }
3567
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003568 final int batteryLevelInt;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003569 if ((firstToken&DELTA_BATTERY_LEVEL_FLAG) != 0) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003570 batteryLevelInt = src.readInt();
Adam Lesinski3944c812015-11-13 15:54:59 -08003571 readBatteryLevelInt(batteryLevelInt, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003572 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003573 if (DEBUG) Slog.i(TAG, "READ DELTA: batteryToken=0x"
3574 + Integer.toHexString(batteryLevelInt)
3575 + " batteryLevel=" + cur.batteryLevel
3576 + " batteryTemp=" + cur.batteryTemperature
3577 + " batteryVolt=" + (int)cur.batteryVoltage);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003578 } else {
3579 batteryLevelInt = 0;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003580 }
3581
3582 if ((firstToken&DELTA_STATE_FLAG) != 0) {
3583 int stateInt = src.readInt();
Adam Lesinski926969b2016-04-28 17:31:12 -07003584 cur.states = (firstToken&DELTA_STATE_MASK) | (stateInt&(~STATE_BATTERY_MASK));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003585 cur.batteryStatus = (byte)((stateInt>>STATE_BATTERY_STATUS_SHIFT)
3586 & STATE_BATTERY_STATUS_MASK);
3587 cur.batteryHealth = (byte)((stateInt>>STATE_BATTERY_HEALTH_SHIFT)
3588 & STATE_BATTERY_HEALTH_MASK);
3589 cur.batteryPlugType = (byte)((stateInt>>STATE_BATTERY_PLUG_SHIFT)
3590 & STATE_BATTERY_PLUG_MASK);
3591 switch (cur.batteryPlugType) {
3592 case 1:
3593 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_AC;
3594 break;
3595 case 2:
3596 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_USB;
3597 break;
3598 case 3:
3599 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_WIRELESS;
3600 break;
3601 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003602 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003603 if (DEBUG) Slog.i(TAG, "READ DELTA: stateToken=0x"
3604 + Integer.toHexString(stateInt)
3605 + " batteryStatus=" + cur.batteryStatus
3606 + " batteryHealth=" + cur.batteryHealth
3607 + " batteryPlugType=" + cur.batteryPlugType
3608 + " states=0x" + Integer.toHexString(cur.states));
3609 } else {
Adam Lesinski926969b2016-04-28 17:31:12 -07003610 cur.states = (firstToken&DELTA_STATE_MASK) | (cur.states&(~STATE_BATTERY_MASK));
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003611 }
3612
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003613 if ((firstToken&DELTA_STATE2_FLAG) != 0) {
3614 cur.states2 = src.readInt();
3615 if (DEBUG) Slog.i(TAG, "READ DELTA: states2=0x"
3616 + Integer.toHexString(cur.states2));
3617 }
3618
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003619 if ((firstToken&DELTA_WAKELOCK_FLAG) != 0) {
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003620 int indexes = src.readInt();
3621 int wakeLockIndex = indexes&0xffff;
3622 int wakeReasonIndex = (indexes>>16)&0xffff;
3623 if (wakeLockIndex != 0xffff) {
3624 cur.wakelockTag = cur.localWakelockTag;
3625 readHistoryTag(wakeLockIndex, cur.wakelockTag);
3626 if (DEBUG) Slog.i(TAG, "READ DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx
3627 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string);
3628 } else {
3629 cur.wakelockTag = null;
3630 }
3631 if (wakeReasonIndex != 0xffff) {
3632 cur.wakeReasonTag = cur.localWakeReasonTag;
3633 readHistoryTag(wakeReasonIndex, cur.wakeReasonTag);
3634 if (DEBUG) Slog.i(TAG, "READ DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx
3635 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string);
3636 } else {
3637 cur.wakeReasonTag = null;
3638 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003639 cur.numReadInts += 1;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003640 } else {
3641 cur.wakelockTag = null;
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003642 cur.wakeReasonTag = null;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003643 }
3644
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003645 if ((firstToken&DELTA_EVENT_FLAG) != 0) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003646 cur.eventTag = cur.localEventTag;
3647 final int codeAndIndex = src.readInt();
Dianne Hackborn099bc622014-01-22 13:39:16 -08003648 cur.eventCode = (codeAndIndex&0xffff);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003649 final int index = ((codeAndIndex>>16)&0xffff);
3650 readHistoryTag(index, cur.eventTag);
3651 cur.numReadInts += 1;
3652 if (DEBUG) Slog.i(TAG, "READ DELTA: event=" + cur.eventCode + " tag=#"
3653 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":"
3654 + cur.eventTag.string);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003655 } else {
3656 cur.eventCode = HistoryItem.EVENT_NONE;
3657 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003658
3659 if ((batteryLevelInt&BATTERY_DELTA_LEVEL_FLAG) != 0) {
3660 cur.stepDetails = mReadHistoryStepDetails;
3661 cur.stepDetails.readFromParcel(src);
3662 } else {
3663 cur.stepDetails = null;
3664 }
Adam Lesinski926969b2016-04-28 17:31:12 -07003665
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003666 if ((firstToken&DELTA_BATTERY_CHARGE_FLAG) != 0) {
3667 cur.batteryChargeUAh = src.readInt();
Adam Lesinski926969b2016-04-28 17:31:12 -07003668 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003669 }
3670
Dianne Hackbornfc064132014-06-02 12:42:12 -07003671 @Override
3672 public void commitCurrentHistoryBatchLocked() {
3673 mHistoryLastWritten.cmd = HistoryItem.CMD_NULL;
3674 }
3675
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003676 void addHistoryBufferLocked(long elapsedRealtimeMs, HistoryItem cur) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003677 if (!mHaveBatteryLevel || !mRecordingHistory) {
3678 return;
3679 }
3680
Dianne Hackborn40c87252014-03-19 16:55:40 -07003681 final long timeDiff = (mHistoryBaseTime+elapsedRealtimeMs) - mHistoryLastWritten.time;
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003682 final int diffStates = mHistoryLastWritten.states^(cur.states&mActiveHistoryStates);
3683 final int diffStates2 = mHistoryLastWritten.states2^(cur.states2&mActiveHistoryStates2);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003684 final int lastDiffStates = mHistoryLastWritten.states^mHistoryLastLastWritten.states;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003685 final int lastDiffStates2 = mHistoryLastWritten.states2^mHistoryLastLastWritten.states2;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003686 if (DEBUG) Slog.i(TAG, "ADD: tdelta=" + timeDiff + " diff="
3687 + Integer.toHexString(diffStates) + " lastDiff="
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003688 + Integer.toHexString(lastDiffStates) + " diff2="
3689 + Integer.toHexString(diffStates2) + " lastDiff2="
3690 + Integer.toHexString(lastDiffStates2));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003691 if (mHistoryBufferLastPos >= 0 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003692 && timeDiff < 1000 && (diffStates&lastDiffStates) == 0
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003693 && (diffStates2&lastDiffStates2) == 0
3694 && (mHistoryLastWritten.wakelockTag == null || cur.wakelockTag == null)
3695 && (mHistoryLastWritten.wakeReasonTag == null || cur.wakeReasonTag == null)
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003696 && mHistoryLastWritten.stepDetails == null
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003697 && (mHistoryLastWritten.eventCode == HistoryItem.EVENT_NONE
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003698 || cur.eventCode == HistoryItem.EVENT_NONE)
3699 && mHistoryLastWritten.batteryLevel == cur.batteryLevel
3700 && mHistoryLastWritten.batteryStatus == cur.batteryStatus
3701 && mHistoryLastWritten.batteryHealth == cur.batteryHealth
3702 && mHistoryLastWritten.batteryPlugType == cur.batteryPlugType
3703 && mHistoryLastWritten.batteryTemperature == cur.batteryTemperature
3704 && mHistoryLastWritten.batteryVoltage == cur.batteryVoltage) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003705 // We can merge this new change in with the last one. Merging is
Dianne Hackborn40c87252014-03-19 16:55:40 -07003706 // allowed as long as only the states have changed, and within those states
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003707 // as long as no bit has changed both between now and the last entry, as
3708 // well as the last entry and the one before it (so we capture any toggles).
3709 if (DEBUG) Slog.i(TAG, "ADD: rewinding back to " + mHistoryBufferLastPos);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003710 mHistoryBuffer.setDataSize(mHistoryBufferLastPos);
3711 mHistoryBuffer.setDataPosition(mHistoryBufferLastPos);
3712 mHistoryBufferLastPos = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003713 elapsedRealtimeMs = mHistoryLastWritten.time - mHistoryBaseTime;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003714 // If the last written history had a wakelock tag, we need to retain it.
3715 // Note that the condition above made sure that we aren't in a case where
3716 // both it and the current history item have a wakelock tag.
3717 if (mHistoryLastWritten.wakelockTag != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003718 cur.wakelockTag = cur.localWakelockTag;
3719 cur.wakelockTag.setTo(mHistoryLastWritten.wakelockTag);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003720 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003721 // If the last written history had a wake reason tag, we need to retain it.
3722 // Note that the condition above made sure that we aren't in a case where
3723 // both it and the current history item have a wakelock tag.
3724 if (mHistoryLastWritten.wakeReasonTag != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003725 cur.wakeReasonTag = cur.localWakeReasonTag;
3726 cur.wakeReasonTag.setTo(mHistoryLastWritten.wakeReasonTag);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003727 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003728 // If the last written history had an event, we need to retain it.
3729 // Note that the condition above made sure that we aren't in a case where
3730 // both it and the current history item have an event.
3731 if (mHistoryLastWritten.eventCode != HistoryItem.EVENT_NONE) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003732 cur.eventCode = mHistoryLastWritten.eventCode;
3733 cur.eventTag = cur.localEventTag;
3734 cur.eventTag.setTo(mHistoryLastWritten.eventTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003735 }
Dianne Hackborn1fadab52011-04-14 17:57:33 -07003736 mHistoryLastWritten.setTo(mHistoryLastLastWritten);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003737 }
3738
Adam Lesinski45489782016-12-15 23:45:17 -08003739 boolean recordResetDueToOverflow = false;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003740 final int dataSize = mHistoryBuffer.dataSize();
Adam Lesinski45489782016-12-15 23:45:17 -08003741 if (dataSize >= MAX_MAX_HISTORY_BUFFER*3) {
3742 // Clients can't deal with history buffers this large. This only
3743 // really happens when the device is on charger and interacted with
3744 // for long periods of time, like in retail mode. Since the device is
3745 // most likely charged, when unplugged, stats would have reset anyways.
3746 // Reset the stats and mark that we overflowed.
3747 // b/32540341
3748 resetAllStatsLocked();
3749
3750 // Mark that we want to set *OVERFLOW* event and the RESET:START
3751 // events.
3752 recordResetDueToOverflow = true;
3753
3754 } else if (dataSize >= MAX_HISTORY_BUFFER) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003755 if (!mHistoryOverflow) {
3756 mHistoryOverflow = true;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003757 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, cur);
3758 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_OVERFLOW, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003759 return;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003760 }
3761
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003762 // After overflow, we allow various bit-wise states to settle to 0.
3763 boolean writeAnyway = false;
3764 final int curStates = cur.states & HistoryItem.SETTLE_TO_ZERO_STATES
3765 & mActiveHistoryStates;
3766 if (mHistoryLastWritten.states != curStates) {
3767 // mActiveHistoryStates keeps track of which bits in .states are now being
3768 // forced to 0.
3769 int old = mActiveHistoryStates;
3770 mActiveHistoryStates &= curStates | ~HistoryItem.SETTLE_TO_ZERO_STATES;
3771 writeAnyway |= old != mActiveHistoryStates;
3772 }
3773 final int curStates2 = cur.states2 & HistoryItem.SETTLE_TO_ZERO_STATES2
3774 & mActiveHistoryStates2;
3775 if (mHistoryLastWritten.states2 != curStates2) {
3776 // mActiveHistoryStates2 keeps track of which bits in .states2 are now being
3777 // forced to 0.
3778 int old = mActiveHistoryStates2;
3779 mActiveHistoryStates2 &= curStates2 | ~HistoryItem.SETTLE_TO_ZERO_STATES2;
3780 writeAnyway |= old != mActiveHistoryStates2;
3781 }
3782
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003783 // Once we've reached the maximum number of items, we only
3784 // record changes to the battery level and the most interesting states.
3785 // Once we've reached the maximum maximum number of items, we only
3786 // record changes to the battery level.
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003787 if (!writeAnyway && mHistoryLastWritten.batteryLevel == cur.batteryLevel &&
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003788 (dataSize >= MAX_MAX_HISTORY_BUFFER
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003789 || ((mHistoryLastWritten.states^cur.states)
Dianne Hackborn3251b902014-06-20 14:40:53 -07003790 & HistoryItem.MOST_INTERESTING_STATES) == 0
3791 || ((mHistoryLastWritten.states2^cur.states2)
3792 & HistoryItem.MOST_INTERESTING_STATES2) == 0)) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003793 return;
3794 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003795
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003796 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003797 return;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003798 }
3799
Adam Lesinski45489782016-12-15 23:45:17 -08003800 if (dataSize == 0 || recordResetDueToOverflow) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003801 // The history is currently empty; we need it to start with a time stamp.
3802 cur.currentTime = System.currentTimeMillis();
Adam Lesinski45489782016-12-15 23:45:17 -08003803 if (recordResetDueToOverflow) {
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003804 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_OVERFLOW, cur);
Adam Lesinski45489782016-12-15 23:45:17 -08003805 }
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003806 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_RESET, cur);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003807 }
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003808 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003809 }
3810
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003811 private void addHistoryBufferLocked(long elapsedRealtimeMs, byte cmd, HistoryItem cur) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003812 if (mIteratingHistory) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003813 throw new IllegalStateException("Can't do this while iterating history!");
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003814 }
3815 mHistoryBufferLastPos = mHistoryBuffer.dataPosition();
3816 mHistoryLastLastWritten.setTo(mHistoryLastWritten);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003817 mHistoryLastWritten.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003818 mHistoryLastWritten.states &= mActiveHistoryStates;
3819 mHistoryLastWritten.states2 &= mActiveHistoryStates2;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003820 writeHistoryDelta(mHistoryBuffer, mHistoryLastWritten, mHistoryLastLastWritten);
Dianne Hackborn40c87252014-03-19 16:55:40 -07003821 mLastHistoryElapsedRealtime = elapsedRealtimeMs;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003822 cur.wakelockTag = null;
3823 cur.wakeReasonTag = null;
3824 cur.eventCode = HistoryItem.EVENT_NONE;
3825 cur.eventTag = null;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003826 if (DEBUG_HISTORY) Slog.i(TAG, "Writing history buffer: was " + mHistoryBufferLastPos
3827 + " now " + mHistoryBuffer.dataPosition()
3828 + " size is now " + mHistoryBuffer.dataSize());
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003829 }
3830
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003831 int mChangedStates = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003832 int mChangedStates2 = 0;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003833
Dianne Hackborn40c87252014-03-19 16:55:40 -07003834 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003835 if (mTrackRunningHistoryElapsedRealtime != 0) {
3836 final long diffElapsed = elapsedRealtimeMs - mTrackRunningHistoryElapsedRealtime;
3837 final long diffUptime = uptimeMs - mTrackRunningHistoryUptime;
3838 if (diffUptime < (diffElapsed-20)) {
3839 final long wakeElapsedTime = elapsedRealtimeMs - (diffElapsed - diffUptime);
3840 mHistoryAddTmp.setTo(mHistoryLastWritten);
3841 mHistoryAddTmp.wakelockTag = null;
3842 mHistoryAddTmp.wakeReasonTag = null;
3843 mHistoryAddTmp.eventCode = HistoryItem.EVENT_NONE;
3844 mHistoryAddTmp.states &= ~HistoryItem.STATE_CPU_RUNNING_FLAG;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003845 addHistoryRecordInnerLocked(wakeElapsedTime, mHistoryAddTmp);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003846 }
3847 }
3848 mHistoryCur.states |= HistoryItem.STATE_CPU_RUNNING_FLAG;
3849 mTrackRunningHistoryElapsedRealtime = elapsedRealtimeMs;
3850 mTrackRunningHistoryUptime = uptimeMs;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003851 addHistoryRecordInnerLocked(elapsedRealtimeMs, mHistoryCur);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003852 }
3853
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003854 void addHistoryRecordInnerLocked(long elapsedRealtimeMs, HistoryItem cur) {
3855 addHistoryBufferLocked(elapsedRealtimeMs, cur);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003856
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003857 if (!USE_OLD_HISTORY) {
3858 return;
3859 }
3860
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003861 if (!mHaveBatteryLevel || !mRecordingHistory) {
3862 return;
3863 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003864
3865 // If the current time is basically the same as the last time,
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003866 // and no states have since the last recorded entry changed and
3867 // are now resetting back to their original value, then just collapse
3868 // into one record.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003869 if (mHistoryEnd != null && mHistoryEnd.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn40c87252014-03-19 16:55:40 -07003870 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+1000)
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003871 && ((mHistoryEnd.states^cur.states)&mChangedStates&mActiveHistoryStates) == 0
3872 && ((mHistoryEnd.states2^cur.states2)&mChangedStates2&mActiveHistoryStates2) == 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003873 // If the current is the same as the one before, then we no
3874 // longer need the entry.
3875 if (mHistoryLastEnd != null && mHistoryLastEnd.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn40c87252014-03-19 16:55:40 -07003876 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+500)
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003877 && mHistoryLastEnd.sameNonEvent(cur)) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003878 mHistoryLastEnd.next = null;
3879 mHistoryEnd.next = mHistoryCache;
3880 mHistoryCache = mHistoryEnd;
3881 mHistoryEnd = mHistoryLastEnd;
3882 mHistoryLastEnd = null;
3883 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003884 mChangedStates |= mHistoryEnd.states^(cur.states&mActiveHistoryStates);
3885 mChangedStates2 |= mHistoryEnd.states^(cur.states2&mActiveHistoryStates2);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003886 mHistoryEnd.setTo(mHistoryEnd.time, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003887 }
3888 return;
3889 }
3890
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003891 mChangedStates = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003892 mChangedStates2 = 0;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003893
3894 if (mNumHistoryItems == MAX_HISTORY_ITEMS
3895 || mNumHistoryItems == MAX_MAX_HISTORY_ITEMS) {
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003896 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_OVERFLOW, cur);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07003897 }
3898
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003899 if (mNumHistoryItems >= MAX_HISTORY_ITEMS) {
3900 // Once we've reached the maximum number of items, we only
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003901 // record changes to the battery level and the most interesting states.
3902 // Once we've reached the maximum maximum number of items, we only
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003903 // record changes to the battery level.
3904 if (mHistoryEnd != null && mHistoryEnd.batteryLevel
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003905 == cur.batteryLevel &&
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003906 (mNumHistoryItems >= MAX_MAX_HISTORY_ITEMS
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003907 || ((mHistoryEnd.states^(cur.states&mActiveHistoryStates))
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003908 & HistoryItem.MOST_INTERESTING_STATES) == 0)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003909 return;
3910 }
3911 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003912
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003913 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003914 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003915
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003916 public void addHistoryEventLocked(long elapsedRealtimeMs, long uptimeMs, int code,
Dianne Hackborn40c87252014-03-19 16:55:40 -07003917 String name, int uid) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003918 mHistoryCur.eventCode = code;
3919 mHistoryCur.eventTag = mHistoryCur.localEventTag;
3920 mHistoryCur.eventTag.string = name;
3921 mHistoryCur.eventTag.uid = uid;
Dianne Hackborn4590e522014-03-24 13:36:46 -07003922 addHistoryRecordLocked(elapsedRealtimeMs, uptimeMs);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003923 }
3924
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003925 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs, byte cmd, HistoryItem cur) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003926 HistoryItem rec = mHistoryCache;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003927 if (rec != null) {
3928 mHistoryCache = rec.next;
3929 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003930 rec = new HistoryItem();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003931 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003932 rec.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003933
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003934 addHistoryRecordLocked(rec);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003935 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003936
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003937 void addHistoryRecordLocked(HistoryItem rec) {
3938 mNumHistoryItems++;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003939 rec.next = null;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003940 mHistoryLastEnd = mHistoryEnd;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003941 if (mHistoryEnd != null) {
3942 mHistoryEnd.next = rec;
3943 mHistoryEnd = rec;
3944 } else {
3945 mHistory = mHistoryEnd = rec;
3946 }
3947 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003948
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003949 void clearHistoryLocked() {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003950 if (DEBUG_HISTORY) Slog.i(TAG, "********** CLEARING HISTORY!");
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003951 if (USE_OLD_HISTORY) {
3952 if (mHistory != null) {
3953 mHistoryEnd.next = mHistoryCache;
3954 mHistoryCache = mHistory;
3955 mHistory = mHistoryLastEnd = mHistoryEnd = null;
3956 }
3957 mNumHistoryItems = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003958 }
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003959
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003960 mHistoryBaseTime = 0;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003961 mLastHistoryElapsedRealtime = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003962 mTrackRunningHistoryElapsedRealtime = 0;
3963 mTrackRunningHistoryUptime = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003964
3965 mHistoryBuffer.setDataSize(0);
3966 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003967 mHistoryBuffer.setDataCapacity(MAX_HISTORY_BUFFER / 2);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003968 mHistoryLastLastWritten.clear();
3969 mHistoryLastWritten.clear();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003970 mHistoryTagPool.clear();
3971 mNextHistoryTagIdx = 0;
3972 mNumHistoryTagChars = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003973 mHistoryBufferLastPos = -1;
3974 mHistoryOverflow = false;
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003975 mActiveHistoryStates = 0xffffffff;
3976 mActiveHistoryStates2 = 0xffffffff;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003977 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003978
Andreas Gampe3f24e692018-02-05 13:24:28 -08003979 @GuardedBy("this")
Mike Mac2f518a2017-09-19 16:06:03 -07003980 public void updateTimeBasesLocked(boolean unplugged, int screenState, long uptime,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003981 long realtime) {
Mike Maa7724752017-10-10 15:29:25 -07003982 final boolean screenOff = !isScreenOn(screenState);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003983 final boolean updateOnBatteryTimeBase = unplugged != mOnBatteryTimeBase.isRunning();
3984 final boolean updateOnBatteryScreenOffTimeBase =
3985 (unplugged && screenOff) != mOnBatteryScreenOffTimeBase.isRunning();
Bookatz867c0d72017-03-07 18:23:42 -08003986
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003987 if (updateOnBatteryScreenOffTimeBase || updateOnBatteryTimeBase) {
3988 if (updateOnBatteryScreenOffTimeBase) {
3989 updateKernelWakelocksLocked();
3990 updateBatteryPropertiesLocked();
Bookatz867c0d72017-03-07 18:23:42 -08003991 }
Bookatz82b341172017-09-07 19:06:08 -07003992 // This if{} is only necessary due to SCREEN_OFF_RPM_STATS_ENABLED, which exists because
3993 // updateRpmStatsLocked is too slow to run each screen change. When the speed is
3994 // improved, remove the surrounding if{}.
3995 if (SCREEN_OFF_RPM_STATS_ENABLED || updateOnBatteryTimeBase) {
3996 updateRpmStatsLocked(); // if either OnBattery or OnBatteryScreenOff timebase changes.
3997 }
Adam Lesinski72478f02015-06-17 15:39:43 -07003998 if (DEBUG_ENERGY_CPU) {
Mike Mac2f518a2017-09-19 16:06:03 -07003999 Slog.d(TAG, "Updating cpu time because screen is now "
4000 + Display.stateToString(screenState)
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07004001 + " and battery is " + (unplugged ? "on" : "off"));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004002 }
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07004003
4004 mOnBatteryTimeBase.setRunning(unplugged, uptime, realtime);
Mike Mac2f518a2017-09-19 16:06:03 -07004005 if (updateOnBatteryTimeBase) {
4006 for (int i = mUidStats.size() - 1; i >= 0; --i) {
4007 mUidStats.valueAt(i).updateOnBatteryBgTimeBase(uptime, realtime);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07004008 }
Mike Mac2f518a2017-09-19 16:06:03 -07004009 }
4010 if (updateOnBatteryScreenOffTimeBase) {
4011 mOnBatteryScreenOffTimeBase.setRunning(unplugged && screenOff, uptime, realtime);
4012 for (int i = mUidStats.size() - 1; i >= 0; --i) {
4013 mUidStats.valueAt(i).updateOnBatteryScreenOffBgTimeBase(uptime, realtime);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07004014 }
Bookatzc8c44962017-05-11 12:12:54 -07004015 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004016 }
4017 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07004018
Adam Lesinskie1f480d2017-02-15 18:51:23 -08004019 private void updateBatteryPropertiesLocked() {
4020 try {
4021 IBatteryPropertiesRegistrar registrar = IBatteryPropertiesRegistrar.Stub.asInterface(
4022 ServiceManager.getService("batteryproperties"));
4023 registrar.scheduleUpdate();
4024 } catch (RemoteException e) {
4025 // Ignore.
4026 }
4027 }
4028
Dianne Hackborn099bc622014-01-22 13:39:16 -08004029 public void addIsolatedUidLocked(int isolatedUid, int appUid) {
4030 mIsolatedUids.put(isolatedUid, appUid);
Bookatz90867622018-01-31 15:05:57 -08004031 StatsLog.write(StatsLog.ISOLATED_UID_CHANGED, appUid, isolatedUid,
4032 StatsLog.ISOLATED_UID_CHANGED__EVENT__CREATED);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08004033 final Uid u = getUidStatsLocked(appUid);
4034 u.addIsolatedUid(isolatedUid);
Dianne Hackborn099bc622014-01-22 13:39:16 -08004035 }
4036
Adam Lesinski61db88f2015-07-01 15:05:07 -07004037 /**
4038 * Schedules a read of the latest cpu times before removing the isolated UID.
4039 * @see #removeIsolatedUidLocked(int)
4040 */
4041 public void scheduleRemoveIsolatedUidLocked(int isolatedUid, int appUid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004042 int curUid = mIsolatedUids.get(isolatedUid, -1);
4043 if (curUid == appUid) {
Adam Lesinski61db88f2015-07-01 15:05:07 -07004044 if (mExternalSync != null) {
4045 mExternalSync.scheduleCpuSyncDueToRemovedUid(isolatedUid);
4046 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08004047 }
4048 }
4049
Adam Lesinski61db88f2015-07-01 15:05:07 -07004050 /**
4051 * This should only be called after the cpu times have been read.
4052 * @see #scheduleRemoveIsolatedUidLocked(int, int)
4053 */
Andreas Gampe3f24e692018-02-05 13:24:28 -08004054 @GuardedBy("this")
Adam Lesinski61db88f2015-07-01 15:05:07 -07004055 public void removeIsolatedUidLocked(int isolatedUid) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08004056 StatsLog.write(
Bookatz90867622018-01-31 15:05:57 -08004057 StatsLog.ISOLATED_UID_CHANGED, mIsolatedUids.get(isolatedUid, -1),
4058 isolatedUid, StatsLog.ISOLATED_UID_CHANGED__EVENT__REMOVED);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08004059 final int idx = mIsolatedUids.indexOfKey(isolatedUid);
4060 if (idx >= 0) {
4061 final int ownerUid = mIsolatedUids.valueAt(idx);
4062 final Uid u = getUidStatsLocked(ownerUid);
4063 u.removeIsolatedUid(isolatedUid);
4064 mIsolatedUids.removeAt(idx);
4065 }
Mike Ma234d1822018-03-13 18:53:21 -07004066 mPendingRemovedUids.add(new UidToRemove(isolatedUid, mClocks.elapsedRealtime()));
Adam Lesinski61db88f2015-07-01 15:05:07 -07004067 }
4068
Dianne Hackborn099bc622014-01-22 13:39:16 -08004069 public int mapUid(int uid) {
4070 int isolated = mIsolatedUids.get(uid, -1);
4071 return isolated > 0 ? isolated : uid;
4072 }
4073
4074 public void noteEventLocked(int code, String name, int uid) {
4075 uid = mapUid(uid);
Dianne Hackborn37de0982014-05-09 09:32:18 -07004076 if (!mActiveEvents.updateState(code, name, uid, 0)) {
4077 return;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08004078 }
Joe Onoratoabded112016-02-08 16:49:39 -08004079 final long elapsedRealtime = mClocks.elapsedRealtime();
4080 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -07004081 addHistoryEventLocked(elapsedRealtime, uptime, code, name, uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -08004082 }
4083
Dianne Hackbornd48954f2015-07-22 17:20:33 -07004084 boolean ensureStartClockTime(final long currentTime) {
4085 final long ABOUT_ONE_YEAR = 365*24*60*60*1000L;
Makoto Onuki62b3c922018-04-25 14:51:56 -07004086 if ((currentTime > ABOUT_ONE_YEAR && mStartClockTime < (currentTime-ABOUT_ONE_YEAR))
4087 || (mStartClockTime > currentTime)) {
Dianne Hackbornd48954f2015-07-22 17:20:33 -07004088 // If the start clock time has changed by more than a year, then presumably
4089 // the previous time was completely bogus. So we are going to figure out a
4090 // new time based on how much time has elapsed since we started counting.
Joe Onoratoabded112016-02-08 16:49:39 -08004091 mStartClockTime = currentTime - (mClocks.elapsedRealtime()-(mRealtimeStart/1000));
Dianne Hackbornd48954f2015-07-22 17:20:33 -07004092 return true;
4093 }
4094 return false;
4095 }
4096
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07004097 public void noteCurrentTimeChangedLocked() {
4098 final long currentTime = System.currentTimeMillis();
Joe Onoratoabded112016-02-08 16:49:39 -08004099 final long elapsedRealtime = mClocks.elapsedRealtime();
4100 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07004101 recordCurrentTimeChangeLocked(currentTime, elapsedRealtime, uptime);
Dianne Hackbornd48954f2015-07-22 17:20:33 -07004102 ensureStartClockTime(currentTime);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07004103 }
4104
Dianne Hackborn61659e52014-07-09 16:13:01 -07004105 public void noteProcessStartLocked(String name, int uid) {
4106 uid = mapUid(uid);
4107 if (isOnBattery()) {
4108 Uid u = getUidStatsLocked(uid);
4109 u.getProcessStatsLocked(name).incStartsLocked();
4110 }
4111 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_START, name, uid, 0)) {
4112 return;
4113 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004114 if (!mRecordAllHistory) {
4115 return;
4116 }
Joe Onoratoabded112016-02-08 16:49:39 -08004117 final long elapsedRealtime = mClocks.elapsedRealtime();
4118 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn61659e52014-07-09 16:13:01 -07004119 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_START, name, uid);
4120 }
4121
Dianne Hackborn1e01d162014-12-04 17:46:42 -08004122 public void noteProcessCrashLocked(String name, int uid) {
4123 uid = mapUid(uid);
4124 if (isOnBattery()) {
4125 Uid u = getUidStatsLocked(uid);
4126 u.getProcessStatsLocked(name).incNumCrashesLocked();
4127 }
4128 }
4129
4130 public void noteProcessAnrLocked(String name, int uid) {
4131 uid = mapUid(uid);
4132 if (isOnBattery()) {
4133 Uid u = getUidStatsLocked(uid);
4134 u.getProcessStatsLocked(name).incNumAnrsLocked();
4135 }
4136 }
4137
Dianne Hackborna8d10942015-11-19 17:55:19 -08004138 public void noteUidProcessStateLocked(int uid, int state) {
Amith Yamasanifd3caf62017-07-26 11:48:35 -07004139 int parentUid = mapUid(uid);
4140 if (uid != parentUid) {
4141 // Isolated UIDs process state is already rolled up into parent, so no need to track
4142 // Otherwise the parent's process state will get downgraded incorrectly
4143 return;
4144 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08004145 getUidStatsLocked(uid).updateUidProcessStateLocked(state);
Dianne Hackborn61659e52014-07-09 16:13:01 -07004146 }
4147
4148 public void noteProcessFinishLocked(String name, int uid) {
4149 uid = mapUid(uid);
4150 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_FINISH, name, uid, 0)) {
4151 return;
4152 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004153 if (!mRecordAllHistory) {
4154 return;
4155 }
Joe Onoratoabded112016-02-08 16:49:39 -08004156 final long elapsedRealtime = mClocks.elapsedRealtime();
4157 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004158 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_FINISH, name, uid);
Dianne Hackborn61659e52014-07-09 16:13:01 -07004159 }
4160
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004161 public void noteSyncStartLocked(String name, int uid) {
4162 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004163 final long elapsedRealtime = mClocks.elapsedRealtime();
4164 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004165 getUidStatsLocked(uid).noteStartSyncLocked(name, elapsedRealtime);
4166 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_START, name, uid, 0)) {
4167 return;
4168 }
4169 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_START, name, uid);
4170 }
4171
4172 public void noteSyncFinishLocked(String name, int uid) {
4173 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004174 final long elapsedRealtime = mClocks.elapsedRealtime();
4175 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004176 getUidStatsLocked(uid).noteStopSyncLocked(name, elapsedRealtime);
4177 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_FINISH, name, uid, 0)) {
4178 return;
4179 }
4180 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_FINISH, name, uid);
4181 }
4182
4183 public void noteJobStartLocked(String name, int uid) {
4184 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004185 final long elapsedRealtime = mClocks.elapsedRealtime();
4186 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004187 getUidStatsLocked(uid).noteStartJobLocked(name, elapsedRealtime);
4188 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_START, name, uid, 0)) {
4189 return;
4190 }
4191 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_START, name, uid);
4192 }
4193
Dianne Hackborn94326cb2017-06-28 16:17:20 -07004194 public void noteJobFinishLocked(String name, int uid, int stopReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004195 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004196 final long elapsedRealtime = mClocks.elapsedRealtime();
4197 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07004198 getUidStatsLocked(uid).noteStopJobLocked(name, elapsedRealtime, stopReason);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004199 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_FINISH, name, uid, 0)) {
4200 return;
4201 }
4202 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_FINISH, name, uid);
4203 }
4204
Amith Yamasani977e11f2018-02-16 11:29:54 -08004205 public void noteJobsDeferredLocked(int uid, int numDeferred, long sinceLast) {
4206 uid = mapUid(uid);
4207 getUidStatsLocked(uid).noteJobsDeferredLocked(numDeferred, sinceLast);
4208 }
4209
Narayan Kamath695cf722017-12-21 18:32:47 +00004210 public void noteAlarmStartLocked(String name, WorkSource workSource, int uid) {
4211 noteAlarmStartOrFinishLocked(HistoryItem.EVENT_ALARM_START, name, workSource, uid);
Dianne Hackborn1e383822015-04-10 14:02:33 -07004212 }
4213
Narayan Kamath695cf722017-12-21 18:32:47 +00004214 public void noteAlarmFinishLocked(String name, WorkSource workSource, int uid) {
4215 noteAlarmStartOrFinishLocked(HistoryItem.EVENT_ALARM_FINISH, name, workSource, uid);
4216 }
4217
4218 private void noteAlarmStartOrFinishLocked(int historyItem, String name, WorkSource workSource,
4219 int uid) {
Dianne Hackborn1e383822015-04-10 14:02:33 -07004220 if (!mRecordAllHistory) {
4221 return;
4222 }
Narayan Kamath695cf722017-12-21 18:32:47 +00004223
Joe Onoratoabded112016-02-08 16:49:39 -08004224 final long elapsedRealtime = mClocks.elapsedRealtime();
4225 final long uptime = mClocks.uptimeMillis();
Narayan Kamath695cf722017-12-21 18:32:47 +00004226
4227 if (workSource != null) {
4228 for (int i = 0; i < workSource.size(); ++i) {
4229 uid = mapUid(workSource.get(i));
4230 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4231 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4232 }
4233 }
4234
4235 List<WorkChain> workChains = workSource.getWorkChains();
4236 if (workChains != null) {
4237 for (int i = 0; i < workChains.size(); ++i) {
4238 uid = mapUid(workChains.get(i).getAttributionUid());
4239 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4240 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4241 }
4242 }
4243 }
4244 } else {
4245 uid = mapUid(uid);
4246
4247 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4248 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4249 }
4250 }
4251 }
4252
4253 public void noteWakupAlarmLocked(String packageName, int uid, WorkSource workSource,
4254 String tag) {
Narayan Kamath695cf722017-12-21 18:32:47 +00004255 if (workSource != null) {
4256 for (int i = 0; i < workSource.size(); ++i) {
4257 uid = workSource.get(i);
4258 final String workSourceName = workSource.getName(i);
4259
Tej Singh6f724c42018-01-03 20:02:03 -08004260 if (isOnBattery()) {
4261 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid,
4262 workSourceName != null ? workSourceName : packageName);
4263 pkg.noteWakeupAlarmLocked(tag);
4264 }
Yangster-mac2f5daec2018-01-16 10:23:15 -08004265 StatsLog.write_non_chained(StatsLog.WAKEUP_ALARM_OCCURRED, workSource.get(i),
4266 workSource.getName(i), tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004267 }
4268
4269 ArrayList<WorkChain> workChains = workSource.getWorkChains();
4270 if (workChains != null) {
4271 for (int i = 0; i < workChains.size(); ++i) {
4272 final WorkChain wc = workChains.get(i);
4273 uid = wc.getAttributionUid();
4274
Tej Singh6f724c42018-01-03 20:02:03 -08004275 if (isOnBattery()) {
4276 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid, packageName);
4277 pkg.noteWakeupAlarmLocked(tag);
4278 }
Yangster-macafad8c62018-01-05 22:30:49 -08004279 StatsLog.write(StatsLog.WAKEUP_ALARM_OCCURRED, wc.getUids(), wc.getTags(), tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004280 }
4281 }
4282 } else {
Tej Singh6f724c42018-01-03 20:02:03 -08004283 if (isOnBattery()) {
4284 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid, packageName);
4285 pkg.noteWakeupAlarmLocked(tag);
4286 }
Yangster-mac2f5daec2018-01-16 10:23:15 -08004287 StatsLog.write_non_chained(StatsLog.WAKEUP_ALARM_OCCURRED, uid, null, tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004288 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07004289 }
4290
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004291 private void requestWakelockCpuUpdate() {
Sudheer Shankac57729a2018-02-09 15:44:42 -08004292 mExternalSync.scheduleCpuSyncDueToWakelockChange(DELAY_UPDATE_WAKELOCKS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004293 }
4294
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004295 private void requestImmediateCpuUpdate() {
Sudheer Shankac57729a2018-02-09 15:44:42 -08004296 mExternalSync.scheduleCpuSyncDueToWakelockChange(0 /* delayMillis */);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004297 }
4298
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004299 public void setRecordAllHistoryLocked(boolean enabled) {
4300 mRecordAllHistory = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004301 if (!enabled) {
4302 // Clear out any existing state.
4303 mActiveEvents.removeEvents(HistoryItem.EVENT_WAKE_LOCK);
Dianne Hackborn1e383822015-04-10 14:02:33 -07004304 mActiveEvents.removeEvents(HistoryItem.EVENT_ALARM);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004305 // Record the currently running processes as stopping, now that we are no
4306 // longer tracking them.
4307 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
4308 HistoryItem.EVENT_PROC);
4309 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08004310 long mSecRealtime = mClocks.elapsedRealtime();
4311 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004312 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
4313 SparseIntArray uids = ent.getValue();
4314 for (int j=0; j<uids.size(); j++) {
4315 addHistoryEventLocked(mSecRealtime, mSecUptime,
4316 HistoryItem.EVENT_PROC_FINISH, ent.getKey(), uids.keyAt(j));
4317 }
4318 }
4319 }
4320 } else {
4321 // Record the currently running processes as starting, now that we are tracking them.
4322 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
4323 HistoryItem.EVENT_PROC);
4324 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08004325 long mSecRealtime = mClocks.elapsedRealtime();
4326 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004327 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
4328 SparseIntArray uids = ent.getValue();
4329 for (int j=0; j<uids.size(); j++) {
4330 addHistoryEventLocked(mSecRealtime, mSecUptime,
4331 HistoryItem.EVENT_PROC_START, ent.getKey(), uids.keyAt(j));
4332 }
4333 }
4334 }
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004335 }
4336 }
4337
Dianne Hackborn9a755432014-05-15 17:05:22 -07004338 public void setNoAutoReset(boolean enabled) {
4339 mNoAutoReset = enabled;
4340 }
4341
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004342 public void setPretendScreenOff(boolean pretendScreenOff) {
Mike Mac2f518a2017-09-19 16:06:03 -07004343 if (mPretendScreenOff != pretendScreenOff) {
4344 mPretendScreenOff = pretendScreenOff;
4345 noteScreenStateLocked(pretendScreenOff ? Display.STATE_OFF : Display.STATE_ON);
4346 }
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004347 }
4348
Dianne Hackborn9a755432014-05-15 17:05:22 -07004349 private String mInitialAcquireWakeName;
4350 private int mInitialAcquireWakeUid = -1;
4351
Narayan Kamath81822022017-12-08 11:56:01 +00004352 public void noteStartWakeLocked(int uid, int pid, WorkChain wc, String name, String historyName,
4353 int type, boolean unimportantForLogging, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004354 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004355 if (type == WAKE_TYPE_PARTIAL) {
4356 // Only care about partial wake locks, since full wake locks
4357 // will be canceled when the user puts the screen to sleep.
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004358 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07004359 if (historyName == null) {
4360 historyName = name;
4361 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004362 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07004363 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_START, historyName,
4364 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07004365 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07004366 HistoryItem.EVENT_WAKE_LOCK_START, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07004367 }
4368 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004369 if (mWakeLockNesting == 0) {
4370 mHistoryCur.states |= HistoryItem.STATE_WAKE_LOCK_FLAG;
4371 if (DEBUG_HISTORY) Slog.v(TAG, "Start wake lock to: "
4372 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08004373 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004374 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07004375 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004376 mWakeLockImportant = !unimportantForLogging;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004377 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07004378 } else if (!mWakeLockImportant && !unimportantForLogging
4379 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004380 if (mHistoryLastWritten.wakelockTag != null) {
4381 // We'll try to update the last tag.
4382 mHistoryLastWritten.wakelockTag = null;
4383 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004384 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07004385 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004386 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004387 }
4388 mWakeLockImportant = true;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004389 }
4390 mWakeLockNesting++;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004391 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004392 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07004393 if (mOnBatteryScreenOffTimeBase.isRunning()) {
4394 // We only update the cpu time when a wake lock is acquired if the screen is off.
4395 // If the screen is on, we don't distribute the power amongst partial wakelocks.
4396 if (DEBUG_ENERGY_CPU) {
4397 Slog.d(TAG, "Updating cpu time because of +wake_lock");
4398 }
4399 requestWakelockCpuUpdate();
4400 }
Narayan Kamath81822022017-12-08 11:56:01 +00004401
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004402 getUidStatsLocked(uid).noteStartWakeLocked(pid, name, type, elapsedRealtime);
Narayan Kamath81822022017-12-08 11:56:01 +00004403
Yangster-mac20877162017-12-22 17:19:39 -08004404 if (wc != null) {
Bookatz1a1b0462018-01-12 11:47:03 -08004405 StatsLog.write(StatsLog.WAKELOCK_STATE_CHANGED, wc.getUids(), wc.getTags(),
Bookatz90867622018-01-31 15:05:57 -08004406 getPowerManagerWakeLockLevel(type), name,
4407 StatsLog.WAKELOCK_STATE_CHANGED__STATE__ACQUIRE);
Yangster-macafad8c62018-01-05 22:30:49 -08004408 } else {
Bookatz1a1b0462018-01-12 11:47:03 -08004409 StatsLog.write_non_chained(StatsLog.WAKELOCK_STATE_CHANGED, uid, null,
Bookatz90867622018-01-31 15:05:57 -08004410 getPowerManagerWakeLockLevel(type), name,
4411 StatsLog.WAKELOCK_STATE_CHANGED__STATE__ACQUIRE);
Narayan Kamath81822022017-12-08 11:56:01 +00004412 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004413 }
4414 }
4415
Narayan Kamath81822022017-12-08 11:56:01 +00004416 public void noteStopWakeLocked(int uid, int pid, WorkChain wc, String name, String historyName,
4417 int type, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004418 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004419 if (type == WAKE_TYPE_PARTIAL) {
4420 mWakeLockNesting--;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004421 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07004422 if (historyName == null) {
4423 historyName = name;
4424 }
4425 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName,
4426 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07004427 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07004428 HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07004429 }
4430 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004431 if (mWakeLockNesting == 0) {
4432 mHistoryCur.states &= ~HistoryItem.STATE_WAKE_LOCK_FLAG;
4433 if (DEBUG_HISTORY) Slog.v(TAG, "Stop wake lock to: "
4434 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn37de0982014-05-09 09:32:18 -07004435 mInitialAcquireWakeName = null;
4436 mInitialAcquireWakeUid = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004437 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004438 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004439 }
4440 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07004441 if (mOnBatteryScreenOffTimeBase.isRunning()) {
4442 if (DEBUG_ENERGY_CPU) {
4443 Slog.d(TAG, "Updating cpu time because of -wake_lock");
4444 }
4445 requestWakelockCpuUpdate();
4446 }
Narayan Kamath81822022017-12-08 11:56:01 +00004447
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004448 getUidStatsLocked(uid).noteStopWakeLocked(pid, name, type, elapsedRealtime);
Yangster-mac20877162017-12-22 17:19:39 -08004449 if (wc != null) {
Bookatz1a1b0462018-01-12 11:47:03 -08004450 StatsLog.write(StatsLog.WAKELOCK_STATE_CHANGED, wc.getUids(), wc.getTags(),
Bookatz90867622018-01-31 15:05:57 -08004451 getPowerManagerWakeLockLevel(type), name,
4452 StatsLog.WAKELOCK_STATE_CHANGED__STATE__RELEASE);
Yangster-macafad8c62018-01-05 22:30:49 -08004453 } else {
Bookatz1a1b0462018-01-12 11:47:03 -08004454 StatsLog.write_non_chained(StatsLog.WAKELOCK_STATE_CHANGED, uid, null,
Bookatz90867622018-01-31 15:05:57 -08004455 getPowerManagerWakeLockLevel(type), name,
4456 StatsLog.WAKELOCK_STATE_CHANGED__STATE__RELEASE);
Narayan Kamath81822022017-12-08 11:56:01 +00004457 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004458 }
4459 }
4460
Bookatz1a1b0462018-01-12 11:47:03 -08004461 /**
4462 * Converts BatteryStats wakelock types back into PowerManager wakelock levels.
4463 * This is the inverse map of Notifier.getBatteryStatsWakeLockMonitorType().
4464 * These are estimations, since batterystats loses some of the original data.
4465 * TODO: Delete this. Instead, StatsLog.write should be called from PowerManager's Notifier.
4466 */
4467 private int getPowerManagerWakeLockLevel(int battertStatsWakelockType) {
4468 switch (battertStatsWakelockType) {
4469 // PowerManager.PARTIAL_WAKE_LOCK or PROXIMITY_SCREEN_OFF_WAKE_LOCK
4470 case BatteryStats.WAKE_TYPE_PARTIAL:
4471 return PowerManager.PARTIAL_WAKE_LOCK;
4472
4473 // PowerManager.SCREEN_DIM_WAKE_LOCK or SCREEN_BRIGHT_WAKE_LOCK
4474 case BatteryStats.WAKE_TYPE_FULL:
4475 return PowerManager.FULL_WAKE_LOCK;
4476
4477 case BatteryStats.WAKE_TYPE_DRAW:
4478 return PowerManager.DRAW_WAKE_LOCK;
4479
4480 // It appears that nothing can ever make a Window and PowerManager lacks an equivalent.
4481 case BatteryStats.WAKE_TYPE_WINDOW:
4482 Slog.e(TAG, "Illegal window wakelock type observed in batterystats.");
4483 return -1;
4484
4485 default:
4486 Slog.e(TAG, "Illegal wakelock type in batterystats: " + battertStatsWakelockType);
4487 return -1;
4488 }
4489 }
4490
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004491 public void noteStartWakeFromSourceLocked(WorkSource ws, int pid, String name,
4492 String historyName, int type, boolean unimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08004493 final long elapsedRealtime = mClocks.elapsedRealtime();
4494 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004495 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004496 for (int i=0; i<N; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004497 noteStartWakeLocked(ws.get(i), pid, null, name, historyName, type,
4498 unimportantForLogging, elapsedRealtime, uptime);
4499 }
4500
4501 List<WorkChain> wcs = ws.getWorkChains();
4502 if (wcs != null) {
4503 for (int i = 0; i < wcs.size(); ++i) {
4504 final WorkChain wc = wcs.get(i);
4505 noteStartWakeLocked(wc.getAttributionUid(), pid, wc, name, historyName, type,
4506 unimportantForLogging, elapsedRealtime, uptime);
4507 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004508 }
4509 }
4510
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004511 public void noteChangeWakelockFromSourceLocked(WorkSource ws, int pid, String name,
4512 String historyName, int type, WorkSource newWs, int newPid, String newName,
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004513 String newHistoryName, int newType, boolean newUnimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08004514 final long elapsedRealtime = mClocks.elapsedRealtime();
4515 final long uptime = mClocks.uptimeMillis();
Narayan Kamath81822022017-12-08 11:56:01 +00004516
4517 List<WorkChain>[] wcs = WorkSource.diffChains(ws, newWs);
4518
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004519 // For correct semantics, we start the need worksources first, so that we won't
4520 // make inappropriate history items as if all wake locks went away and new ones
4521 // appeared. This is okay because tracking of wake locks allows nesting.
Narayan Kamath81822022017-12-08 11:56:01 +00004522 //
4523 // First the starts :
Dianne Hackborn40c87252014-03-19 16:55:40 -07004524 final int NN = newWs.size();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004525 for (int i=0; i<NN; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004526 noteStartWakeLocked(newWs.get(i), newPid, null, newName, newHistoryName, newType,
Dianne Hackborn40c87252014-03-19 16:55:40 -07004527 newUnimportantForLogging, elapsedRealtime, uptime);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004528 }
Narayan Kamath81822022017-12-08 11:56:01 +00004529 if (wcs != null) {
4530 List<WorkChain> newChains = wcs[0];
4531 if (newChains != null) {
4532 for (int i = 0; i < newChains.size(); ++i) {
4533 final WorkChain newChain = newChains.get(i);
4534 noteStartWakeLocked(newChain.getAttributionUid(), newPid, newChain, newName,
4535 newHistoryName, newType, newUnimportantForLogging, elapsedRealtime,
4536 uptime);
4537 }
4538 }
4539 }
4540
4541 // Then the stops :
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004542 final int NO = ws.size();
4543 for (int i=0; i<NO; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004544 noteStopWakeLocked(ws.get(i), pid, null, name, historyName, type, elapsedRealtime,
4545 uptime);
4546 }
4547 if (wcs != null) {
4548 List<WorkChain> goneChains = wcs[1];
4549 if (goneChains != null) {
4550 for (int i = 0; i < goneChains.size(); ++i) {
4551 final WorkChain goneChain = goneChains.get(i);
4552 noteStopWakeLocked(goneChain.getAttributionUid(), pid, goneChain, name,
4553 historyName, type, elapsedRealtime, uptime);
4554 }
4555 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004556 }
4557 }
4558
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004559 public void noteStopWakeFromSourceLocked(WorkSource ws, int pid, String name,
4560 String historyName, int type) {
Joe Onoratoabded112016-02-08 16:49:39 -08004561 final long elapsedRealtime = mClocks.elapsedRealtime();
4562 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004563 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004564 for (int i=0; i<N; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004565 noteStopWakeLocked(ws.get(i), pid, null, name, historyName, type, elapsedRealtime,
4566 uptime);
4567 }
4568
4569 List<WorkChain> wcs = ws.getWorkChains();
4570 if (wcs != null) {
4571 for (int i = 0; i < wcs.size(); ++i) {
4572 final WorkChain wc = wcs.get(i);
4573 noteStopWakeLocked(wc.getAttributionUid(), pid, wc, name, historyName, type,
4574 elapsedRealtime, uptime);
4575 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004576 }
4577 }
4578
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004579 public void noteLongPartialWakelockStart(String name, String historyName, int uid) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08004580 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004581 uid, null, name, historyName,
4582 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
Yangster-macafad8c62018-01-05 22:30:49 -08004583
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004584 uid = mapUid(uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004585 noteLongPartialWakeLockStartInternal(name, historyName, uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004586 }
4587
4588 public void noteLongPartialWakelockStartFromSource(String name, String historyName,
4589 WorkSource workSource) {
4590 final int N = workSource.size();
4591 for (int i = 0; i < N; ++i) {
4592 final int uid = mapUid(workSource.get(i));
4593 noteLongPartialWakeLockStartInternal(name, historyName, uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08004594 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004595 workSource.get(i), workSource.getName(i), name, historyName,
4596 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath96a92562018-01-02 18:57:17 +00004597 }
4598
4599 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
4600 if (workChains != null) {
4601 for (int i = 0; i < workChains.size(); ++i) {
4602 final WorkChain workChain = workChains.get(i);
4603 final int uid = workChain.getAttributionUid();
4604 noteLongPartialWakeLockStartInternal(name, historyName, uid);
4605
Yangster-macafad8c62018-01-05 22:30:49 -08004606 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004607 workChain.getUids(), workChain.getTags(), name, historyName,
4608 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath96a92562018-01-02 18:57:17 +00004609 }
4610 }
4611 }
4612
4613 private void noteLongPartialWakeLockStartInternal(String name, String historyName, int uid) {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004614 final long elapsedRealtime = mClocks.elapsedRealtime();
4615 final long uptime = mClocks.uptimeMillis();
4616 if (historyName == null) {
4617 historyName = name;
4618 }
4619 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_START, historyName, uid,
4620 0)) {
4621 return;
4622 }
4623 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_START,
4624 historyName, uid);
4625 }
4626
4627 public void noteLongPartialWakelockFinish(String name, String historyName, int uid) {
Bookatz90867622018-01-31 15:05:57 -08004628 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED, uid, null,
4629 name, historyName, StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
Yangster-macafad8c62018-01-05 22:30:49 -08004630
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004631 uid = mapUid(uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004632 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004633 }
4634
4635 public void noteLongPartialWakelockFinishFromSource(String name, String historyName,
4636 WorkSource workSource) {
4637 final int N = workSource.size();
4638 for (int i = 0; i < N; ++i) {
4639 final int uid = mapUid(workSource.get(i));
4640 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08004641 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004642 workSource.get(i), workSource.getName(i), name, historyName,
4643 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath96a92562018-01-02 18:57:17 +00004644 }
4645
4646 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
4647 if (workChains != null) {
4648 for (int i = 0; i < workChains.size(); ++i) {
4649 final WorkChain workChain = workChains.get(i);
4650 final int uid = workChain.getAttributionUid();
Narayan Kamath96a92562018-01-02 18:57:17 +00004651 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Yangster-macafad8c62018-01-05 22:30:49 -08004652 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004653 workChain.getUids(), workChain.getTags(), name, historyName,
4654 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath96a92562018-01-02 18:57:17 +00004655 }
4656 }
4657 }
4658
4659 private void noteLongPartialWakeLockFinishInternal(String name, String historyName, int uid) {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004660 final long elapsedRealtime = mClocks.elapsedRealtime();
4661 final long uptime = mClocks.uptimeMillis();
4662 if (historyName == null) {
4663 historyName = name;
4664 }
4665 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH, historyName, uid,
4666 0)) {
4667 return;
4668 }
4669 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH,
4670 historyName, uid);
4671 }
4672
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004673 void aggregateLastWakeupUptimeLocked(long uptimeMs) {
4674 if (mLastWakeupReason != null) {
4675 long deltaUptime = uptimeMs - mLastWakeupUptimeMs;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004676 SamplingTimer timer = getWakeupReasonTimerLocked(mLastWakeupReason);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07004677 timer.add(deltaUptime * 1000, 1); // time in in microseconds
Bookatz90867622018-01-31 15:05:57 -08004678 StatsLog.write(StatsLog.KERNEL_WAKEUP_REPORTED, mLastWakeupReason,
4679 /* duration_usec */ deltaUptime * 1000);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004680 mLastWakeupReason = null;
4681 }
4682 }
4683
4684 public void noteWakeupReasonLocked(String reason) {
Joe Onoratoabded112016-02-08 16:49:39 -08004685 final long elapsedRealtime = mClocks.elapsedRealtime();
4686 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004687 if (DEBUG_HISTORY) Slog.v(TAG, "Wakeup reason \"" + reason +"\": "
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004688 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004689 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004690 mHistoryCur.wakeReasonTag = mHistoryCur.localWakeReasonTag;
4691 mHistoryCur.wakeReasonTag.string = reason;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004692 mHistoryCur.wakeReasonTag.uid = 0;
4693 mLastWakeupReason = reason;
4694 mLastWakeupUptimeMs = uptime;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004695 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004696 }
4697
Adam Lesinski72478f02015-06-17 15:39:43 -07004698 public boolean startAddingCpuLocked() {
Sudheer Shankac57729a2018-02-09 15:44:42 -08004699 mExternalSync.cancelCpuSyncDueToWakelockChange();
Adam Lesinski72478f02015-06-17 15:39:43 -07004700 return mOnBatteryInternal;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004701 }
4702
Adam Lesinski72478f02015-06-17 15:39:43 -07004703 public void finishAddingCpuLocked(int totalUTime, int totalSTime, int statUserTime,
4704 int statSystemTime, int statIOWaitTime, int statIrqTime,
4705 int statSoftIrqTime, int statIdleTime) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004706 if (DEBUG) Slog.d(TAG, "Adding cpu: tuser=" + totalUTime + " tsys=" + totalSTime
4707 + " user=" + statUserTime + " sys=" + statSystemTime
4708 + " io=" + statIOWaitTime + " irq=" + statIrqTime
4709 + " sirq=" + statSoftIrqTime + " idle=" + statIdleTime);
4710 mCurStepCpuUserTime += totalUTime;
4711 mCurStepCpuSystemTime += totalSTime;
4712 mCurStepStatUserTime += statUserTime;
4713 mCurStepStatSystemTime += statSystemTime;
4714 mCurStepStatIOWaitTime += statIOWaitTime;
4715 mCurStepStatIrqTime += statIrqTime;
4716 mCurStepStatSoftIrqTime += statSoftIrqTime;
4717 mCurStepStatIdleTime += statIdleTime;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004718 }
4719
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004720 public void noteProcessDiedLocked(int uid, int pid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004721 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004722 Uid u = mUidStats.get(uid);
4723 if (u != null) {
4724 u.mPids.remove(pid);
4725 }
4726 }
4727
4728 public long getProcessWakeTime(int uid, int pid, long realtime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004729 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004730 Uid u = mUidStats.get(uid);
4731 if (u != null) {
4732 Uid.Pid p = u.mPids.get(pid);
4733 if (p != null) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004734 return p.mWakeSumMs + (p.mWakeNesting > 0 ? (realtime - p.mWakeStartMs) : 0);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004735 }
4736 }
4737 return 0;
4738 }
4739
Dianne Hackborn287952c2010-09-22 22:34:31 -07004740 public void reportExcessiveCpuLocked(int uid, String proc, long overTime, long usedTime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004741 uid = mapUid(uid);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004742 Uid u = mUidStats.get(uid);
4743 if (u != null) {
4744 u.reportExcessiveCpuLocked(proc, overTime, usedTime);
4745 }
4746 }
4747
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004748 int mSensorNesting;
4749
4750 public void noteStartSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004751 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004752 final long elapsedRealtime = mClocks.elapsedRealtime();
4753 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004754 if (mSensorNesting == 0) {
4755 mHistoryCur.states |= HistoryItem.STATE_SENSOR_ON_FLAG;
4756 if (DEBUG_HISTORY) Slog.v(TAG, "Start sensor to: "
4757 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004758 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004759 }
4760 mSensorNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004761 getUidStatsLocked(uid).noteStartSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004762 }
4763
4764 public void noteStopSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004765 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004766 final long elapsedRealtime = mClocks.elapsedRealtime();
4767 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004768 mSensorNesting--;
4769 if (mSensorNesting == 0) {
4770 mHistoryCur.states &= ~HistoryItem.STATE_SENSOR_ON_FLAG;
4771 if (DEBUG_HISTORY) Slog.v(TAG, "Stop sensor to: "
4772 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004773 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004774 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004775 getUidStatsLocked(uid).noteStopSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004776 }
4777
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004778 int mGpsNesting;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004779
Narayan Kamath32684dd2018-01-08 17:32:51 +00004780 public void noteGpsChangedLocked(WorkSource oldWs, WorkSource newWs) {
4781 for (int i = 0; i < newWs.size(); ++i) {
4782 noteStartGpsLocked(newWs.get(i), null);
4783 }
4784
4785 for (int i = 0; i < oldWs.size(); ++i) {
4786 noteStopGpsLocked((oldWs.get(i)), null);
4787 }
4788
4789 List<WorkChain>[] wcs = WorkSource.diffChains(oldWs, newWs);
4790 if (wcs != null) {
4791 if (wcs[0] != null) {
4792 final List<WorkChain> newChains = wcs[0];
4793 for (int i = 0; i < newChains.size(); ++i) {
4794 noteStartGpsLocked(-1, newChains.get(i));
4795 }
4796 }
4797
4798 if (wcs[1] != null) {
4799 final List<WorkChain> goneChains = wcs[1];
4800 for (int i = 0; i < goneChains.size(); ++i) {
4801 noteStopGpsLocked(-1, goneChains.get(i));
4802 }
4803 }
4804 }
4805 }
4806
4807 private void noteStartGpsLocked(int uid, WorkChain workChain) {
4808 uid = getAttributionUid(uid, workChain);
Joe Onoratoabded112016-02-08 16:49:39 -08004809 final long elapsedRealtime = mClocks.elapsedRealtime();
4810 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004811 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004812 mHistoryCur.states |= HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004813 if (DEBUG_HISTORY) Slog.v(TAG, "Start GPS to: "
4814 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004815 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004816 }
4817 mGpsNesting++;
Narayan Kamath32684dd2018-01-08 17:32:51 +00004818
4819 if (workChain == null) {
Bookatz90867622018-01-31 15:05:57 -08004820 StatsLog.write_non_chained(StatsLog.GPS_SCAN_STATE_CHANGED, uid, null,
4821 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004822 } else {
4823 StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004824 workChain.getUids(), workChain.getTags(),
4825 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004826 }
4827
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004828 getUidStatsLocked(uid).noteStartGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004829 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004830
Narayan Kamath32684dd2018-01-08 17:32:51 +00004831 private void noteStopGpsLocked(int uid, WorkChain workChain) {
4832 uid = getAttributionUid(uid, workChain);
Joe Onoratoabded112016-02-08 16:49:39 -08004833 final long elapsedRealtime = mClocks.elapsedRealtime();
4834 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004835 mGpsNesting--;
4836 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004837 mHistoryCur.states &= ~HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004838 if (DEBUG_HISTORY) Slog.v(TAG, "Stop GPS to: "
4839 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004840 addHistoryRecordLocked(elapsedRealtime, uptime);
Siddharth Ray78ccaf52017-12-23 16:16:21 -08004841 stopAllGpsSignalQualityTimersLocked(-1);
4842 mGpsSignalQualityBin = -1;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004843 }
Narayan Kamath32684dd2018-01-08 17:32:51 +00004844
4845 if (workChain == null) {
Bookatz90867622018-01-31 15:05:57 -08004846 StatsLog.write_non_chained(StatsLog.GPS_SCAN_STATE_CHANGED, uid, null,
4847 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004848 } else {
4849 StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED, workChain.getUids(),
Bookatz90867622018-01-31 15:05:57 -08004850 workChain.getTags(), StatsLog.GPS_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004851 }
4852
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004853 getUidStatsLocked(uid).noteStopGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004854 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07004855
Siddharth Ray78ccaf52017-12-23 16:16:21 -08004856 public void noteGpsSignalQualityLocked(int signalLevel) {
4857 if (mGpsNesting == 0) {
4858 return;
4859 }
4860 if (signalLevel < 0 || signalLevel >= GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS) {
4861 stopAllGpsSignalQualityTimersLocked(-1);
4862 return;
4863 }
4864 final long elapsedRealtime = mClocks.elapsedRealtime();
4865 final long uptime = mClocks.uptimeMillis();
4866 if (mGpsSignalQualityBin != signalLevel) {
4867 if (mGpsSignalQualityBin >= 0) {
4868 mGpsSignalQualityTimer[mGpsSignalQualityBin].stopRunningLocked(elapsedRealtime);
4869 }
4870 if(!mGpsSignalQualityTimer[signalLevel].isRunningLocked()) {
4871 mGpsSignalQualityTimer[signalLevel].startRunningLocked(elapsedRealtime);
4872 }
4873 mHistoryCur.states2 = (mHistoryCur.states2&~HistoryItem.STATE2_GPS_SIGNAL_QUALITY_MASK)
4874 | (signalLevel << HistoryItem.STATE2_GPS_SIGNAL_QUALITY_SHIFT);
4875 addHistoryRecordLocked(elapsedRealtime, uptime);
4876 mGpsSignalQualityBin = signalLevel;
4877 }
4878 return;
4879 }
4880
Andreas Gampe3f24e692018-02-05 13:24:28 -08004881 @GuardedBy("this")
Jeff Browne95c3cd2014-05-02 16:59:26 -07004882 public void noteScreenStateLocked(int state) {
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004883 state = mPretendScreenOff ? Display.STATE_OFF : state;
Santos Cordone94f0502017-02-24 12:31:20 -08004884
4885 // Battery stats relies on there being 4 states. To accommodate this, new states beyond the
4886 // original 4 are mapped to one of the originals.
4887 if (state > MAX_TRACKED_SCREEN_STATE) {
4888 switch (state) {
4889 case Display.STATE_VR:
4890 state = Display.STATE_ON;
4891 break;
4892 default:
4893 Slog.wtf(TAG, "Unknown screen state (not mapped): " + state);
4894 break;
4895 }
4896 }
4897
Jeff Browne95c3cd2014-05-02 16:59:26 -07004898 if (mScreenState != state) {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08004899 recordDailyStatsIfNeededLocked(true);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004900 final int oldState = mScreenState;
4901 mScreenState = state;
4902 if (DEBUG) Slog.v(TAG, "Screen state: oldState=" + Display.stateToString(oldState)
4903 + ", newState=" + Display.stateToString(state));
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004904
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004905 if (state != Display.STATE_UNKNOWN) {
4906 int stepState = state-1;
Santos Cordone94f0502017-02-24 12:31:20 -08004907 if ((stepState & STEP_LEVEL_MODE_SCREEN_STATE) == stepState) {
4908 mModStepMode |= (mCurStepMode & STEP_LEVEL_MODE_SCREEN_STATE) ^ stepState;
4909 mCurStepMode = (mCurStepMode & ~STEP_LEVEL_MODE_SCREEN_STATE) | stepState;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004910 } else {
4911 Slog.wtf(TAG, "Unexpected screen state: " + state);
4912 }
4913 }
4914
Mike Mac2f518a2017-09-19 16:06:03 -07004915 final long elapsedRealtime = mClocks.elapsedRealtime();
4916 final long uptime = mClocks.uptimeMillis();
4917
4918 boolean updateHistory = false;
4919 if (isScreenDoze(state)) {
4920 mHistoryCur.states |= HistoryItem.STATE_SCREEN_DOZE_FLAG;
4921 mScreenDozeTimer.startRunningLocked(elapsedRealtime);
4922 updateHistory = true;
4923 } else if (isScreenDoze(oldState)) {
4924 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_DOZE_FLAG;
4925 mScreenDozeTimer.stopRunningLocked(elapsedRealtime);
4926 updateHistory = true;
4927 }
4928 if (isScreenOn(state)) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07004929 mHistoryCur.states |= HistoryItem.STATE_SCREEN_ON_FLAG;
4930 if (DEBUG_HISTORY) Slog.v(TAG, "Screen on to: "
4931 + Integer.toHexString(mHistoryCur.states));
Jeff Browne95c3cd2014-05-02 16:59:26 -07004932 mScreenOnTimer.startRunningLocked(elapsedRealtime);
4933 if (mScreenBrightnessBin >= 0) {
4934 mScreenBrightnessTimer[mScreenBrightnessBin].startRunningLocked(elapsedRealtime);
4935 }
Mike Mac2f518a2017-09-19 16:06:03 -07004936 updateHistory = true;
4937 } else if (isScreenOn(oldState)) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07004938 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_ON_FLAG;
4939 if (DEBUG_HISTORY) Slog.v(TAG, "Screen off to: "
4940 + Integer.toHexString(mHistoryCur.states));
Jeff Browne95c3cd2014-05-02 16:59:26 -07004941 mScreenOnTimer.stopRunningLocked(elapsedRealtime);
4942 if (mScreenBrightnessBin >= 0) {
4943 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
4944 }
Mike Mac2f518a2017-09-19 16:06:03 -07004945 updateHistory = true;
4946 }
4947 if (updateHistory) {
4948 if (DEBUG_HISTORY) Slog.v(TAG, "Screen state to: "
4949 + Display.stateToString(state));
4950 addHistoryRecordLocked(elapsedRealtime, uptime);
4951 }
Sudheer Shankac57729a2018-02-09 15:44:42 -08004952 mExternalSync.scheduleCpuSyncDueToScreenStateChange(
4953 mOnBatteryTimeBase.isRunning(), mOnBatteryScreenOffTimeBase.isRunning());
Mike Mac2f518a2017-09-19 16:06:03 -07004954 if (isScreenOn(state)) {
4955 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), state,
4956 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
4957 // Fake a wake lock, so we consider the device waked as long as the screen is on.
Narayan Kamath81822022017-12-08 11:56:01 +00004958 noteStartWakeLocked(-1, -1, null, "screen", null, WAKE_TYPE_PARTIAL, false,
Mike Mac2f518a2017-09-19 16:06:03 -07004959 elapsedRealtime, uptime);
4960 } else if (isScreenOn(oldState)) {
Narayan Kamath81822022017-12-08 11:56:01 +00004961 noteStopWakeLocked(-1, -1, null, "screen", "screen", WAKE_TYPE_PARTIAL,
Jeff Browne95c3cd2014-05-02 16:59:26 -07004962 elapsedRealtime, uptime);
Mike Mac2f518a2017-09-19 16:06:03 -07004963 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), state,
Joe Onoratoabded112016-02-08 16:49:39 -08004964 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
Mike Mac2f518a2017-09-19 16:06:03 -07004965 }
4966 // Update discharge amounts.
4967 if (mOnBatteryInternal) {
4968 updateDischargeScreenLevelsLocked(oldState, state);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08004969 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07004970 }
4971 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004972
Dianne Hackborn617f8772009-03-31 15:04:46 -07004973 public void noteScreenBrightnessLocked(int brightness) {
4974 // Bin the brightness.
4975 int bin = brightness / (256/NUM_SCREEN_BRIGHTNESS_BINS);
4976 if (bin < 0) bin = 0;
4977 else if (bin >= NUM_SCREEN_BRIGHTNESS_BINS) bin = NUM_SCREEN_BRIGHTNESS_BINS-1;
4978 if (mScreenBrightnessBin != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08004979 final long elapsedRealtime = mClocks.elapsedRealtime();
4980 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004981 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_BRIGHTNESS_MASK)
4982 | (bin << HistoryItem.STATE_BRIGHTNESS_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004983 if (DEBUG_HISTORY) Slog.v(TAG, "Screen brightness " + bin + " to: "
4984 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004985 addHistoryRecordLocked(elapsedRealtime, uptime);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004986 if (mScreenState == Display.STATE_ON) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07004987 if (mScreenBrightnessBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004988 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07004989 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004990 mScreenBrightnessTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07004991 }
4992 mScreenBrightnessBin = bin;
4993 }
4994 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004995
Dianne Hackborn617f8772009-03-31 15:04:46 -07004996 public void noteUserActivityLocked(int uid, int event) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08004997 if (mOnBatteryInternal) {
4998 uid = mapUid(uid);
4999 getUidStatsLocked(uid).noteUserActivityLocked(event);
5000 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005001 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005002
Dianne Hackborn280a64e2015-07-13 14:48:08 -07005003 public void noteWakeUpLocked(String reason, int reasonUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005004 final long elapsedRealtime = mClocks.elapsedRealtime();
5005 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn280a64e2015-07-13 14:48:08 -07005006 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SCREEN_WAKE_UP,
5007 reason, reasonUid);
5008 }
5009
Jeff Browne95c3cd2014-05-02 16:59:26 -07005010 public void noteInteractiveLocked(boolean interactive) {
5011 if (mInteractive != interactive) {
Joe Onoratoabded112016-02-08 16:49:39 -08005012 final long elapsedRealtime = mClocks.elapsedRealtime();
Jeff Browne95c3cd2014-05-02 16:59:26 -07005013 mInteractive = interactive;
5014 if (DEBUG) Slog.v(TAG, "Interactive: " + interactive);
5015 if (interactive) {
5016 mInteractiveTimer.startRunningLocked(elapsedRealtime);
5017 } else {
5018 mInteractiveTimer.stopRunningLocked(elapsedRealtime);
5019 }
5020 }
5021 }
5022
Dianne Hackborn1e01d162014-12-04 17:46:42 -08005023 public void noteConnectivityChangedLocked(int type, String extra) {
Joe Onoratoabded112016-02-08 16:49:39 -08005024 final long elapsedRealtime = mClocks.elapsedRealtime();
5025 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08005026 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_CONNECTIVITY_CHANGED,
5027 extra, type);
5028 mNumConnectivityChange++;
5029 }
5030
Adam Lesinski5f056f62016-07-14 16:56:08 -07005031 private void noteMobileRadioApWakeupLocked(final long elapsedRealtimeMillis,
5032 final long uptimeMillis, int uid) {
5033 uid = mapUid(uid);
5034 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
5035 uid);
5036 getUidStatsLocked(uid).noteMobileRadioApWakeupLocked();
5037 }
5038
Adam Lesinski14ae39a2017-05-26 11:50:40 -07005039 /**
5040 * Updates the radio power state and returns true if an external stats collection should occur.
5041 */
5042 public boolean noteMobileRadioPowerStateLocked(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005043 final long elapsedRealtime = mClocks.elapsedRealtime();
5044 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005045 if (mMobileRadioPowerState != powerState) {
5046 long realElapsedRealtimeMs;
5047 final boolean active =
5048 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
5049 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
5050 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07005051 if (uid > 0) {
5052 noteMobileRadioApWakeupLocked(elapsedRealtime, uptime, uid);
5053 }
5054
Adam Lesinski9acfd812016-04-19 18:29:50 -07005055 mMobileRadioActiveStartTime = realElapsedRealtimeMs = timestampNs / (1000 * 1000);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005056 mHistoryCur.states |= HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
5057 } else {
5058 realElapsedRealtimeMs = timestampNs / (1000*1000);
Dianne Hackbornf7097a52014-05-13 09:56:14 -07005059 long lastUpdateTimeMs = mMobileRadioActiveStartTime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005060 if (realElapsedRealtimeMs < lastUpdateTimeMs) {
5061 Slog.wtf(TAG, "Data connection inactive timestamp " + realElapsedRealtimeMs
5062 + " is before start time " + lastUpdateTimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005063 realElapsedRealtimeMs = elapsedRealtime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005064 } else if (realElapsedRealtimeMs < elapsedRealtime) {
5065 mMobileRadioActiveAdjustedTime.addCountLocked(elapsedRealtime
5066 - realElapsedRealtimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005067 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005068 mHistoryCur.states &= ~HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
5069 }
5070 if (DEBUG_HISTORY) Slog.v(TAG, "Mobile network active " + active + " to: "
5071 + Integer.toHexString(mHistoryCur.states));
5072 addHistoryRecordLocked(elapsedRealtime, uptime);
5073 mMobileRadioPowerState = powerState;
Bookatzddccf0a2017-11-28 16:48:14 -08005074 StatsLog.write(StatsLog.MOBILE_RADIO_POWER_STATE_CHANGED, uid, powerState);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005075 if (active) {
5076 mMobileRadioActiveTimer.startRunningLocked(elapsedRealtime);
5077 mMobileRadioActivePerAppTimer.startRunningLocked(elapsedRealtime);
5078 } else {
5079 mMobileRadioActiveTimer.stopRunningLocked(realElapsedRealtimeMs);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005080 mMobileRadioActivePerAppTimer.stopRunningLocked(realElapsedRealtimeMs);
Adam Lesinski14ae39a2017-05-26 11:50:40 -07005081 // Tell the caller to collect radio network/power stats.
5082 return true;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08005083 }
Dianne Hackborne13c4c02014-02-11 17:18:35 -08005084 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -07005085 return false;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08005086 }
5087
Adam Lesinski14ae39a2017-05-26 11:50:40 -07005088 public void notePowerSaveModeLocked(boolean enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005089 if (mPowerSaveModeEnabled != enabled) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07005090 int stepState = enabled ? STEP_LEVEL_MODE_POWER_SAVE : 0;
5091 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_POWER_SAVE) ^ stepState;
5092 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_POWER_SAVE) | stepState;
Joe Onoratoabded112016-02-08 16:49:39 -08005093 final long elapsedRealtime = mClocks.elapsedRealtime();
5094 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005095 mPowerSaveModeEnabled = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005096 if (enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005097 mHistoryCur.states2 |= HistoryItem.STATE2_POWER_SAVE_FLAG;
5098 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode enabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005099 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005100 mPowerSaveModeEnabledTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005101 } else {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005102 mHistoryCur.states2 &= ~HistoryItem.STATE2_POWER_SAVE_FLAG;
5103 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode disabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005104 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005105 mPowerSaveModeEnabledTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005106 }
5107 addHistoryRecordLocked(elapsedRealtime, uptime);
Bookatz90867622018-01-31 15:05:57 -08005108 StatsLog.write(StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED, enabled ?
5109 StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED__STATE__ON :
5110 StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED__STATE__OFF);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005111 }
5112 }
5113
Bookatzddccf0a2017-11-28 16:48:14 -08005114 public void noteDeviceIdleModeLocked(final int mode, String activeReason, int activeUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005115 final long elapsedRealtime = mClocks.elapsedRealtime();
5116 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005117 boolean nowIdling = mode == DEVICE_IDLE_MODE_DEEP;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005118 if (mDeviceIdling && !nowIdling && activeReason == null) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005119 // We don't go out of general idling mode until explicitly taken out of
5120 // device idle through going active or significant motion.
5121 nowIdling = true;
5122 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005123 boolean nowLightIdling = mode == DEVICE_IDLE_MODE_LIGHT;
5124 if (mDeviceLightIdling && !nowLightIdling && !nowIdling && activeReason == null) {
5125 // We don't go out of general light idling mode until explicitly taken out of
5126 // device idle through going active or significant motion.
5127 nowLightIdling = true;
5128 }
5129 if (activeReason != null && (mDeviceIdling || mDeviceLightIdling)) {
5130 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_ACTIVE,
5131 activeReason, activeUid);
5132 }
Bookatzddccf0a2017-11-28 16:48:14 -08005133 if (mDeviceIdling != nowIdling || mDeviceLightIdling != nowLightIdling) {
5134 int statsmode;
5135 if (nowIdling) statsmode = DEVICE_IDLE_MODE_DEEP;
5136 else if (nowLightIdling) statsmode = DEVICE_IDLE_MODE_LIGHT;
5137 else statsmode = DEVICE_IDLE_MODE_OFF;
5138 StatsLog.write(StatsLog.DEVICE_IDLING_MODE_STATE_CHANGED, statsmode);
5139 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005140 if (mDeviceIdling != nowIdling) {
5141 mDeviceIdling = nowIdling;
5142 int stepState = nowIdling ? STEP_LEVEL_MODE_DEVICE_IDLE : 0;
5143 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_DEVICE_IDLE) ^ stepState;
5144 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_DEVICE_IDLE) | stepState;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005145 if (nowIdling) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005146 mDeviceIdlingTimer.startRunningLocked(elapsedRealtime);
5147 } else {
5148 mDeviceIdlingTimer.stopRunningLocked(elapsedRealtime);
5149 }
5150 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005151 if (mDeviceLightIdling != nowLightIdling) {
5152 mDeviceLightIdling = nowLightIdling;
5153 if (nowLightIdling) {
5154 mDeviceLightIdlingTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005155 } else {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005156 mDeviceLightIdlingTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005157 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005158 }
5159 if (mDeviceIdleMode != mode) {
5160 mHistoryCur.states2 = (mHistoryCur.states2 & ~HistoryItem.STATE2_DEVICE_IDLE_MASK)
5161 | (mode << HistoryItem.STATE2_DEVICE_IDLE_SHIFT);
5162 if (DEBUG_HISTORY) Slog.v(TAG, "Device idle mode changed to: "
5163 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005164 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005165 long lastDuration = elapsedRealtime - mLastIdleTimeStart;
5166 mLastIdleTimeStart = elapsedRealtime;
5167 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
5168 if (lastDuration > mLongestLightIdleTime) {
5169 mLongestLightIdleTime = lastDuration;
5170 }
5171 mDeviceIdleModeLightTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005172 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005173 if (lastDuration > mLongestFullIdleTime) {
5174 mLongestFullIdleTime = lastDuration;
5175 }
5176 mDeviceIdleModeFullTimer.stopRunningLocked(elapsedRealtime);
5177 }
5178 if (mode == DEVICE_IDLE_MODE_LIGHT) {
5179 mDeviceIdleModeLightTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005180 } else if (mode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005181 mDeviceIdleModeFullTimer.startRunningLocked(elapsedRealtime);
5182 }
5183 mDeviceIdleMode = mode;
Bookatzddccf0a2017-11-28 16:48:14 -08005184 StatsLog.write(StatsLog.DEVICE_IDLE_MODE_STATE_CHANGED, mode);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005185 }
5186 }
5187
Dianne Hackborn3accca02013-09-20 09:32:11 -07005188 public void notePackageInstalledLocked(String pkgName, long versionCode) {
Joe Onoratoabded112016-02-08 16:49:39 -08005189 final long elapsedRealtime = mClocks.elapsedRealtime();
5190 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3accca02013-09-20 09:32:11 -07005191 // XXX need to figure out what to do with long version codes.
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005192 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_INSTALLED,
Dianne Hackborn3accca02013-09-20 09:32:11 -07005193 pkgName, (int)versionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005194 PackageChange pc = new PackageChange();
5195 pc.mPackageName = pkgName;
5196 pc.mUpdate = true;
5197 pc.mVersionCode = versionCode;
5198 addPackageChange(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005199 }
5200
5201 public void notePackageUninstalledLocked(String pkgName) {
Joe Onoratoabded112016-02-08 16:49:39 -08005202 final long elapsedRealtime = mClocks.elapsedRealtime();
5203 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005204 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_UNINSTALLED,
5205 pkgName, 0);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005206 PackageChange pc = new PackageChange();
5207 pc.mPackageName = pkgName;
5208 pc.mUpdate = true;
5209 addPackageChange(pc);
5210 }
5211
5212 private void addPackageChange(PackageChange pc) {
5213 if (mDailyPackageChanges == null) {
5214 mDailyPackageChanges = new ArrayList<>();
5215 }
5216 mDailyPackageChanges.add(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005217 }
5218
Siddharth Ray78ccaf52017-12-23 16:16:21 -08005219 void stopAllGpsSignalQualityTimersLocked(int except) {
5220 final long elapsedRealtime = mClocks.elapsedRealtime();
5221 for (int i = 0; i < GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
5222 if (i == except) {
5223 continue;
5224 }
5225 while (mGpsSignalQualityTimer[i].isRunningLocked()) {
5226 mGpsSignalQualityTimer[i].stopRunningLocked(elapsedRealtime);
5227 }
5228 }
5229 }
5230
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005231 public void notePhoneOnLocked() {
5232 if (!mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005233 final long elapsedRealtime = mClocks.elapsedRealtime();
5234 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005235 mHistoryCur.states2 |= HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005236 if (DEBUG_HISTORY) Slog.v(TAG, "Phone on to: "
5237 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005238 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005239 mPhoneOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005240 mPhoneOnTimer.startRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005241 }
5242 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005244 public void notePhoneOffLocked() {
5245 if (mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005246 final long elapsedRealtime = mClocks.elapsedRealtime();
5247 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005248 mHistoryCur.states2 &= ~HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005249 if (DEBUG_HISTORY) Slog.v(TAG, "Phone off to: "
5250 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005251 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005252 mPhoneOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005253 mPhoneOnTimer.stopRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005254 }
5255 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07005256
Mike Mafbc01fc2018-04-02 10:28:28 -07005257 private void registerUsbStateReceiver(Context context) {
5258 final IntentFilter usbStateFilter = new IntentFilter();
5259 usbStateFilter.addAction(UsbManager.ACTION_USB_STATE);
5260 context.registerReceiver(new BroadcastReceiver() {
5261 @Override
5262 public void onReceive(Context context, Intent intent) {
5263 final boolean state = intent.getBooleanExtra(UsbManager.USB_CONNECTED, false);
5264 synchronized (BatteryStatsImpl.this) {
5265 noteUsbConnectionStateLocked(state);
5266 }
5267 }
5268 }, usbStateFilter);
5269 synchronized (this) {
5270 if (mUsbDataState == USB_DATA_UNKNOWN) {
5271 final Intent usbState = context.registerReceiver(null, usbStateFilter);
5272 final boolean initState = usbState != null && usbState.getBooleanExtra(
5273 UsbManager.USB_CONNECTED, false);
5274 noteUsbConnectionStateLocked(initState);
5275 }
5276 }
5277 }
5278
5279 private void noteUsbConnectionStateLocked(boolean connected) {
5280 int newState = connected ? USB_DATA_CONNECTED : USB_DATA_DISCONNECTED;
Mike Ma926a97c2018-03-25 02:32:35 -07005281 if (mUsbDataState != newState) {
5282 mUsbDataState = newState;
5283 if (connected) {
5284 mHistoryCur.states2 |= HistoryItem.STATE2_USB_DATA_LINK_FLAG;
5285 } else {
5286 mHistoryCur.states2 &= ~HistoryItem.STATE2_USB_DATA_LINK_FLAG;
5287 }
5288 addHistoryRecordLocked(mClocks.elapsedRealtime(), mClocks.uptimeMillis());
5289 }
5290 }
5291
Dianne Hackborn3251b902014-06-20 14:40:53 -07005292 void stopAllPhoneSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005293 final long elapsedRealtime = mClocks.elapsedRealtime();
Wink Saville52840902011-02-18 12:40:47 -08005294 for (int i = 0; i < SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005295 if (i == except) {
5296 continue;
5297 }
5298 while (mPhoneSignalStrengthsTimer[i].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005299 mPhoneSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005300 }
5301 }
5302 }
5303
Dianne Hackborne4a59512010-12-07 11:08:07 -08005304 private int fixPhoneServiceState(int state, int signalBin) {
5305 if (mPhoneSimStateRaw == TelephonyManager.SIM_STATE_ABSENT) {
5306 // In this case we will always be STATE_OUT_OF_SERVICE, so need
5307 // to infer that we are scanning from other data.
5308 if (state == ServiceState.STATE_OUT_OF_SERVICE
Wink Saville52840902011-02-18 12:40:47 -08005309 && signalBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005310 state = ServiceState.STATE_IN_SERVICE;
5311 }
5312 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005313
Dianne Hackborne4a59512010-12-07 11:08:07 -08005314 return state;
5315 }
5316
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005317 private void updateAllPhoneStateLocked(int state, int simState, int strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005318 boolean scanning = false;
5319 boolean newHistory = false;
5320
5321 mPhoneServiceStateRaw = state;
5322 mPhoneSimStateRaw = simState;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005323 mPhoneSignalStrengthBinRaw = strengthBin;
5324
Joe Onoratoabded112016-02-08 16:49:39 -08005325 final long elapsedRealtime = mClocks.elapsedRealtime();
5326 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne4a59512010-12-07 11:08:07 -08005327
5328 if (simState == TelephonyManager.SIM_STATE_ABSENT) {
5329 // In this case we will always be STATE_OUT_OF_SERVICE, so need
5330 // to infer that we are scanning from other data.
5331 if (state == ServiceState.STATE_OUT_OF_SERVICE
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005332 && strengthBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005333 state = ServiceState.STATE_IN_SERVICE;
5334 }
5335 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005336
5337 // If the phone is powered off, stop all timers.
5338 if (state == ServiceState.STATE_POWER_OFF) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005339 strengthBin = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -07005340
Dianne Hackborne4a59512010-12-07 11:08:07 -08005341 // If we are in service, make sure the correct signal string timer is running.
5342 } else if (state == ServiceState.STATE_IN_SERVICE) {
5343 // Bin will be changed below.
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005344
5345 // If we're out of service, we are in the lowest signal strength
5346 // bin and have the scanning bit set.
Amith Yamasanif37447b2009-10-08 18:28:01 -07005347 } else if (state == ServiceState.STATE_OUT_OF_SERVICE) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005348 scanning = true;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005349 strengthBin = SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN;
Amith Yamasanif37447b2009-10-08 18:28:01 -07005350 if (!mPhoneSignalScanningTimer.isRunningLocked()) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005351 mHistoryCur.states |= HistoryItem.STATE_PHONE_SCANNING_FLAG;
Dianne Hackborne4a59512010-12-07 11:08:07 -08005352 newHistory = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005353 if (DEBUG_HISTORY) Slog.v(TAG, "Phone started scanning to: "
5354 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005355 mPhoneSignalScanningTimer.startRunningLocked(elapsedRealtime);
Amith Yamasanif37447b2009-10-08 18:28:01 -07005356 }
5357 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005358
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005359 if (!scanning) {
5360 // If we are no longer scanning, then stop the scanning timer.
5361 if (mPhoneSignalScanningTimer.isRunningLocked()) {
5362 mHistoryCur.states &= ~HistoryItem.STATE_PHONE_SCANNING_FLAG;
5363 if (DEBUG_HISTORY) Slog.v(TAG, "Phone stopped scanning to: "
5364 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08005365 newHistory = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005366 mPhoneSignalScanningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005367 }
5368 }
5369
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005370 if (mPhoneServiceState != state) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005371 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_STATE_MASK)
5372 | (state << HistoryItem.STATE_PHONE_STATE_SHIFT);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005373 if (DEBUG_HISTORY) Slog.v(TAG, "Phone state " + state + " to: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005374 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08005375 newHistory = true;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005376 mPhoneServiceState = state;
5377 }
Dianne Hackborne4a59512010-12-07 11:08:07 -08005378
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005379 if (mPhoneSignalStrengthBin != strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005380 if (mPhoneSignalStrengthBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005381 mPhoneSignalStrengthsTimer[mPhoneSignalStrengthBin].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005382 elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005383 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005384 if (strengthBin >= 0) {
5385 if (!mPhoneSignalStrengthsTimer[strengthBin].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005386 mPhoneSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005387 }
Dianne Hackborn3251b902014-06-20 14:40:53 -07005388 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_MASK)
5389 | (strengthBin << HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_SHIFT);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005390 if (DEBUG_HISTORY) Slog.v(TAG, "Signal strength " + strengthBin + " to: "
Dianne Hackborne4a59512010-12-07 11:08:07 -08005391 + Integer.toHexString(mHistoryCur.states));
5392 newHistory = true;
Bookatze5885242017-10-24 20:10:31 -07005393 StatsLog.write(StatsLog.PHONE_SIGNAL_STRENGTH_CHANGED, strengthBin);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005394 } else {
Dianne Hackborn3251b902014-06-20 14:40:53 -07005395 stopAllPhoneSignalStrengthTimersLocked(-1);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005396 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005397 mPhoneSignalStrengthBin = strengthBin;
Dianne Hackborne4a59512010-12-07 11:08:07 -08005398 }
5399
5400 if (newHistory) {
Dianne Hackborn40c87252014-03-19 16:55:40 -07005401 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005402 }
5403 }
5404
5405 /**
5406 * Telephony stack updates the phone state.
5407 * @param state phone state from ServiceState.getState()
5408 */
5409 public void notePhoneStateLocked(int state, int simState) {
5410 updateAllPhoneStateLocked(state, simState, mPhoneSignalStrengthBinRaw);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07005411 }
5412
Wink Savillee9b06d72009-05-18 21:47:50 -07005413 public void notePhoneSignalStrengthLocked(SignalStrength signalStrength) {
Dianne Hackborn627bba72009-03-24 22:32:56 -07005414 // Bin the strength.
Wink Saville52840902011-02-18 12:40:47 -08005415 int bin = signalStrength.getLevel();
Dianne Hackborne4a59512010-12-07 11:08:07 -08005416 updateAllPhoneStateLocked(mPhoneServiceStateRaw, mPhoneSimStateRaw, bin);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005417 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005418
Dianne Hackborn627bba72009-03-24 22:32:56 -07005419 public void notePhoneDataConnectionStateLocked(int dataType, boolean hasData) {
Tej Singheee317b2018-03-07 19:28:05 -08005420 // BatteryStats uses 0 to represent no network type.
5421 // Telephony does not have a concept of no network type, and uses 0 to represent unknown.
5422 // Unknown is included in DATA_CONNECTION_OTHER.
Dianne Hackborn627bba72009-03-24 22:32:56 -07005423 int bin = DATA_CONNECTION_NONE;
5424 if (hasData) {
Tej Singheee317b2018-03-07 19:28:05 -08005425 if (dataType > 0 && dataType <= TelephonyManager.MAX_NETWORK_TYPE) {
5426 bin = dataType;
5427 } else {
5428 bin = DATA_CONNECTION_OTHER;
Dianne Hackborn627bba72009-03-24 22:32:56 -07005429 }
5430 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07005431 if (DEBUG) Log.i(TAG, "Phone Data Connection -> " + dataType + " = " + hasData);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005432 if (mPhoneDataConnectionType != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005433 final long elapsedRealtime = mClocks.elapsedRealtime();
5434 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005435 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_DATA_CONNECTION_MASK)
5436 | (bin << HistoryItem.STATE_DATA_CONNECTION_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005437 if (DEBUG_HISTORY) Slog.v(TAG, "Data connection " + bin + " to: "
5438 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005439 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005440 if (mPhoneDataConnectionType >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005441 mPhoneDataConnectionsTimer[mPhoneDataConnectionType].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005442 elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005443 }
5444 mPhoneDataConnectionType = bin;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005445 mPhoneDataConnectionsTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005446 }
5447 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005448
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005449 public void noteWifiOnLocked() {
The Android Open Source Project10592532009-03-18 17:39:46 -07005450 if (!mWifiOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005451 final long elapsedRealtime = mClocks.elapsedRealtime();
5452 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005453 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005454 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI on to: "
5455 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005456 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005457 mWifiOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005458 mWifiOnTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005459 scheduleSyncExternalStatsLocked("wifi-off", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07005460 }
5461 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005462
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005463 public void noteWifiOffLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08005464 final long elapsedRealtime = mClocks.elapsedRealtime();
5465 final long uptime = mClocks.uptimeMillis();
The Android Open Source Project10592532009-03-18 17:39:46 -07005466 if (mWifiOn) {
Dianne Hackborn3251b902014-06-20 14:40:53 -07005467 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005468 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI off to: "
5469 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005470 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005471 mWifiOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005472 mWifiOnTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005473 scheduleSyncExternalStatsLocked("wifi-on", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07005474 }
5475 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005476
5477 public void noteAudioOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005478 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005479 final long elapsedRealtime = mClocks.elapsedRealtime();
5480 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005481 if (mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005482 mHistoryCur.states |= HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005483 if (DEBUG_HISTORY) Slog.v(TAG, "Audio on to: "
5484 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005485 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005486 mAudioOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005487 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005488 mAudioOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005489 getUidStatsLocked(uid).noteAudioTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005490 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005491
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005492 public void noteAudioOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005493 if (mAudioOnNesting == 0) {
5494 return;
5495 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08005496 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005497 final long elapsedRealtime = mClocks.elapsedRealtime();
5498 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005499 if (--mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005500 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005501 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
5502 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005503 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005504 mAudioOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005505 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005506 getUidStatsLocked(uid).noteAudioTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005507 }
5508
5509 public void noteVideoOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005510 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005511 final long elapsedRealtime = mClocks.elapsedRealtime();
5512 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005513 if (mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005514 mHistoryCur.states2 |= HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005515 if (DEBUG_HISTORY) Slog.v(TAG, "Video on to: "
5516 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005517 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005518 mVideoOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005519 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005520 mVideoOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005521 getUidStatsLocked(uid).noteVideoTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005522 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005523
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005524 public void noteVideoOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005525 if (mVideoOnNesting == 0) {
5526 return;
5527 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08005528 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005529 final long elapsedRealtime = mClocks.elapsedRealtime();
5530 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005531 if (--mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005532 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005533 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
5534 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005535 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005536 mVideoOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005537 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005538 getUidStatsLocked(uid).noteVideoTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005539 }
5540
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005541 public void noteResetAudioLocked() {
5542 if (mAudioOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005543 final long elapsedRealtime = mClocks.elapsedRealtime();
5544 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005545 mAudioOnNesting = 0;
5546 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
5547 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
5548 + Integer.toHexString(mHistoryCur.states));
5549 addHistoryRecordLocked(elapsedRealtime, uptime);
5550 mAudioOnTimer.stopAllRunningLocked(elapsedRealtime);
5551 for (int i=0; i<mUidStats.size(); i++) {
5552 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5553 uid.noteResetAudioLocked(elapsedRealtime);
5554 }
5555 }
5556 }
5557
5558 public void noteResetVideoLocked() {
5559 if (mVideoOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005560 final long elapsedRealtime = mClocks.elapsedRealtime();
5561 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005562 mAudioOnNesting = 0;
5563 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
5564 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
5565 + Integer.toHexString(mHistoryCur.states));
5566 addHistoryRecordLocked(elapsedRealtime, uptime);
5567 mVideoOnTimer.stopAllRunningLocked(elapsedRealtime);
5568 for (int i=0; i<mUidStats.size(); i++) {
5569 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5570 uid.noteResetVideoLocked(elapsedRealtime);
5571 }
5572 }
5573 }
5574
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005575 public void noteActivityResumedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005576 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005577 getUidStatsLocked(uid).noteActivityResumedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005578 }
5579
5580 public void noteActivityPausedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005581 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005582 getUidStatsLocked(uid).noteActivityPausedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005583 }
5584
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005585 public void noteVibratorOnLocked(int uid, long durationMillis) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005586 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005587 getUidStatsLocked(uid).noteVibratorOnLocked(durationMillis);
5588 }
5589
5590 public void noteVibratorOffLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005591 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005592 getUidStatsLocked(uid).noteVibratorOffLocked();
5593 }
5594
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005595 public void noteFlashlightOnLocked(int uid) {
5596 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005597 final long elapsedRealtime = mClocks.elapsedRealtime();
5598 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005599 if (mFlashlightOnNesting++ == 0) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005600 mHistoryCur.states2 |= HistoryItem.STATE2_FLASHLIGHT_FLAG;
5601 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight on to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005602 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005603 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005604 mFlashlightOnTimer.startRunningLocked(elapsedRealtime);
5605 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005606 getUidStatsLocked(uid).noteFlashlightTurnedOnLocked(elapsedRealtime);
5607 }
5608
5609 public void noteFlashlightOffLocked(int uid) {
5610 if (mFlashlightOnNesting == 0) {
5611 return;
5612 }
5613 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005614 final long elapsedRealtime = mClocks.elapsedRealtime();
5615 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005616 if (--mFlashlightOnNesting == 0) {
5617 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
5618 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
5619 + Integer.toHexString(mHistoryCur.states2));
5620 addHistoryRecordLocked(elapsedRealtime, uptime);
5621 mFlashlightOnTimer.stopRunningLocked(elapsedRealtime);
5622 }
5623 getUidStatsLocked(uid).noteFlashlightTurnedOffLocked(elapsedRealtime);
5624 }
5625
5626 public void noteCameraOnLocked(int uid) {
5627 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005628 final long elapsedRealtime = mClocks.elapsedRealtime();
5629 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005630 if (mCameraOnNesting++ == 0) {
5631 mHistoryCur.states2 |= HistoryItem.STATE2_CAMERA_FLAG;
5632 if (DEBUG_HISTORY) Slog.v(TAG, "Camera on to: "
5633 + Integer.toHexString(mHistoryCur.states2));
5634 addHistoryRecordLocked(elapsedRealtime, uptime);
5635 mCameraOnTimer.startRunningLocked(elapsedRealtime);
5636 }
5637 getUidStatsLocked(uid).noteCameraTurnedOnLocked(elapsedRealtime);
5638 }
5639
5640 public void noteCameraOffLocked(int uid) {
5641 if (mCameraOnNesting == 0) {
5642 return;
5643 }
5644 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005645 final long elapsedRealtime = mClocks.elapsedRealtime();
5646 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005647 if (--mCameraOnNesting == 0) {
5648 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
5649 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
5650 + Integer.toHexString(mHistoryCur.states2));
5651 addHistoryRecordLocked(elapsedRealtime, uptime);
5652 mCameraOnTimer.stopRunningLocked(elapsedRealtime);
5653 }
5654 getUidStatsLocked(uid).noteCameraTurnedOffLocked(elapsedRealtime);
5655 }
5656
5657 public void noteResetCameraLocked() {
5658 if (mCameraOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005659 final long elapsedRealtime = mClocks.elapsedRealtime();
5660 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005661 mCameraOnNesting = 0;
5662 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
5663 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
5664 + Integer.toHexString(mHistoryCur.states2));
5665 addHistoryRecordLocked(elapsedRealtime, uptime);
5666 mCameraOnTimer.stopAllRunningLocked(elapsedRealtime);
5667 for (int i=0; i<mUidStats.size(); i++) {
5668 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5669 uid.noteResetCameraLocked(elapsedRealtime);
5670 }
5671 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005672 }
5673
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005674 public void noteResetFlashlightLocked() {
5675 if (mFlashlightOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005676 final long elapsedRealtime = mClocks.elapsedRealtime();
5677 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005678 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005679 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
5680 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005681 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005682 addHistoryRecordLocked(elapsedRealtime, uptime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005683 mFlashlightOnTimer.stopAllRunningLocked(elapsedRealtime);
5684 for (int i=0; i<mUidStats.size(); i++) {
5685 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5686 uid.noteResetFlashlightLocked(elapsedRealtime);
5687 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005688 }
5689 }
5690
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005691 private void noteBluetoothScanStartedLocked(WorkChain workChain, int uid,
5692 boolean isUnoptimized) {
5693 uid = getAttributionUid(uid, workChain);
Bookatz867c0d72017-03-07 18:23:42 -08005694 final long elapsedRealtime = mClocks.elapsedRealtime();
5695 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005696 if (mBluetoothScanNesting == 0) {
5697 mHistoryCur.states2 |= HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5698 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan started for: "
5699 + Integer.toHexString(mHistoryCur.states2));
5700 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005701 mBluetoothScanTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005702 }
5703 mBluetoothScanNesting++;
Bookatzb1f04f32017-05-19 13:57:32 -07005704 getUidStatsLocked(uid).noteBluetoothScanStartedLocked(elapsedRealtime, isUnoptimized);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005705 }
5706
Bookatzb1f04f32017-05-19 13:57:32 -07005707 public void noteBluetoothScanStartedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005708 final int N = ws.size();
5709 for (int i = 0; i < N; i++) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005710 noteBluetoothScanStartedLocked(null, ws.get(i), isUnoptimized);
5711 }
5712
5713 final List<WorkChain> workChains = ws.getWorkChains();
5714 if (workChains != null) {
5715 for (int i = 0; i < workChains.size(); ++i) {
5716 noteBluetoothScanStartedLocked(workChains.get(i), -1, isUnoptimized);
5717 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005718 }
5719 }
5720
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005721 private void noteBluetoothScanStoppedLocked(WorkChain workChain, int uid,
5722 boolean isUnoptimized) {
5723 uid = getAttributionUid(uid, workChain);
Bookatz867c0d72017-03-07 18:23:42 -08005724 final long elapsedRealtime = mClocks.elapsedRealtime();
5725 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005726 mBluetoothScanNesting--;
5727 if (mBluetoothScanNesting == 0) {
5728 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5729 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan stopped for: "
5730 + Integer.toHexString(mHistoryCur.states2));
5731 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005732 mBluetoothScanTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005733 }
Bookatz94c5a312017-07-11 16:49:17 -07005734 getUidStatsLocked(uid).noteBluetoothScanStoppedLocked(elapsedRealtime, isUnoptimized);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005735 }
5736
5737 private int getAttributionUid(int uid, WorkChain workChain) {
5738 if (workChain != null) {
5739 return mapUid(workChain.getAttributionUid());
5740 }
5741
5742 return mapUid(uid);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005743 }
5744
Bookatz94c5a312017-07-11 16:49:17 -07005745 public void noteBluetoothScanStoppedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005746 final int N = ws.size();
5747 for (int i = 0; i < N; i++) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005748 noteBluetoothScanStoppedLocked(null, ws.get(i), isUnoptimized);
5749 }
5750
5751 final List<WorkChain> workChains = ws.getWorkChains();
5752 if (workChains != null) {
5753 for (int i = 0; i < workChains.size(); ++i) {
5754 noteBluetoothScanStoppedLocked(workChains.get(i), -1, isUnoptimized);
5755 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005756 }
5757 }
5758
5759 public void noteResetBluetoothScanLocked() {
5760 if (mBluetoothScanNesting > 0) {
Bookatz867c0d72017-03-07 18:23:42 -08005761 final long elapsedRealtime = mClocks.elapsedRealtime();
5762 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005763 mBluetoothScanNesting = 0;
5764 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5765 if (DEBUG_HISTORY) Slog.v(TAG, "BLE can stopped for: "
5766 + Integer.toHexString(mHistoryCur.states2));
5767 addHistoryRecordLocked(elapsedRealtime, uptime);
5768 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtime);
5769 for (int i=0; i<mUidStats.size(); i++) {
5770 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5771 uid.noteResetBluetoothScanLocked(elapsedRealtime);
5772 }
5773 }
5774 }
5775
Bookatz4ebc0642017-05-11 12:21:19 -07005776 public void noteBluetoothScanResultsFromSourceLocked(WorkSource ws, int numNewResults) {
Bookatz956f36bf2017-04-28 09:48:17 -07005777 final int N = ws.size();
5778 for (int i = 0; i < N; i++) {
5779 int uid = mapUid(ws.get(i));
Bookatz4ebc0642017-05-11 12:21:19 -07005780 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Yangster-mac2f5daec2018-01-16 10:23:15 -08005781 StatsLog.write_non_chained(StatsLog.BLE_SCAN_RESULT_RECEIVED, ws.get(i), ws.getName(i),
5782 numNewResults);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005783 }
5784
5785 final List<WorkChain> workChains = ws.getWorkChains();
5786 if (workChains != null) {
5787 for (int i = 0; i < workChains.size(); ++i) {
5788 final WorkChain wc = workChains.get(i);
5789 int uid = mapUid(wc.getAttributionUid());
5790 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Yangster-macafad8c62018-01-05 22:30:49 -08005791 StatsLog.write(StatsLog.BLE_SCAN_RESULT_RECEIVED,
5792 wc.getUids(), wc.getTags(), numNewResults);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005793 }
Bookatz956f36bf2017-04-28 09:48:17 -07005794 }
5795 }
5796
Adam Lesinski5f056f62016-07-14 16:56:08 -07005797 private void noteWifiRadioApWakeupLocked(final long elapsedRealtimeMillis,
5798 final long uptimeMillis, int uid) {
5799 uid = mapUid(uid);
5800 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
5801 uid);
5802 getUidStatsLocked(uid).noteWifiRadioApWakeupLocked();
5803 }
5804
5805 public void noteWifiRadioPowerState(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005806 final long elapsedRealtime = mClocks.elapsedRealtime();
5807 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005808 if (mWifiRadioPowerState != powerState) {
5809 final boolean active =
5810 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
5811 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
5812 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07005813 if (uid > 0) {
5814 noteWifiRadioApWakeupLocked(elapsedRealtime, uptime, uid);
5815 }
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005816 mHistoryCur.states |= HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
Siddharth Rayb50a6842017-12-14 15:15:28 -08005817 mWifiActiveTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005818 } else {
5819 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
Siddharth Rayb50a6842017-12-14 15:15:28 -08005820 mWifiActiveTimer.stopRunningLocked(
5821 timestampNs / (1000 * 1000));
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005822 }
5823 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi network active " + active + " to: "
5824 + Integer.toHexString(mHistoryCur.states));
5825 addHistoryRecordLocked(elapsedRealtime, uptime);
5826 mWifiRadioPowerState = powerState;
Bookatzddccf0a2017-11-28 16:48:14 -08005827 StatsLog.write(StatsLog.WIFI_RADIO_POWER_STATE_CHANGED, uid, powerState);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005828 }
5829 }
5830
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005831 public void noteWifiRunningLocked(WorkSource ws) {
5832 if (!mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005833 final long elapsedRealtime = mClocks.elapsedRealtime();
5834 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005835 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005836 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI running to: "
5837 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005838 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005839 mGlobalWifiRunning = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005840 mGlobalWifiRunningTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005841 int N = ws.size();
5842 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005843 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005844 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005845 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005846
5847 List<WorkChain> workChains = ws.getWorkChains();
5848 if (workChains != null) {
5849 for (int i = 0; i < workChains.size(); ++i) {
5850 int uid = mapUid(workChains.get(i).getAttributionUid());
5851 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
5852 }
5853 }
5854
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005855 scheduleSyncExternalStatsLocked("wifi-running", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005856 } else {
5857 Log.w(TAG, "noteWifiRunningLocked -- called while WIFI running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005858 }
5859 }
5860
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005861 public void noteWifiRunningChangedLocked(WorkSource oldWs, WorkSource newWs) {
5862 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005863 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005864 int N = oldWs.size();
5865 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005866 int uid = mapUid(oldWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005867 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005868 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005869
5870 List<WorkChain> workChains = oldWs.getWorkChains();
5871 if (workChains != null) {
5872 for (int i = 0; i < workChains.size(); ++i) {
5873 int uid = mapUid(workChains.get(i).getAttributionUid());
5874 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
5875 }
5876 }
5877
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005878 N = newWs.size();
5879 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005880 int uid = mapUid(newWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005881 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005882 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005883
5884 workChains = newWs.getWorkChains();
5885 if (workChains != null) {
5886 for (int i = 0; i < workChains.size(); ++i) {
5887 int uid = mapUid(workChains.get(i).getAttributionUid());
5888 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
5889 }
5890 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005891 } else {
5892 Log.w(TAG, "noteWifiRunningChangedLocked -- called while WIFI not running");
5893 }
5894 }
5895
5896 public void noteWifiStoppedLocked(WorkSource ws) {
5897 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005898 final long elapsedRealtime = mClocks.elapsedRealtime();
5899 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005900 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005901 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI stopped to: "
5902 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005903 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005904 mGlobalWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005905 mGlobalWifiRunningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005906 int N = ws.size();
5907 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005908 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005909 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005910 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005911
5912 List<WorkChain> workChains = ws.getWorkChains();
5913 if (workChains != null) {
5914 for (int i = 0; i < workChains.size(); ++i) {
5915 int uid = mapUid(workChains.get(i).getAttributionUid());
5916 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
5917 }
5918 }
5919
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005920 scheduleSyncExternalStatsLocked("wifi-stopped", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005921 } else {
5922 Log.w(TAG, "noteWifiStoppedLocked -- called while WIFI not running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005923 }
5924 }
5925
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005926 public void noteWifiStateLocked(int wifiState, String accessPoint) {
5927 if (DEBUG) Log.i(TAG, "WiFi state -> " + wifiState);
5928 if (mWifiState != wifiState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005929 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005930 if (mWifiState >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005931 mWifiStateTimer[mWifiState].stopRunningLocked(elapsedRealtime);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005932 }
5933 mWifiState = wifiState;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005934 mWifiStateTimer[wifiState].startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005935 scheduleSyncExternalStatsLocked("wifi-state", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005936 }
5937 }
5938
Dianne Hackborn3251b902014-06-20 14:40:53 -07005939 public void noteWifiSupplicantStateChangedLocked(int supplState, boolean failedAuth) {
5940 if (DEBUG) Log.i(TAG, "WiFi suppl state -> " + supplState);
5941 if (mWifiSupplState != supplState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005942 final long elapsedRealtime = mClocks.elapsedRealtime();
5943 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005944 if (mWifiSupplState >= 0) {
5945 mWifiSupplStateTimer[mWifiSupplState].stopRunningLocked(elapsedRealtime);
5946 }
5947 mWifiSupplState = supplState;
5948 mWifiSupplStateTimer[supplState].startRunningLocked(elapsedRealtime);
5949 mHistoryCur.states2 =
5950 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SUPPL_STATE_MASK)
5951 | (supplState << HistoryItem.STATE2_WIFI_SUPPL_STATE_SHIFT);
5952 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi suppl state " + supplState + " to: "
5953 + Integer.toHexString(mHistoryCur.states2));
5954 addHistoryRecordLocked(elapsedRealtime, uptime);
5955 }
5956 }
5957
5958 void stopAllWifiSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005959 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005960 for (int i = 0; i < NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
5961 if (i == except) {
5962 continue;
5963 }
5964 while (mWifiSignalStrengthsTimer[i].isRunningLocked()) {
5965 mWifiSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
5966 }
5967 }
5968 }
5969
5970 public void noteWifiRssiChangedLocked(int newRssi) {
5971 int strengthBin = WifiManager.calculateSignalLevel(newRssi, NUM_WIFI_SIGNAL_STRENGTH_BINS);
5972 if (DEBUG) Log.i(TAG, "WiFi rssi -> " + newRssi + " bin=" + strengthBin);
5973 if (mWifiSignalStrengthBin != strengthBin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005974 final long elapsedRealtime = mClocks.elapsedRealtime();
5975 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005976 if (mWifiSignalStrengthBin >= 0) {
5977 mWifiSignalStrengthsTimer[mWifiSignalStrengthBin].stopRunningLocked(
5978 elapsedRealtime);
5979 }
5980 if (strengthBin >= 0) {
5981 if (!mWifiSignalStrengthsTimer[strengthBin].isRunningLocked()) {
5982 mWifiSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
5983 }
5984 mHistoryCur.states2 =
5985 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_MASK)
5986 | (strengthBin << HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_SHIFT);
5987 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi signal strength " + strengthBin + " to: "
5988 + Integer.toHexString(mHistoryCur.states2));
5989 addHistoryRecordLocked(elapsedRealtime, uptime);
5990 } else {
5991 stopAllWifiSignalStrengthTimersLocked(-1);
5992 }
Bookatz235343d2018-03-26 13:03:50 -07005993 StatsLog.write(StatsLog.WIFI_SIGNAL_STRENGTH_CHANGED, strengthBin);
Dianne Hackborn3251b902014-06-20 14:40:53 -07005994 mWifiSignalStrengthBin = strengthBin;
5995 }
5996 }
5997
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005998 int mWifiFullLockNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005999
The Android Open Source Project10592532009-03-18 17:39:46 -07006000 public void noteFullWifiLockAcquiredLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006001 final long elapsedRealtime = mClocks.elapsedRealtime();
6002 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006003 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006004 mHistoryCur.states |= HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006005 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock on to: "
6006 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006007 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006008 }
6009 mWifiFullLockNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006010 getUidStatsLocked(uid).noteFullWifiLockAcquiredLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006011 }
6012
6013 public void noteFullWifiLockReleasedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006014 final long elapsedRealtime = mClocks.elapsedRealtime();
6015 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006016 mWifiFullLockNesting--;
6017 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006018 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006019 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock off to: "
6020 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006021 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006022 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006023 getUidStatsLocked(uid).noteFullWifiLockReleasedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006024 }
6025
Nick Pelly6ccaa542012-06-15 15:22:47 -07006026 int mWifiScanNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006027
Nick Pelly6ccaa542012-06-15 15:22:47 -07006028 public void noteWifiScanStartedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006029 final long elapsedRealtime = mClocks.elapsedRealtime();
6030 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07006031 if (mWifiScanNesting == 0) {
6032 mHistoryCur.states |= HistoryItem.STATE_WIFI_SCAN_FLAG;
6033 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan started for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006034 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006035 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006036 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07006037 mWifiScanNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006038 getUidStatsLocked(uid).noteWifiScanStartedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006039 }
6040
Nick Pelly6ccaa542012-06-15 15:22:47 -07006041 public void noteWifiScanStoppedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006042 final long elapsedRealtime = mClocks.elapsedRealtime();
6043 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07006044 mWifiScanNesting--;
6045 if (mWifiScanNesting == 0) {
6046 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_SCAN_FLAG;
6047 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan stopped for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006048 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006049 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006050 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006051 getUidStatsLocked(uid).noteWifiScanStoppedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006052 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006053
Robert Greenwalta029ea12013-09-25 16:38:12 -07006054 public void noteWifiBatchedScanStartedLocked(int uid, int csph) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006055 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006056 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006057 getUidStatsLocked(uid).noteWifiBatchedScanStartedLocked(csph, elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006058 }
6059
6060 public void noteWifiBatchedScanStoppedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006061 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006062 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006063 getUidStatsLocked(uid).noteWifiBatchedScanStoppedLocked(elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006064 }
6065
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006066 int mWifiMulticastNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006067
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006068 public void noteWifiMulticastEnabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006069 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006070 final long elapsedRealtime = mClocks.elapsedRealtime();
6071 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006072 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006073 mHistoryCur.states |= HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006074 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast on to: "
6075 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006076 addHistoryRecordLocked(elapsedRealtime, uptime);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006077
6078 // Start Wifi Multicast overall timer
6079 if (!mWifiMulticastWakelockTimer.isRunningLocked()) {
6080 if (DEBUG_HISTORY) Slog.v(TAG, "WiFi Multicast Overall Timer Started");
6081 mWifiMulticastWakelockTimer.startRunningLocked(elapsedRealtime);
6082 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006083 }
6084 mWifiMulticastNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006085 getUidStatsLocked(uid).noteWifiMulticastEnabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006086 }
6087
6088 public void noteWifiMulticastDisabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006089 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006090 final long elapsedRealtime = mClocks.elapsedRealtime();
6091 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006092 mWifiMulticastNesting--;
6093 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006094 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006095 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast off to: "
6096 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006097 addHistoryRecordLocked(elapsedRealtime, uptime);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006098
6099 // Stop Wifi Multicast overall timer
6100 if (mWifiMulticastWakelockTimer.isRunningLocked()) {
6101 if (DEBUG_HISTORY) Slog.v(TAG, "Multicast Overall Timer Stopped");
6102 mWifiMulticastWakelockTimer.stopRunningLocked(elapsedRealtime);
6103 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006104 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006105 getUidStatsLocked(uid).noteWifiMulticastDisabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006106 }
6107
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006108 public void noteFullWifiLockAcquiredFromSourceLocked(WorkSource ws) {
6109 int N = ws.size();
6110 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006111 final int uid = mapUid(ws.get(i));
6112 noteFullWifiLockAcquiredLocked(uid);
Bookatz90867622018-01-31 15:05:57 -08006113 StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, ws.get(i), ws.getName(i),
6114 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006115 }
6116
6117 final List<WorkChain> workChains = ws.getWorkChains();
6118 if (workChains != null) {
6119 for (int i = 0; i < workChains.size(); ++i) {
6120 final WorkChain workChain = workChains.get(i);
6121 final int uid = mapUid(workChain.getAttributionUid());
6122 noteFullWifiLockAcquiredLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006123 StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006124 workChain.getUids(), workChain.getTags(),
6125 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006126 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006127 }
6128 }
6129
6130 public void noteFullWifiLockReleasedFromSourceLocked(WorkSource ws) {
6131 int N = ws.size();
6132 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006133 final int uid = mapUid(ws.get(i));
6134 noteFullWifiLockReleasedLocked(uid);
Bookatz90867622018-01-31 15:05:57 -08006135 StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, ws.get(i), ws.getName(i),
6136 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006137 }
6138
6139 final List<WorkChain> workChains = ws.getWorkChains();
6140 if (workChains != null) {
6141 for (int i = 0; i < workChains.size(); ++i) {
6142 final WorkChain workChain = workChains.get(i);
6143 final int uid = mapUid(workChain.getAttributionUid());
6144 noteFullWifiLockReleasedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006145 StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006146 workChain.getUids(), workChain.getTags(),
6147 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006148 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006149 }
6150 }
6151
Nick Pelly6ccaa542012-06-15 15:22:47 -07006152 public void noteWifiScanStartedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006153 int N = ws.size();
6154 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006155 final int uid = mapUid(ws.get(i));
6156 noteWifiScanStartedLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08006157 StatsLog.write_non_chained(StatsLog.WIFI_SCAN_STATE_CHANGED, ws.get(i), ws.getName(i),
Bookatz90867622018-01-31 15:05:57 -08006158 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006159 }
6160
6161 final List<WorkChain> workChains = ws.getWorkChains();
6162 if (workChains != null) {
6163 for (int i = 0; i < workChains.size(); ++i) {
6164 final WorkChain workChain = workChains.get(i);
6165 final int uid = mapUid(workChain.getAttributionUid());
6166 noteWifiScanStartedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006167 StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED, workChain.getUids(),
Bookatz90867622018-01-31 15:05:57 -08006168 workChain.getTags(), StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006169 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006170 }
6171 }
6172
Nick Pelly6ccaa542012-06-15 15:22:47 -07006173 public void noteWifiScanStoppedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006174 int N = ws.size();
6175 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006176 final int uid = mapUid(ws.get(i));
6177 noteWifiScanStoppedLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08006178 StatsLog.write_non_chained(StatsLog.WIFI_SCAN_STATE_CHANGED, ws.get(i), ws.getName(i),
Bookatz90867622018-01-31 15:05:57 -08006179 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006180 }
6181
6182 final List<WorkChain> workChains = ws.getWorkChains();
6183 if (workChains != null) {
6184 for (int i = 0; i < workChains.size(); ++i) {
6185 final WorkChain workChain = workChains.get(i);
6186 final int uid = mapUid(workChain.getAttributionUid());
6187 noteWifiScanStoppedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006188 StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006189 workChain.getUids(), workChain.getTags(),
6190 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006191 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006192 }
6193 }
6194
Robert Greenwalta029ea12013-09-25 16:38:12 -07006195 public void noteWifiBatchedScanStartedFromSourceLocked(WorkSource ws, int csph) {
6196 int N = ws.size();
6197 for (int i=0; i<N; i++) {
6198 noteWifiBatchedScanStartedLocked(ws.get(i), csph);
6199 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00006200
6201 final List<WorkChain> workChains = ws.getWorkChains();
6202 if (workChains != null) {
6203 for (int i = 0; i < workChains.size(); ++i) {
6204 noteWifiBatchedScanStartedLocked(workChains.get(i).getAttributionUid(), csph);
6205 }
6206 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006207 }
6208
6209 public void noteWifiBatchedScanStoppedFromSourceLocked(WorkSource ws) {
6210 int N = ws.size();
6211 for (int i=0; i<N; i++) {
6212 noteWifiBatchedScanStoppedLocked(ws.get(i));
6213 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00006214
6215 final List<WorkChain> workChains = ws.getWorkChains();
6216 if (workChains != null) {
6217 for (int i = 0; i < workChains.size(); ++i) {
6218 noteWifiBatchedScanStoppedLocked(workChains.get(i).getAttributionUid());
6219 }
6220 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006221 }
6222
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08006223 private static String[] includeInStringArray(String[] array, String str) {
6224 if (ArrayUtils.indexOf(array, str) >= 0) {
6225 return array;
6226 }
6227 String[] newArray = new String[array.length+1];
6228 System.arraycopy(array, 0, newArray, 0, array.length);
6229 newArray[array.length] = str;
6230 return newArray;
6231 }
6232
6233 private static String[] excludeFromStringArray(String[] array, String str) {
6234 int index = ArrayUtils.indexOf(array, str);
6235 if (index >= 0) {
6236 String[] newArray = new String[array.length-1];
6237 if (index > 0) {
6238 System.arraycopy(array, 0, newArray, 0, index);
6239 }
6240 if (index < array.length-1) {
6241 System.arraycopy(array, index+1, newArray, index, array.length-index-1);
6242 }
6243 return newArray;
6244 }
6245 return array;
6246 }
6247
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07006248 public void noteNetworkInterfaceTypeLocked(String iface, int networkType) {
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07006249 if (TextUtils.isEmpty(iface)) return;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006250
Adam Lesinski14ae39a2017-05-26 11:50:40 -07006251 synchronized (mModemNetworkLock) {
6252 if (ConnectivityManager.isNetworkTypeMobile(networkType)) {
6253 mModemIfaces = includeInStringArray(mModemIfaces, iface);
6254 if (DEBUG) Slog.d(TAG, "Note mobile iface " + iface + ": " + mModemIfaces);
6255 } else {
6256 mModemIfaces = excludeFromStringArray(mModemIfaces, iface);
6257 if (DEBUG) Slog.d(TAG, "Note non-mobile iface " + iface + ": " + mModemIfaces);
6258 }
6259 }
6260
6261 synchronized (mWifiNetworkLock) {
6262 if (ConnectivityManager.isNetworkTypeWifi(networkType)) {
6263 mWifiIfaces = includeInStringArray(mWifiIfaces, iface);
6264 if (DEBUG) Slog.d(TAG, "Note wifi iface " + iface + ": " + mWifiIfaces);
6265 } else {
6266 mWifiIfaces = excludeFromStringArray(mWifiIfaces, iface);
6267 if (DEBUG) Slog.d(TAG, "Note non-wifi iface " + iface + ": " + mWifiIfaces);
6268 }
6269 }
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07006270 }
6271
David Chenc8a43242017-10-17 16:23:28 -07006272 public String[] getWifiIfaces() {
6273 synchronized (mWifiNetworkLock) {
6274 return mWifiIfaces;
6275 }
6276 }
6277
6278 public String[] getMobileIfaces() {
6279 synchronized (mModemNetworkLock) {
6280 return mModemIfaces;
6281 }
6282 }
6283
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006284 @Override public long getScreenOnTime(long elapsedRealtimeUs, int which) {
6285 return mScreenOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006286 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006287
Dianne Hackborn77b987f2014-02-26 16:20:52 -08006288 @Override public int getScreenOnCount(int which) {
6289 return mScreenOnTimer.getCountLocked(which);
6290 }
6291
Mike Mac2f518a2017-09-19 16:06:03 -07006292 @Override public long getScreenDozeTime(long elapsedRealtimeUs, int which) {
6293 return mScreenDozeTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6294 }
6295
6296 @Override public int getScreenDozeCount(int which) {
6297 return mScreenDozeTimer.getCountLocked(which);
6298 }
6299
Dianne Hackborn617f8772009-03-31 15:04:46 -07006300 @Override public long getScreenBrightnessTime(int brightnessBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006301 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006302 return mScreenBrightnessTimer[brightnessBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006303 elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006304 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006305
Kweku Adams87b19ec2017-10-09 12:40:03 -07006306 @Override public Timer getScreenBrightnessTimer(int brightnessBin) {
6307 return mScreenBrightnessTimer[brightnessBin];
6308 }
6309
Jeff Browne95c3cd2014-05-02 16:59:26 -07006310 @Override public long getInteractiveTime(long elapsedRealtimeUs, int which) {
6311 return mInteractiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006312 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006313
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006314 @Override public long getPowerSaveModeEnabledTime(long elapsedRealtimeUs, int which) {
6315 return mPowerSaveModeEnabledTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07006316 }
6317
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006318 @Override public int getPowerSaveModeEnabledCount(int which) {
6319 return mPowerSaveModeEnabledTimer.getCountLocked(which);
6320 }
6321
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006322 @Override public long getDeviceIdleModeTime(int mode, long elapsedRealtimeUs,
6323 int which) {
6324 switch (mode) {
6325 case DEVICE_IDLE_MODE_LIGHT:
6326 return mDeviceIdleModeLightTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006327 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006328 return mDeviceIdleModeFullTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6329 }
6330 return 0;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006331 }
6332
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006333 @Override public int getDeviceIdleModeCount(int mode, int which) {
6334 switch (mode) {
6335 case DEVICE_IDLE_MODE_LIGHT:
6336 return mDeviceIdleModeLightTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006337 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006338 return mDeviceIdleModeFullTimer.getCountLocked(which);
6339 }
6340 return 0;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07006341 }
6342
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006343 @Override public long getLongestDeviceIdleModeTime(int mode) {
6344 switch (mode) {
6345 case DEVICE_IDLE_MODE_LIGHT:
6346 return mLongestLightIdleTime;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006347 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006348 return mLongestFullIdleTime;
6349 }
6350 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07006351 }
6352
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006353 @Override public long getDeviceIdlingTime(int mode, long elapsedRealtimeUs, int which) {
6354 switch (mode) {
6355 case DEVICE_IDLE_MODE_LIGHT:
6356 return mDeviceLightIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006357 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006358 return mDeviceIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6359 }
6360 return 0;
6361 }
6362
6363 @Override public int getDeviceIdlingCount(int mode, int which) {
6364 switch (mode) {
6365 case DEVICE_IDLE_MODE_LIGHT:
6366 return mDeviceLightIdlingTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006367 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006368 return mDeviceIdlingTimer.getCountLocked(which);
6369 }
6370 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07006371 }
6372
Dianne Hackborn1e01d162014-12-04 17:46:42 -08006373 @Override public int getNumConnectivityChange(int which) {
6374 int val = mNumConnectivityChange;
6375 if (which == STATS_CURRENT) {
6376 val -= mLoadedNumConnectivityChange;
6377 } else if (which == STATS_SINCE_UNPLUGGED) {
6378 val -= mUnpluggedNumConnectivityChange;
6379 }
6380 return val;
6381 }
6382
Siddharth Ray78ccaf52017-12-23 16:16:21 -08006383 @Override public long getGpsSignalQualityTime(int strengthBin,
6384 long elapsedRealtimeUs, int which) {
6385 if (strengthBin < 0 || strengthBin >= GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS) {
6386 return 0;
6387 }
6388 return mGpsSignalQualityTimer[strengthBin].getTotalTimeLocked(
6389 elapsedRealtimeUs, which);
6390 }
6391
6392 @Override public long getGpsBatteryDrainMaMs() {
Siddharth Ray0ed2e952018-01-22 11:32:14 -08006393 final double opVolt = mPowerProfile.getAveragePower(
6394 PowerProfile.POWER_GPS_OPERATING_VOLTAGE) / 1000.0;
6395 if (opVolt == 0) {
6396 return 0;
6397 }
6398 double energyUsedMaMs = 0.0;
6399 final int which = STATS_SINCE_CHARGED;
6400 final long rawRealtime = SystemClock.elapsedRealtime() * 1000;
6401 for(int i=0; i < GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
6402 energyUsedMaMs
6403 += mPowerProfile.getAveragePower(PowerProfile.POWER_GPS_SIGNAL_QUALITY_BASED, i)
6404 * (getGpsSignalQualityTime(i, rawRealtime, which) / 1000);
6405 }
6406 return (long) energyUsedMaMs;
Siddharth Ray78ccaf52017-12-23 16:16:21 -08006407 }
6408
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006409 @Override public long getPhoneOnTime(long elapsedRealtimeUs, int which) {
6410 return mPhoneOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006411 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006412
Dianne Hackborn77b987f2014-02-26 16:20:52 -08006413 @Override public int getPhoneOnCount(int which) {
6414 return mPhoneOnTimer.getCountLocked(which);
6415 }
6416
Dianne Hackborn627bba72009-03-24 22:32:56 -07006417 @Override public long getPhoneSignalStrengthTime(int strengthBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006418 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006419 return mPhoneSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006420 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07006421 }
Amith Yamasanif37447b2009-10-08 18:28:01 -07006422
6423 @Override public long getPhoneSignalScanningTime(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006424 long elapsedRealtimeUs, int which) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07006425 return mPhoneSignalScanningTimer.getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006426 elapsedRealtimeUs, which);
Amith Yamasanif37447b2009-10-08 18:28:01 -07006427 }
6428
Kweku Adams87b19ec2017-10-09 12:40:03 -07006429 @Override public Timer getPhoneSignalScanningTimer() {
6430 return mPhoneSignalScanningTimer;
6431 }
6432
Catherine Liufb900812012-07-17 14:12:56 -05006433 @Override public int getPhoneSignalStrengthCount(int strengthBin, int which) {
6434 return mPhoneSignalStrengthsTimer[strengthBin].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006435 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006436
Kweku Adams87b19ec2017-10-09 12:40:03 -07006437 @Override public Timer getPhoneSignalStrengthTimer(int strengthBin) {
6438 return mPhoneSignalStrengthsTimer[strengthBin];
6439 }
6440
Dianne Hackborn627bba72009-03-24 22:32:56 -07006441 @Override public long getPhoneDataConnectionTime(int dataType,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006442 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006443 return mPhoneDataConnectionsTimer[dataType].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006444 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07006445 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006446
Dianne Hackborn617f8772009-03-31 15:04:46 -07006447 @Override public int getPhoneDataConnectionCount(int dataType, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006448 return mPhoneDataConnectionsTimer[dataType].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006449 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006450
Kweku Adams87b19ec2017-10-09 12:40:03 -07006451 @Override public Timer getPhoneDataConnectionTimer(int dataType) {
6452 return mPhoneDataConnectionsTimer[dataType];
6453 }
6454
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006455 @Override public long getMobileRadioActiveTime(long elapsedRealtimeUs, int which) {
6456 return mMobileRadioActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborne13c4c02014-02-11 17:18:35 -08006457 }
6458
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006459 @Override public int getMobileRadioActiveCount(int which) {
6460 return mMobileRadioActiveTimer.getCountLocked(which);
6461 }
6462
Dianne Hackborna1bd7922014-03-21 11:07:11 -07006463 @Override public long getMobileRadioActiveAdjustedTime(int which) {
6464 return mMobileRadioActiveAdjustedTime.getCountLocked(which);
6465 }
6466
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006467 @Override public long getMobileRadioActiveUnknownTime(int which) {
6468 return mMobileRadioActiveUnknownTime.getCountLocked(which);
6469 }
6470
6471 @Override public int getMobileRadioActiveUnknownCount(int which) {
6472 return (int)mMobileRadioActiveUnknownCount.getCountLocked(which);
6473 }
6474
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006475 @Override public long getWifiMulticastWakelockTime(
6476 long elapsedRealtimeUs, int which) {
6477 return mWifiMulticastWakelockTimer.getTotalTimeLocked(
6478 elapsedRealtimeUs, which);
6479 }
6480
6481 @Override public int getWifiMulticastWakelockCount(int which) {
6482 return mWifiMulticastWakelockTimer.getCountLocked(which);
6483 }
6484
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006485 @Override public long getWifiOnTime(long elapsedRealtimeUs, int which) {
6486 return mWifiOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07006487 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006488
Siddharth Rayb50a6842017-12-14 15:15:28 -08006489 @Override public long getWifiActiveTime(long elapsedRealtimeUs, int which) {
6490 return mWifiActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6491 }
6492
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006493 @Override public long getGlobalWifiRunningTime(long elapsedRealtimeUs, int which) {
6494 return mGlobalWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07006495 }
6496
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006497 @Override public long getWifiStateTime(int wifiState,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006498 long elapsedRealtimeUs, int which) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006499 return mWifiStateTimer[wifiState].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006500 elapsedRealtimeUs, which);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006501 }
6502
6503 @Override public int getWifiStateCount(int wifiState, int which) {
6504 return mWifiStateTimer[wifiState].getCountLocked(which);
6505 }
6506
Kweku Adams87b19ec2017-10-09 12:40:03 -07006507 @Override public Timer getWifiStateTimer(int wifiState) {
6508 return mWifiStateTimer[wifiState];
6509 }
6510
Dianne Hackborn3251b902014-06-20 14:40:53 -07006511 @Override public long getWifiSupplStateTime(int state,
6512 long elapsedRealtimeUs, int which) {
6513 return mWifiSupplStateTimer[state].getTotalTimeLocked(
6514 elapsedRealtimeUs, which);
6515 }
6516
6517 @Override public int getWifiSupplStateCount(int state, int which) {
6518 return mWifiSupplStateTimer[state].getCountLocked(which);
6519 }
6520
Kweku Adams87b19ec2017-10-09 12:40:03 -07006521 @Override public Timer getWifiSupplStateTimer(int state) {
6522 return mWifiSupplStateTimer[state];
6523 }
6524
Dianne Hackborn3251b902014-06-20 14:40:53 -07006525 @Override public long getWifiSignalStrengthTime(int strengthBin,
6526 long elapsedRealtimeUs, int which) {
6527 return mWifiSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
6528 elapsedRealtimeUs, which);
6529 }
6530
6531 @Override public int getWifiSignalStrengthCount(int strengthBin, int which) {
6532 return mWifiSignalStrengthsTimer[strengthBin].getCountLocked(which);
6533 }
6534
Kweku Adams87b19ec2017-10-09 12:40:03 -07006535 @Override public Timer getWifiSignalStrengthTimer(int strengthBin) {
6536 return mWifiSignalStrengthsTimer[strengthBin];
6537 }
6538
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006539 @Override
6540 public ControllerActivityCounter getBluetoothControllerActivity() {
6541 return mBluetoothActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07006542 }
6543
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006544 @Override
6545 public ControllerActivityCounter getWifiControllerActivity() {
6546 return mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -07006547 }
6548
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006549 @Override
6550 public ControllerActivityCounter getModemControllerActivity() {
6551 return mModemActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07006552 }
6553
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006554 @Override
6555 public boolean hasBluetoothActivityReporting() {
6556 return mHasBluetoothReporting;
6557 }
6558
6559 @Override
6560 public boolean hasWifiActivityReporting() {
6561 return mHasWifiReporting;
6562 }
6563
6564 @Override
6565 public boolean hasModemActivityReporting() {
6566 return mHasModemReporting;
Adam Lesinski33dac552015-03-09 15:24:48 -07006567 }
6568
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006569 @Override
6570 public long getFlashlightOnTime(long elapsedRealtimeUs, int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07006571 return mFlashlightOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6572 }
6573
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006574 @Override
6575 public long getFlashlightOnCount(int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07006576 return mFlashlightOnTimer.getCountLocked(which);
6577 }
6578
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006579 @Override
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006580 public long getCameraOnTime(long elapsedRealtimeUs, int which) {
6581 return mCameraOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6582 }
6583
6584 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006585 public long getBluetoothScanTime(long elapsedRealtimeUs, int which) {
6586 return mBluetoothScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6587 }
6588
6589 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006590 public long getNetworkActivityBytes(int type, int which) {
6591 if (type >= 0 && type < mNetworkByteActivityCounters.length) {
6592 return mNetworkByteActivityCounters[type].getCountLocked(which);
6593 } else {
6594 return 0;
6595 }
6596 }
6597
6598 @Override
6599 public long getNetworkActivityPackets(int type, int which) {
6600 if (type >= 0 && type < mNetworkPacketActivityCounters.length) {
6601 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006602 } else {
6603 return 0;
6604 }
6605 }
6606
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08006607 @Override public long getStartClockTime() {
Dianne Hackbornd48954f2015-07-22 17:20:33 -07006608 final long currentTime = System.currentTimeMillis();
6609 if (ensureStartClockTime(currentTime)) {
Joe Onoratoabded112016-02-08 16:49:39 -08006610 recordCurrentTimeChangeLocked(currentTime, mClocks.elapsedRealtime(),
6611 mClocks.uptimeMillis());
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07006612 }
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08006613 return mStartClockTime;
6614 }
6615
Dianne Hackborncd0e3352014-08-07 17:08:09 -07006616 @Override public String getStartPlatformVersion() {
6617 return mStartPlatformVersion;
6618 }
6619
6620 @Override public String getEndPlatformVersion() {
6621 return mEndPlatformVersion;
6622 }
6623
6624 @Override public int getParcelVersion() {
6625 return VERSION;
6626 }
6627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006628 @Override public boolean getIsOnBattery() {
6629 return mOnBattery;
6630 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006632 @Override public SparseArray<? extends BatteryStats.Uid> getUidStats() {
6633 return mUidStats;
6634 }
6635
Adam Lesinski5f056f62016-07-14 16:56:08 -07006636 private static void detachTimerIfNotNull(BatteryStatsImpl.Timer timer) {
6637 if (timer != null) {
6638 timer.detach();
6639 }
6640 }
6641
6642 private static boolean resetTimerIfNotNull(BatteryStatsImpl.Timer timer,
6643 boolean detachIfReset) {
6644 if (timer != null) {
6645 return timer.reset(detachIfReset);
6646 }
6647 return true;
6648 }
6649
Bookatz867c0d72017-03-07 18:23:42 -08006650 private static boolean resetTimerIfNotNull(DualTimer timer, boolean detachIfReset) {
6651 if (timer != null) {
6652 return timer.reset(detachIfReset);
6653 }
6654 return true;
6655 }
6656
Adam Lesinski5f056f62016-07-14 16:56:08 -07006657 private static void detachLongCounterIfNotNull(LongSamplingCounter counter) {
6658 if (counter != null) {
6659 counter.detach();
6660 }
6661 }
6662
6663 private static void resetLongCounterIfNotNull(LongSamplingCounter counter,
6664 boolean detachIfReset) {
6665 if (counter != null) {
6666 counter.reset(detachIfReset);
6667 }
6668 }
6669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006670 /**
6671 * The statistics associated with a particular uid.
6672 */
Joe Onoratoabded112016-02-08 16:49:39 -08006673 public static class Uid extends BatteryStats.Uid {
6674 /**
6675 * BatteryStatsImpl that we are associated with.
6676 */
6677 protected BatteryStatsImpl mBsi;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006678
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006679 final int mUid;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006680
Bookatz867c0d72017-03-07 18:23:42 -08006681 /** TimeBase for when uid is in background and device is on battery. */
6682 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6683 public final TimeBase mOnBatteryBackgroundTimeBase;
Bookatzc8c44962017-05-11 12:12:54 -07006684 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6685 public final TimeBase mOnBatteryScreenOffBackgroundTimeBase;
Bookatz867c0d72017-03-07 18:23:42 -08006686
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006687 boolean mWifiRunning;
6688 StopwatchTimer mWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006689
The Android Open Source Project10592532009-03-18 17:39:46 -07006690 boolean mFullWifiLockOut;
Evan Millarc64edde2009-04-18 12:26:32 -07006691 StopwatchTimer mFullWifiLockTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006692
Nick Pelly6ccaa542012-06-15 15:22:47 -07006693 boolean mWifiScanStarted;
Bookatz867c0d72017-03-07 18:23:42 -08006694 DualTimer mWifiScanTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006695
Dianne Hackborn61659e52014-07-09 16:13:01 -07006696 static final int NO_BATCHED_SCAN_STARTED = -1;
Robert Greenwalta029ea12013-09-25 16:38:12 -07006697 int mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
6698 StopwatchTimer[] mWifiBatchedScanTimer;
6699
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006700 boolean mWifiMulticastEnabled;
6701 StopwatchTimer mWifiMulticastTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006702
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006703 StopwatchTimer mAudioTurnedOnTimer;
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006704 StopwatchTimer mVideoTurnedOnTimer;
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006705 StopwatchTimer mFlashlightTurnedOnTimer;
6706 StopwatchTimer mCameraTurnedOnTimer;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006707 StopwatchTimer mForegroundActivityTimer;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006708 StopwatchTimer mForegroundServiceTimer;
Bookatzc8c44962017-05-11 12:12:54 -07006709 /** Total time spent by the uid holding any partial wakelocks. */
6710 DualTimer mAggregatedPartialWakelockTimer;
Bookatz867c0d72017-03-07 18:23:42 -08006711 DualTimer mBluetoothScanTimer;
Bookatzb1f04f32017-05-19 13:57:32 -07006712 DualTimer mBluetoothUnoptimizedScanTimer;
Bookatz956f36bf2017-04-28 09:48:17 -07006713 Counter mBluetoothScanResultCounter;
Bookatzb1f04f32017-05-19 13:57:32 -07006714 Counter mBluetoothScanResultBgCounter;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006715
Dianne Hackborna8d10942015-11-19 17:55:19 -08006716 int mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07006717 StopwatchTimer[] mProcessStateTimer;
6718
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006719 boolean mInForegroundService = false;
6720
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006721 BatchTimer mVibratorOnTimer;
6722
Dianne Hackborn617f8772009-03-31 15:04:46 -07006723 Counter[] mUserActivityCounters;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006724
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006725 LongSamplingCounter[] mNetworkByteActivityCounters;
6726 LongSamplingCounter[] mNetworkPacketActivityCounters;
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006727 LongSamplingCounter mMobileRadioActiveTime;
6728 LongSamplingCounter mMobileRadioActiveCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006730 /**
Adam Lesinski5f056f62016-07-14 16:56:08 -07006731 * How many times this UID woke up the Application Processor due to a Mobile radio packet.
6732 */
6733 private LongSamplingCounter mMobileRadioApWakeupCount;
6734
6735 /**
6736 * How many times this UID woke up the Application Processor due to a Wifi packet.
6737 */
6738 private LongSamplingCounter mWifiRadioApWakeupCount;
6739
6740 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07006741 * The amount of time this uid has kept the WiFi controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006742 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07006743 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006744 private ControllerActivityCounterImpl mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006745
6746 /**
6747 * The amount of time this uid has kept the Bluetooth controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006748 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07006749 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006750 private ControllerActivityCounterImpl mBluetoothControllerActivity;
6751
6752 /**
6753 * The amount of time this uid has kept the Modem controller in idle, tx, and rx mode.
6754 * Can be null if the UID has had no such activity.
6755 */
6756 private ControllerActivityCounterImpl mModemControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006757
6758 /**
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006759 * The CPU times we had at the last history details update.
6760 */
6761 long mLastStepUserTime;
6762 long mLastStepSystemTime;
6763 long mCurStepUserTime;
6764 long mCurStepSystemTime;
6765
Joe Onoratoabded112016-02-08 16:49:39 -08006766 LongSamplingCounter mUserCpuTime;
6767 LongSamplingCounter mSystemCpuTime;
Sudheer Shankaaf857412017-07-21 00:14:24 -07006768 LongSamplingCounter[][] mCpuClusterSpeedTimesUs;
Mike Ma3d422c32017-10-25 11:08:57 -07006769 LongSamplingCounter mCpuActiveTimeMs;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006770
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006771 LongSamplingCounterArray mCpuFreqTimeMs;
6772 LongSamplingCounterArray mScreenOffCpuFreqTimeMs;
Mike Ma3d422c32017-10-25 11:08:57 -07006773 LongSamplingCounterArray mCpuClusterTimesMs;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006774
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006775 LongSamplingCounterArray[] mProcStateTimeMs;
6776 LongSamplingCounterArray[] mProcStateScreenOffTimeMs;
6777
6778 IntArray mChildUids;
6779
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006780 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006781 * The statistics we have collected for this uid's wake locks.
6782 */
Joe Onoratoabded112016-02-08 16:49:39 -08006783 final OverflowArrayMap<Wakelock> mWakelockStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006784
6785 /**
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006786 * The statistics we have collected for this uid's syncs.
6787 */
Bookatz2bffb5b2017-04-13 11:59:33 -07006788 final OverflowArrayMap<DualTimer> mSyncStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006789
6790 /**
6791 * The statistics we have collected for this uid's jobs.
6792 */
Bookatzaa4594a2017-03-24 12:39:56 -07006793 final OverflowArrayMap<DualTimer> mJobStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006794
6795 /**
Dianne Hackborn94326cb2017-06-28 16:17:20 -07006796 * Count of the jobs that have completed and the reasons why they completed.
6797 */
6798 final ArrayMap<String, SparseIntArray> mJobCompletions = new ArrayMap<>();
6799
6800 /**
Amith Yamasani977e11f2018-02-16 11:29:54 -08006801 * Count of app launch events that had associated deferred job counts or info about
6802 * last time a job was run.
6803 */
6804 Counter mJobsDeferredEventCount;
6805
6806 /**
6807 * Count of deferred jobs that were pending when the app was launched or brought to
6808 * the foreground through a user interaction.
6809 */
6810 Counter mJobsDeferredCount;
6811
6812 /**
6813 * Sum of time since the last time a job was run for this app before it was launched.
6814 */
6815 LongSamplingCounter mJobsFreshnessTimeMs;
6816
6817 /**
6818 * Array of counts of instances where the time since the last job was run for the app
6819 * fell within one of the thresholds in {@link #JOB_FRESHNESS_BUCKETS}.
6820 */
6821 final Counter[] mJobsFreshnessBuckets;
6822
6823 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006824 * The statistics we have collected for this uid's sensor activations.
6825 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006826 final SparseArray<Sensor> mSensorStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006827
6828 /**
6829 * The statistics we have collected for this uid's processes.
6830 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006831 final ArrayMap<String, Proc> mProcessStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006832
6833 /**
6834 * The statistics we have collected for this uid's processes.
6835 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006836 final ArrayMap<String, Pkg> mPackageStats = new ArrayMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006837
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006838 /**
6839 * The transient wake stats we have collected for this uid's pids.
6840 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006841 final SparseArray<Pid> mPids = new SparseArray<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006842
Joe Onoratoabded112016-02-08 16:49:39 -08006843 public Uid(BatteryStatsImpl bsi, int uid) {
6844 mBsi = bsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006845 mUid = uid;
Joe Onoratoabded112016-02-08 16:49:39 -08006846
Bookatz867c0d72017-03-07 18:23:42 -08006847 mOnBatteryBackgroundTimeBase = new TimeBase();
6848 mOnBatteryBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
6849 mBsi.mClocks.elapsedRealtime() * 1000);
6850
Bookatzc8c44962017-05-11 12:12:54 -07006851 mOnBatteryScreenOffBackgroundTimeBase = new TimeBase();
6852 mOnBatteryScreenOffBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
6853 mBsi.mClocks.elapsedRealtime() * 1000);
6854
Joe Onoratoabded112016-02-08 16:49:39 -08006855 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6856 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Mike Ma3d422c32017-10-25 11:08:57 -07006857 mCpuActiveTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6858 mCpuClusterTimesMs = new LongSamplingCounterArray(mBsi.mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006859
Dianne Hackborn657153b2016-07-29 14:54:14 -07006860 mWakelockStats = mBsi.new OverflowArrayMap<Wakelock>(uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006861 @Override public Wakelock instantiateObject() {
6862 return new Wakelock(mBsi, Uid.this);
6863 }
6864 };
Bookatz2bffb5b2017-04-13 11:59:33 -07006865 mSyncStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
6866 @Override public DualTimer instantiateObject() {
6867 return new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
6868 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006869 }
6870 };
Bookatzaa4594a2017-03-24 12:39:56 -07006871 mJobStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
6872 @Override public DualTimer instantiateObject() {
6873 return new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
6874 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006875 }
6876 };
6877
6878 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_RUNNING,
6879 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
6880 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, this, FULL_WIFI_LOCK,
6881 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Bookatz867c0d72017-03-07 18:23:42 -08006882 mWifiScanTimer = new DualTimer(mBsi.mClocks, this, WIFI_SCAN,
6883 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006884 mWifiBatchedScanTimer = new StopwatchTimer[NUM_WIFI_BATCHED_SCAN_BINS];
Joe Onoratoabded112016-02-08 16:49:39 -08006885 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_MULTICAST_ENABLED,
6886 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006887 mProcessStateTimer = new StopwatchTimer[NUM_PROCESS_STATE];
Amith Yamasani977e11f2018-02-16 11:29:54 -08006888 mJobsDeferredEventCount = new Counter(mBsi.mOnBatteryTimeBase);
6889 mJobsDeferredCount = new Counter(mBsi.mOnBatteryTimeBase);
6890 mJobsFreshnessTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6891 mJobsFreshnessBuckets = new Counter[JOB_FRESHNESS_BUCKETS.length];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006892 }
6893
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006894 @VisibleForTesting
6895 public void setProcessStateForTest(int procState) {
6896 mProcessState = procState;
6897 }
6898
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006899 @Override
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006900 public long[] getCpuFreqTimes(int which) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006901 return nullIfAllZeros(mCpuFreqTimeMs, which);
6902 }
6903
6904 @Override
6905 public long[] getScreenOffCpuFreqTimes(int which) {
6906 return nullIfAllZeros(mScreenOffCpuFreqTimeMs, which);
6907 }
6908
6909 @Override
Mike Ma3d422c32017-10-25 11:08:57 -07006910 public long getCpuActiveTime() {
6911 return mCpuActiveTimeMs.getCountLocked(STATS_SINCE_CHARGED);
6912 }
6913
6914 @Override
6915 public long[] getCpuClusterTimes() {
6916 return nullIfAllZeros(mCpuClusterTimesMs, STATS_SINCE_CHARGED);
6917 }
6918
6919
6920 @Override
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006921 public long[] getCpuFreqTimes(int which, int procState) {
6922 if (which < 0 || which >= NUM_PROCESS_STATE) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006923 return null;
6924 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006925 if (mProcStateTimeMs == null) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006926 return null;
6927 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006928 if (!mBsi.mPerProcStateCpuTimesAvailable) {
6929 mProcStateTimeMs = null;
6930 return null;
6931 }
6932 return nullIfAllZeros(mProcStateTimeMs[procState], which);
6933 }
6934
6935 @Override
6936 public long[] getScreenOffCpuFreqTimes(int which, int procState) {
6937 if (which < 0 || which >= NUM_PROCESS_STATE) {
6938 return null;
6939 }
6940 if (mProcStateScreenOffTimeMs == null) {
6941 return null;
6942 }
6943 if (!mBsi.mPerProcStateCpuTimesAvailable) {
6944 mProcStateScreenOffTimeMs = null;
6945 return null;
6946 }
6947 return nullIfAllZeros(mProcStateScreenOffTimeMs[procState], which);
6948 }
6949
6950 public void addIsolatedUid(int isolatedUid) {
6951 if (mChildUids == null) {
6952 mChildUids = new IntArray();
6953 } else if (mChildUids.indexOf(isolatedUid) >= 0) {
6954 return;
6955 }
6956 mChildUids.add(isolatedUid);
6957 }
6958
6959 public void removeIsolatedUid(int isolatedUid) {
6960 final int idx = mChildUids == null ? -1 : mChildUids.indexOf(isolatedUid);
6961 if (idx < 0) {
6962 return;
6963 }
6964 mChildUids.remove(idx);
6965 }
6966
6967 private long[] nullIfAllZeros(LongSamplingCounterArray cpuTimesMs, int which) {
6968 if (cpuTimesMs == null) {
6969 return null;
6970 }
6971 final long[] counts = cpuTimesMs.getCountsLocked(which);
6972 if (counts == null) {
6973 return null;
6974 }
6975 // Return counts only if at least one of the elements is non-zero.
6976 for (int i = counts.length - 1; i >= 0; --i) {
6977 if (counts[i] != 0) {
6978 return counts;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006979 }
6980 }
6981 return null;
6982 }
6983
Sudheer Shankae544d162017-12-28 17:06:20 -08006984 private void addProcStateTimesMs(int procState, long[] cpuTimesMs, boolean onBattery) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006985 if (mProcStateTimeMs == null) {
6986 mProcStateTimeMs = new LongSamplingCounterArray[NUM_PROCESS_STATE];
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006987 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006988 if (mProcStateTimeMs[procState] == null
6989 || mProcStateTimeMs[procState].getSize() != cpuTimesMs.length) {
6990 mProcStateTimeMs[procState] = new LongSamplingCounterArray(
6991 mBsi.mOnBatteryTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006992 }
Sudheer Shankae544d162017-12-28 17:06:20 -08006993 mProcStateTimeMs[procState].addCountLocked(cpuTimesMs, onBattery);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006994 }
6995
Sudheer Shankae544d162017-12-28 17:06:20 -08006996 private void addProcStateScreenOffTimesMs(int procState, long[] cpuTimesMs,
6997 boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006998 if (mProcStateScreenOffTimeMs == null) {
6999 mProcStateScreenOffTimeMs = new LongSamplingCounterArray[NUM_PROCESS_STATE];
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007000 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007001 if (mProcStateScreenOffTimeMs[procState] == null
7002 || mProcStateScreenOffTimeMs[procState].getSize() != cpuTimesMs.length) {
7003 mProcStateScreenOffTimeMs[procState] = new LongSamplingCounterArray(
7004 mBsi.mOnBatteryScreenOffTimeBase);
7005 }
Sudheer Shankae544d162017-12-28 17:06:20 -08007006 mProcStateScreenOffTimeMs[procState].addCountLocked(cpuTimesMs, onBatteryScreenOff);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007007 }
7008
7009 @Override
Bookatzc8c44962017-05-11 12:12:54 -07007010 public Timer getAggregatedPartialWakelockTimer() {
7011 return mAggregatedPartialWakelockTimer;
7012 }
7013
7014 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007015 public ArrayMap<String, ? extends BatteryStats.Uid.Wakelock> getWakelockStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007016 return mWakelockStats.getMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007017 }
7018
7019 @Override
Ahmed ElArabawyddd09692017-10-30 17:58:29 -07007020 public Timer getMulticastWakelockStats() {
7021 return mWifiMulticastTimer;
7022 }
7023
7024 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007025 public ArrayMap<String, ? extends BatteryStats.Timer> getSyncStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007026 return mSyncStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007027 }
7028
7029 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007030 public ArrayMap<String, ? extends BatteryStats.Timer> getJobStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007031 return mJobStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007032 }
7033
7034 @Override
Dianne Hackborn94326cb2017-06-28 16:17:20 -07007035 public ArrayMap<String, SparseIntArray> getJobCompletionStats() {
7036 return mJobCompletions;
7037 }
7038
7039 @Override
Dianne Hackborn61659e52014-07-09 16:13:01 -07007040 public SparseArray<? extends BatteryStats.Uid.Sensor> getSensorStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007041 return mSensorStats;
7042 }
7043
7044 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007045 public ArrayMap<String, ? extends BatteryStats.Uid.Proc> getProcessStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007046 return mProcessStats;
7047 }
7048
7049 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007050 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg> getPackageStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007051 return mPackageStats;
7052 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007053
7054 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007055 public int getUid() {
7056 return mUid;
7057 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007058
7059 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007060 public void noteWifiRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007061 if (!mWifiRunning) {
7062 mWifiRunning = true;
7063 if (mWifiRunningTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007064 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
7065 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007066 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007067 mWifiRunningTimer.startRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007068 }
7069 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007070
Dianne Hackborn617f8772009-03-31 15:04:46 -07007071 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007072 public void noteWifiStoppedLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007073 if (mWifiRunning) {
7074 mWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007075 mWifiRunningTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007076 }
7077 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007078
Dianne Hackborn617f8772009-03-31 15:04:46 -07007079 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007080 public void noteFullWifiLockAcquiredLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07007081 if (!mFullWifiLockOut) {
7082 mFullWifiLockOut = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007083 if (mFullWifiLockTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007084 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
7085 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007086 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007087 mFullWifiLockTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007088 }
7089 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007090
The Android Open Source Project10592532009-03-18 17:39:46 -07007091 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007092 public void noteFullWifiLockReleasedLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07007093 if (mFullWifiLockOut) {
7094 mFullWifiLockOut = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007095 mFullWifiLockTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007096 }
7097 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007098
The Android Open Source Project10592532009-03-18 17:39:46 -07007099 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007100 public void noteWifiScanStartedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007101 if (!mWifiScanStarted) {
7102 mWifiScanStarted = true;
7103 if (mWifiScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007104 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
7105 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase,
7106 mOnBatteryBackgroundTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007107 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007108 mWifiScanTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007109 }
7110 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007111
The Android Open Source Project10592532009-03-18 17:39:46 -07007112 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007113 public void noteWifiScanStoppedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007114 if (mWifiScanStarted) {
7115 mWifiScanStarted = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007116 mWifiScanTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007117 }
7118 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007119
7120 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007121 public void noteWifiBatchedScanStartedLocked(int csph, long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007122 int bin = 0;
Navtej Singh Mann3c0ce5c2015-06-11 16:53:11 -07007123 while (csph > 8 && bin < NUM_WIFI_BATCHED_SCAN_BINS-1) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007124 csph = csph >> 3;
7125 bin++;
7126 }
7127
7128 if (mWifiBatchedScanBinStarted == bin) return;
7129
7130 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
7131 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007132 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007133 }
7134 mWifiBatchedScanBinStarted = bin;
7135 if (mWifiBatchedScanTimer[bin] == null) {
7136 makeWifiBatchedScanBin(bin, null);
7137 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007138 mWifiBatchedScanTimer[bin].startRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007139 }
7140
7141 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007142 public void noteWifiBatchedScanStoppedLocked(long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007143 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
7144 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007145 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007146 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
7147 }
7148 }
7149
7150 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007151 public void noteWifiMulticastEnabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007152 if (!mWifiMulticastEnabled) {
7153 mWifiMulticastEnabled = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007154 if (mWifiMulticastTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007155 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7156 WIFI_MULTICAST_ENABLED, mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007157 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007158 mWifiMulticastTimer.startRunningLocked(elapsedRealtimeMs);
Tej Singh4503e102018-01-04 14:35:01 -08007159 StatsLog.write_non_chained(
Bookatz90867622018-01-31 15:05:57 -08007160 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED, getUid(), null,
7161 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED__STATE__ON);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007162 }
7163 }
7164
7165 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007166 public void noteWifiMulticastDisabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007167 if (mWifiMulticastEnabled) {
7168 mWifiMulticastEnabled = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007169 mWifiMulticastTimer.stopRunningLocked(elapsedRealtimeMs);
Tej Singh4503e102018-01-04 14:35:01 -08007170 StatsLog.write_non_chained(
Bookatz90867622018-01-31 15:05:57 -08007171 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED, getUid(), null,
7172 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED__STATE__OFF);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007173 }
7174 }
7175
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007176 @Override
7177 public ControllerActivityCounter getWifiControllerActivity() {
7178 return mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07007179 }
7180
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007181 @Override
7182 public ControllerActivityCounter getBluetoothControllerActivity() {
7183 return mBluetoothControllerActivity;
7184 }
7185
7186 @Override
7187 public ControllerActivityCounter getModemControllerActivity() {
7188 return mModemControllerActivity;
7189 }
7190
7191 public ControllerActivityCounterImpl getOrCreateWifiControllerActivityLocked() {
7192 if (mWifiControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007193 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007194 NUM_BT_TX_LEVELS);
Adam Lesinski50e47602015-12-04 17:04:54 -08007195 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007196 return mWifiControllerActivity;
7197 }
7198
7199 public ControllerActivityCounterImpl getOrCreateBluetoothControllerActivityLocked() {
7200 if (mBluetoothControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007201 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007202 NUM_BT_TX_LEVELS);
7203 }
7204 return mBluetoothControllerActivity;
7205 }
7206
7207 public ControllerActivityCounterImpl getOrCreateModemControllerActivityLocked() {
7208 if (mModemControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007209 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007210 ModemActivityInfo.TX_POWER_LEVELS);
7211 }
7212 return mModemControllerActivity;
Adam Lesinski50e47602015-12-04 17:04:54 -08007213 }
7214
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007215 public StopwatchTimer createAudioTurnedOnTimerLocked() {
7216 if (mAudioTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007217 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
7218 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007219 }
7220 return mAudioTurnedOnTimer;
7221 }
7222
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007223 public void noteAudioTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007224 createAudioTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
7225 }
7226
7227 public void noteAudioTurnedOffLocked(long elapsedRealtimeMs) {
7228 if (mAudioTurnedOnTimer != null) {
7229 mAudioTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007230 }
7231 }
7232
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007233 public void noteResetAudioLocked(long elapsedRealtimeMs) {
7234 if (mAudioTurnedOnTimer != null) {
7235 mAudioTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007236 }
7237 }
7238
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007239 public StopwatchTimer createVideoTurnedOnTimerLocked() {
7240 if (mVideoTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007241 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
7242 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007243 }
7244 return mVideoTurnedOnTimer;
7245 }
7246
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007247 public void noteVideoTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007248 createVideoTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
7249 }
7250
7251 public void noteVideoTurnedOffLocked(long elapsedRealtimeMs) {
7252 if (mVideoTurnedOnTimer != null) {
7253 mVideoTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007254 }
7255 }
7256
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007257 public void noteResetVideoLocked(long elapsedRealtimeMs) {
7258 if (mVideoTurnedOnTimer != null) {
7259 mVideoTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007260 }
7261 }
7262
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007263 public StopwatchTimer createFlashlightTurnedOnTimerLocked() {
7264 if (mFlashlightTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007265 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7266 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007267 }
7268 return mFlashlightTurnedOnTimer;
7269 }
7270
7271 public void noteFlashlightTurnedOnLocked(long elapsedRealtimeMs) {
7272 createFlashlightTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
7273 }
7274
7275 public void noteFlashlightTurnedOffLocked(long elapsedRealtimeMs) {
7276 if (mFlashlightTurnedOnTimer != null) {
7277 mFlashlightTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
7278 }
7279 }
7280
7281 public void noteResetFlashlightLocked(long elapsedRealtimeMs) {
7282 if (mFlashlightTurnedOnTimer != null) {
7283 mFlashlightTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
7284 }
7285 }
7286
7287 public StopwatchTimer createCameraTurnedOnTimerLocked() {
7288 if (mCameraTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007289 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
7290 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007291 }
7292 return mCameraTurnedOnTimer;
7293 }
7294
7295 public void noteCameraTurnedOnLocked(long elapsedRealtimeMs) {
7296 createCameraTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
7297 }
7298
7299 public void noteCameraTurnedOffLocked(long elapsedRealtimeMs) {
7300 if (mCameraTurnedOnTimer != null) {
7301 mCameraTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
7302 }
7303 }
7304
7305 public void noteResetCameraLocked(long elapsedRealtimeMs) {
7306 if (mCameraTurnedOnTimer != null) {
7307 mCameraTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
7308 }
7309 }
7310
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007311 public StopwatchTimer createForegroundActivityTimerLocked() {
7312 if (mForegroundActivityTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007313 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7314 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007315 }
7316 return mForegroundActivityTimer;
7317 }
7318
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007319 public StopwatchTimer createForegroundServiceTimerLocked() {
7320 if (mForegroundServiceTimer == null) {
7321 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7322 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase);
7323 }
7324 return mForegroundServiceTimer;
7325 }
7326
Bookatzc8c44962017-05-11 12:12:54 -07007327 public DualTimer createAggregatedPartialWakelockTimerLocked() {
7328 if (mAggregatedPartialWakelockTimer == null) {
7329 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
7330 AGGREGATED_WAKE_TYPE_PARTIAL, null,
7331 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase);
7332 }
7333 return mAggregatedPartialWakelockTimer;
7334 }
7335
Bookatz867c0d72017-03-07 18:23:42 -08007336 public DualTimer createBluetoothScanTimerLocked() {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007337 if (mBluetoothScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007338 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
7339 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
7340 mOnBatteryBackgroundTimeBase);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007341 }
7342 return mBluetoothScanTimer;
7343 }
7344
Bookatzb1f04f32017-05-19 13:57:32 -07007345 public DualTimer createBluetoothUnoptimizedScanTimerLocked() {
7346 if (mBluetoothUnoptimizedScanTimer == null) {
7347 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
7348 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
7349 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
7350 }
7351 return mBluetoothUnoptimizedScanTimer;
7352 }
7353
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00007354 public void noteBluetoothScanStartedLocked(long elapsedRealtimeMs,
7355 boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007356 createBluetoothScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatzb1f04f32017-05-19 13:57:32 -07007357 if (isUnoptimized) {
7358 createBluetoothUnoptimizedScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
7359 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007360 }
7361
Bookatz94c5a312017-07-11 16:49:17 -07007362 public void noteBluetoothScanStoppedLocked(long elapsedRealtimeMs, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007363 if (mBluetoothScanTimer != null) {
7364 mBluetoothScanTimer.stopRunningLocked(elapsedRealtimeMs);
7365 }
Bookatz94c5a312017-07-11 16:49:17 -07007366 if (isUnoptimized && mBluetoothUnoptimizedScanTimer != null) {
Bookatzb1f04f32017-05-19 13:57:32 -07007367 mBluetoothUnoptimizedScanTimer.stopRunningLocked(elapsedRealtimeMs);
7368 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007369 }
7370
7371 public void noteResetBluetoothScanLocked(long elapsedRealtimeMs) {
7372 if (mBluetoothScanTimer != null) {
7373 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
7374 }
Bookatzb1f04f32017-05-19 13:57:32 -07007375 if (mBluetoothUnoptimizedScanTimer != null) {
7376 mBluetoothUnoptimizedScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
7377 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007378 }
7379
Bookatz956f36bf2017-04-28 09:48:17 -07007380 public Counter createBluetoothScanResultCounterLocked() {
7381 if (mBluetoothScanResultCounter == null) {
7382 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase);
7383 }
7384 return mBluetoothScanResultCounter;
7385 }
7386
Bookatzb1f04f32017-05-19 13:57:32 -07007387 public Counter createBluetoothScanResultBgCounterLocked() {
7388 if (mBluetoothScanResultBgCounter == null) {
7389 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase);
7390 }
7391 return mBluetoothScanResultBgCounter;
7392 }
7393
Bookatz4ebc0642017-05-11 12:21:19 -07007394 public void noteBluetoothScanResultsLocked(int numNewResults) {
7395 createBluetoothScanResultCounterLocked().addAtomic(numNewResults);
Bookatzb1f04f32017-05-19 13:57:32 -07007396 // Uses background timebase, so the count will only be incremented if uid in background.
7397 createBluetoothScanResultBgCounterLocked().addAtomic(numNewResults);
Bookatz956f36bf2017-04-28 09:48:17 -07007398 }
7399
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007400 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007401 public void noteActivityResumedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007402 // We always start, since we want multiple foreground PIDs to nest
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007403 createForegroundActivityTimerLocked().startRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007404 }
7405
7406 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007407 public void noteActivityPausedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007408 if (mForegroundActivityTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007409 mForegroundActivityTimer.stopRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007410 }
7411 }
7412
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007413 public void noteForegroundServiceResumedLocked(long elapsedRealtimeMs) {
7414 createForegroundServiceTimerLocked().startRunningLocked(elapsedRealtimeMs);
7415 }
7416
7417 public void noteForegroundServicePausedLocked(long elapsedRealtimeMs) {
7418 if (mForegroundServiceTimer != null) {
7419 mForegroundServiceTimer.stopRunningLocked(elapsedRealtimeMs);
7420 }
7421 }
7422
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007423 public BatchTimer createVibratorOnTimerLocked() {
7424 if (mVibratorOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007425 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
7426 mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007427 }
7428 return mVibratorOnTimer;
7429 }
7430
7431 public void noteVibratorOnLocked(long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08007432 createVibratorOnTimerLocked().addDuration(mBsi, durationMillis);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007433 }
7434
7435 public void noteVibratorOffLocked() {
7436 if (mVibratorOnTimer != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007437 mVibratorOnTimer.abortLastDuration(mBsi);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007438 }
7439 }
7440
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007441 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007442 public long getWifiRunningTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007443 if (mWifiRunningTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007444 return 0;
7445 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007446 return mWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007447 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07007448
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007449 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007450 public long getFullWifiLockTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007451 if (mFullWifiLockTimer == null) {
7452 return 0;
7453 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007454 return mFullWifiLockTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07007455 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007456
7457 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007458 public long getWifiScanTime(long elapsedRealtimeUs, int which) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007459 if (mWifiScanTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007460 return 0;
7461 }
Bookatzaa4594a2017-03-24 12:39:56 -07007462 return mWifiScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07007463 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007464
7465 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07007466 public int getWifiScanCount(int which) {
7467 if (mWifiScanTimer == null) {
7468 return 0;
7469 }
Bookatzaa4594a2017-03-24 12:39:56 -07007470 return mWifiScanTimer.getCountLocked(which);
Bookatz867c0d72017-03-07 18:23:42 -08007471 }
7472
7473 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07007474 public Timer getWifiScanTimer() {
7475 return mWifiScanTimer;
7476 }
7477
7478 @Override
Bookatz867c0d72017-03-07 18:23:42 -08007479 public int getWifiScanBackgroundCount(int which) {
Bookatzaa4594a2017-03-24 12:39:56 -07007480 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007481 return 0;
7482 }
7483 return mWifiScanTimer.getSubTimer().getCountLocked(which);
7484 }
7485
7486 @Override
7487 public long getWifiScanActualTime(final long elapsedRealtimeUs) {
7488 if (mWifiScanTimer == null) {
7489 return 0;
7490 }
7491 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
Bookatzaa4594a2017-03-24 12:39:56 -07007492 return mWifiScanTimer.getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Bookatz867c0d72017-03-07 18:23:42 -08007493 }
7494
7495 @Override
7496 public long getWifiScanBackgroundTime(final long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07007497 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007498 return 0;
7499 }
7500 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
7501 return mWifiScanTimer.getSubTimer().getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Dianne Hackborn62793e42015-03-09 11:15:41 -07007502 }
7503
7504 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07007505 public Timer getWifiScanBackgroundTimer() {
7506 if (mWifiScanTimer == null) {
7507 return null;
7508 }
7509 return mWifiScanTimer.getSubTimer();
7510 }
7511
7512 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007513 public long getWifiBatchedScanTime(int csphBin, long elapsedRealtimeUs, int which) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007514 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
7515 if (mWifiBatchedScanTimer[csphBin] == null) {
7516 return 0;
7517 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007518 return mWifiBatchedScanTimer[csphBin].getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007519 }
7520
7521 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07007522 public int getWifiBatchedScanCount(int csphBin, int which) {
7523 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
7524 if (mWifiBatchedScanTimer[csphBin] == null) {
7525 return 0;
7526 }
7527 return mWifiBatchedScanTimer[csphBin].getCountLocked(which);
7528 }
7529
7530 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007531 public long getWifiMulticastTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007532 if (mWifiMulticastTimer == null) {
7533 return 0;
7534 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007535 return mWifiMulticastTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007536 }
7537
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007538 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007539 public Timer getAudioTurnedOnTimer() {
7540 return mAudioTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007541 }
7542
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007543 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007544 public Timer getVideoTurnedOnTimer() {
7545 return mVideoTurnedOnTimer;
7546 }
7547
7548 @Override
7549 public Timer getFlashlightTurnedOnTimer() {
7550 return mFlashlightTurnedOnTimer;
7551 }
7552
7553 @Override
7554 public Timer getCameraTurnedOnTimer() {
7555 return mCameraTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007556 }
7557
Dianne Hackborn617f8772009-03-31 15:04:46 -07007558 @Override
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007559 public Timer getForegroundActivityTimer() {
7560 return mForegroundActivityTimer;
7561 }
7562
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007563 @Override
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007564 public Timer getForegroundServiceTimer() {
7565 return mForegroundServiceTimer;
7566 }
7567
7568 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007569 public Timer getBluetoothScanTimer() {
Bookatzaa4594a2017-03-24 12:39:56 -07007570 return mBluetoothScanTimer;
Bookatz867c0d72017-03-07 18:23:42 -08007571 }
7572
7573 @Override
7574 public Timer getBluetoothScanBackgroundTimer() {
7575 if (mBluetoothScanTimer == null) {
7576 return null;
7577 }
7578 return mBluetoothScanTimer.getSubTimer();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007579 }
7580
Bookatz956f36bf2017-04-28 09:48:17 -07007581 @Override
Bookatzb1f04f32017-05-19 13:57:32 -07007582 public Timer getBluetoothUnoptimizedScanTimer() {
7583 return mBluetoothUnoptimizedScanTimer;
7584 }
7585
7586 @Override
7587 public Timer getBluetoothUnoptimizedScanBackgroundTimer() {
7588 if (mBluetoothUnoptimizedScanTimer == null) {
7589 return null;
7590 }
7591 return mBluetoothUnoptimizedScanTimer.getSubTimer();
7592 }
7593
7594 @Override
Bookatz956f36bf2017-04-28 09:48:17 -07007595 public Counter getBluetoothScanResultCounter() {
7596 return mBluetoothScanResultCounter;
7597 }
7598
Bookatzb1f04f32017-05-19 13:57:32 -07007599 @Override
7600 public Counter getBluetoothScanResultBgCounter() {
7601 return mBluetoothScanResultBgCounter;
7602 }
7603
Dianne Hackborn61659e52014-07-09 16:13:01 -07007604 void makeProcessState(int i, Parcel in) {
7605 if (i < 0 || i >= NUM_PROCESS_STATE) return;
7606
7607 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007608 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
7609 mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007610 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08007611 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
7612 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007613 }
7614 }
7615
7616 @Override
7617 public long getProcessStateTime(int state, long elapsedRealtimeUs, int which) {
7618 if (state < 0 || state >= NUM_PROCESS_STATE) return 0;
7619 if (mProcessStateTimer[state] == null) {
7620 return 0;
7621 }
7622 return mProcessStateTimer[state].getTotalTimeLocked(elapsedRealtimeUs, which);
7623 }
7624
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007625 @Override
Joe Onorato713fec82016-03-04 10:34:02 -08007626 public Timer getProcessStateTimer(int state) {
7627 if (state < 0 || state >= NUM_PROCESS_STATE) return null;
7628 return mProcessStateTimer[state];
7629 }
7630
7631 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007632 public Timer getVibratorOnTimer() {
7633 return mVibratorOnTimer;
7634 }
7635
7636 @Override
Dianne Hackborn617f8772009-03-31 15:04:46 -07007637 public void noteUserActivityLocked(int type) {
7638 if (mUserActivityCounters == null) {
7639 initUserActivityLocked();
7640 }
Jeff Browndf693de2012-07-27 12:03:38 -07007641 if (type >= 0 && type < NUM_USER_ACTIVITY_TYPES) {
7642 mUserActivityCounters[type].stepAtomic();
7643 } else {
7644 Slog.w(TAG, "Unknown user activity type " + type + " was specified.",
7645 new Throwable());
7646 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07007647 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007648
Dianne Hackborn617f8772009-03-31 15:04:46 -07007649 @Override
7650 public boolean hasUserActivity() {
7651 return mUserActivityCounters != null;
7652 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007653
Dianne Hackborn617f8772009-03-31 15:04:46 -07007654 @Override
7655 public int getUserActivityCount(int type, int which) {
7656 if (mUserActivityCounters == null) {
7657 return 0;
7658 }
Evan Millarc64edde2009-04-18 12:26:32 -07007659 return mUserActivityCounters[type].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007660 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007661
Robert Greenwalta029ea12013-09-25 16:38:12 -07007662 void makeWifiBatchedScanBin(int i, Parcel in) {
7663 if (i < 0 || i >= NUM_WIFI_BATCHED_SCAN_BINS) return;
7664
Joe Onoratoabded112016-02-08 16:49:39 -08007665 ArrayList<StopwatchTimer> collected = mBsi.mWifiBatchedScanTimers.get(i);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007666 if (collected == null) {
7667 collected = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08007668 mBsi.mWifiBatchedScanTimers.put(i, collected);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007669 }
7670 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007671 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
7672 collected, mBsi.mOnBatteryTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007673 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08007674 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
7675 collected, mBsi.mOnBatteryTimeBase, in);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007676 }
7677 }
7678
7679
Dianne Hackborn617f8772009-03-31 15:04:46 -07007680 void initUserActivityLocked() {
7681 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
7682 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007683 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007684 }
7685 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007686
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007687 void noteNetworkActivityLocked(int type, long deltaBytes, long deltaPackets) {
7688 if (mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007689 initNetworkActivityLocked();
7690 }
7691 if (type >= 0 && type < NUM_NETWORK_ACTIVITY_TYPES) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007692 mNetworkByteActivityCounters[type].addCountLocked(deltaBytes);
7693 mNetworkPacketActivityCounters[type].addCountLocked(deltaPackets);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007694 } else {
7695 Slog.w(TAG, "Unknown network activity type " + type + " was specified.",
7696 new Throwable());
7697 }
7698 }
7699
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007700 void noteMobileRadioActiveTimeLocked(long batteryUptime) {
7701 if (mNetworkByteActivityCounters == null) {
7702 initNetworkActivityLocked();
7703 }
7704 mMobileRadioActiveTime.addCountLocked(batteryUptime);
7705 mMobileRadioActiveCount.addCountLocked(1);
7706 }
7707
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007708 @Override
7709 public boolean hasNetworkActivity() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007710 return mNetworkByteActivityCounters != null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007711 }
7712
7713 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007714 public long getNetworkActivityBytes(int type, int which) {
7715 if (mNetworkByteActivityCounters != null && type >= 0
7716 && type < mNetworkByteActivityCounters.length) {
7717 return mNetworkByteActivityCounters[type].getCountLocked(which);
7718 } else {
7719 return 0;
7720 }
7721 }
7722
7723 @Override
7724 public long getNetworkActivityPackets(int type, int which) {
7725 if (mNetworkPacketActivityCounters != null && type >= 0
7726 && type < mNetworkPacketActivityCounters.length) {
7727 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007728 } else {
7729 return 0;
7730 }
7731 }
7732
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007733 @Override
7734 public long getMobileRadioActiveTime(int which) {
7735 return mMobileRadioActiveTime != null
7736 ? mMobileRadioActiveTime.getCountLocked(which) : 0;
7737 }
7738
7739 @Override
7740 public int getMobileRadioActiveCount(int which) {
7741 return mMobileRadioActiveCount != null
7742 ? (int)mMobileRadioActiveCount.getCountLocked(which) : 0;
7743 }
7744
Adam Lesinskie08af192015-03-25 16:42:59 -07007745 @Override
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007746 public long getUserCpuTimeUs(int which) {
7747 return mUserCpuTime.getCountLocked(which);
7748 }
7749
7750 @Override
7751 public long getSystemCpuTimeUs(int which) {
7752 return mSystemCpuTime.getCountLocked(which);
7753 }
7754
7755 @Override
Adam Lesinski6832f392015-09-05 18:05:40 -07007756 public long getTimeAtCpuSpeed(int cluster, int step, int which) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07007757 if (mCpuClusterSpeedTimesUs != null) {
7758 if (cluster >= 0 && cluster < mCpuClusterSpeedTimesUs.length) {
7759 final LongSamplingCounter[] cpuSpeedTimesUs = mCpuClusterSpeedTimesUs[cluster];
7760 if (cpuSpeedTimesUs != null) {
7761 if (step >= 0 && step < cpuSpeedTimesUs.length) {
7762 final LongSamplingCounter c = cpuSpeedTimesUs[step];
Adam Lesinski6832f392015-09-05 18:05:40 -07007763 if (c != null) {
7764 return c.getCountLocked(which);
7765 }
7766 }
7767 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007768 }
7769 }
7770 return 0;
7771 }
7772
Adam Lesinski5f056f62016-07-14 16:56:08 -07007773 public void noteMobileRadioApWakeupLocked() {
7774 if (mMobileRadioApWakeupCount == null) {
7775 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7776 }
7777 mMobileRadioApWakeupCount.addCountLocked(1);
7778 }
7779
7780 @Override
7781 public long getMobileRadioApWakeupCount(int which) {
7782 if (mMobileRadioApWakeupCount != null) {
7783 return mMobileRadioApWakeupCount.getCountLocked(which);
7784 }
7785 return 0;
7786 }
7787
7788 public void noteWifiRadioApWakeupLocked() {
7789 if (mWifiRadioApWakeupCount == null) {
7790 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7791 }
7792 mWifiRadioApWakeupCount.addCountLocked(1);
7793 }
7794
7795 @Override
7796 public long getWifiRadioApWakeupCount(int which) {
7797 if (mWifiRadioApWakeupCount != null) {
7798 return mWifiRadioApWakeupCount.getCountLocked(which);
7799 }
7800 return 0;
7801 }
7802
Amith Yamasani977e11f2018-02-16 11:29:54 -08007803 @Override
7804 public void getDeferredJobsCheckinLineLocked(StringBuilder sb, int which) {
7805 sb.setLength(0);
7806 final int deferredEventCount = mJobsDeferredEventCount.getCountLocked(which);
7807 if (deferredEventCount == 0) {
7808 return;
7809 }
7810 final int deferredCount = mJobsDeferredCount.getCountLocked(which);
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007811 final long totalLatency = mJobsFreshnessTimeMs.getCountLocked(which);
Amith Yamasani977e11f2018-02-16 11:29:54 -08007812 sb.append(deferredEventCount); sb.append(',');
7813 sb.append(deferredCount); sb.append(',');
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007814 sb.append(totalLatency);
Amith Yamasani977e11f2018-02-16 11:29:54 -08007815 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
7816 if (mJobsFreshnessBuckets[i] == null) {
7817 sb.append(",0");
7818 } else {
7819 sb.append(",");
7820 sb.append(mJobsFreshnessBuckets[i].getCountLocked(which));
7821 }
7822 }
7823 }
7824
7825 @Override
7826 public void getDeferredJobsLineLocked(StringBuilder sb, int which) {
7827 sb.setLength(0);
7828 final int deferredEventCount = mJobsDeferredEventCount.getCountLocked(which);
7829 if (deferredEventCount == 0) {
7830 return;
7831 }
7832 final int deferredCount = mJobsDeferredCount.getCountLocked(which);
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007833 final long totalLatency = mJobsFreshnessTimeMs.getCountLocked(which);
Amith Yamasani977e11f2018-02-16 11:29:54 -08007834 sb.append("times="); sb.append(deferredEventCount); sb.append(", ");
7835 sb.append("count="); sb.append(deferredCount); sb.append(", ");
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007836 sb.append("totalLatencyMs="); sb.append(totalLatency); sb.append(", ");
Amith Yamasani977e11f2018-02-16 11:29:54 -08007837 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
7838 sb.append("<"); sb.append(JOB_FRESHNESS_BUCKETS[i]); sb.append("ms=");
7839 if (mJobsFreshnessBuckets[i] == null) {
7840 sb.append("0");
7841 } else {
7842 sb.append(mJobsFreshnessBuckets[i].getCountLocked(which));
7843 }
7844 sb.append(" ");
7845 }
7846 }
7847
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007848 void initNetworkActivityLocked() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007849 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
7850 mNetworkPacketActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007851 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007852 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7853 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007854 }
Joe Onoratoabded112016-02-08 16:49:39 -08007855 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7856 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007857 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07007858
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007859 /**
7860 * Clear all stats for this uid. Returns true if the uid is completely
7861 * inactive so can be dropped.
7862 */
Adam Lesinski5f212c82017-03-13 12:25:13 -07007863 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
Bookatz993a0be2017-07-21 09:03:23 -07007864 public boolean reset(long uptime, long realtime) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007865 boolean active = false;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007866
Bookatz993a0be2017-07-21 09:03:23 -07007867 mOnBatteryBackgroundTimeBase.init(uptime, realtime);
7868 mOnBatteryScreenOffBackgroundTimeBase.init(uptime, realtime);
7869
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007870 if (mWifiRunningTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007871 active |= !mWifiRunningTimer.reset(false);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007872 active |= mWifiRunning;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007873 }
7874 if (mFullWifiLockTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007875 active |= !mFullWifiLockTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007876 active |= mFullWifiLockOut;
7877 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07007878 if (mWifiScanTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007879 active |= !mWifiScanTimer.reset(false);
Nick Pelly6ccaa542012-06-15 15:22:47 -07007880 active |= mWifiScanStarted;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007881 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07007882 if (mWifiBatchedScanTimer != null) {
7883 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
7884 if (mWifiBatchedScanTimer[i] != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007885 active |= !mWifiBatchedScanTimer[i].reset(false);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007886 }
7887 }
7888 active |= (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED);
7889 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007890 if (mWifiMulticastTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007891 active |= !mWifiMulticastTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007892 active |= mWifiMulticastEnabled;
7893 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007894
7895 active |= !resetTimerIfNotNull(mAudioTurnedOnTimer, false);
7896 active |= !resetTimerIfNotNull(mVideoTurnedOnTimer, false);
7897 active |= !resetTimerIfNotNull(mFlashlightTurnedOnTimer, false);
7898 active |= !resetTimerIfNotNull(mCameraTurnedOnTimer, false);
7899 active |= !resetTimerIfNotNull(mForegroundActivityTimer, false);
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007900 active |= !resetTimerIfNotNull(mForegroundServiceTimer, false);
Bookatzc8c44962017-05-11 12:12:54 -07007901 active |= !resetTimerIfNotNull(mAggregatedPartialWakelockTimer, false);
Adam Lesinski5f056f62016-07-14 16:56:08 -07007902 active |= !resetTimerIfNotNull(mBluetoothScanTimer, false);
Bookatzb1f04f32017-05-19 13:57:32 -07007903 active |= !resetTimerIfNotNull(mBluetoothUnoptimizedScanTimer, false);
Bookatz956f36bf2017-04-28 09:48:17 -07007904 if (mBluetoothScanResultCounter != null) {
7905 mBluetoothScanResultCounter.reset(false);
7906 }
Bookatzb1f04f32017-05-19 13:57:32 -07007907 if (mBluetoothScanResultBgCounter != null) {
7908 mBluetoothScanResultBgCounter.reset(false);
7909 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007910
Dianne Hackborn61659e52014-07-09 16:13:01 -07007911 if (mProcessStateTimer != null) {
7912 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
7913 if (mProcessStateTimer[i] != null) {
7914 active |= !mProcessStateTimer[i].reset(false);
7915 }
7916 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08007917 active |= (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007918 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007919 if (mVibratorOnTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007920 if (mVibratorOnTimer.reset(false)) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007921 mVibratorOnTimer.detach();
7922 mVibratorOnTimer = null;
7923 } else {
7924 active = true;
7925 }
7926 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007927
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007928 if (mUserActivityCounters != null) {
7929 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
7930 mUserActivityCounters[i].reset(false);
7931 }
7932 }
7933
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007934 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007935 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007936 mNetworkByteActivityCounters[i].reset(false);
7937 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007938 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007939 mMobileRadioActiveTime.reset(false);
7940 mMobileRadioActiveCount.reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007941 }
7942
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007943 if (mWifiControllerActivity != null) {
7944 mWifiControllerActivity.reset(false);
7945 }
Adam Lesinskie08af192015-03-25 16:42:59 -07007946
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07007947 if (mBluetoothControllerActivity != null) {
7948 mBluetoothControllerActivity.reset(false);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007949 }
7950
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07007951 if (mModemControllerActivity != null) {
7952 mModemControllerActivity.reset(false);
Adam Lesinskie08af192015-03-25 16:42:59 -07007953 }
7954
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007955 mUserCpuTime.reset(false);
7956 mSystemCpuTime.reset(false);
Adam Lesinski6832f392015-09-05 18:05:40 -07007957
Sudheer Shankaaf857412017-07-21 00:14:24 -07007958 if (mCpuClusterSpeedTimesUs != null) {
7959 for (LongSamplingCounter[] speeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07007960 if (speeds != null) {
7961 for (LongSamplingCounter speed : speeds) {
7962 if (speed != null) {
7963 speed.reset(false);
7964 }
7965 }
7966 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007967 }
7968 }
7969
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007970 if (mCpuFreqTimeMs != null) {
7971 mCpuFreqTimeMs.reset(false);
7972 }
7973 if (mScreenOffCpuFreqTimeMs != null) {
7974 mScreenOffCpuFreqTimeMs.reset(false);
7975 }
7976
Mike Ma3d422c32017-10-25 11:08:57 -07007977 mCpuActiveTimeMs.reset(false);
7978 mCpuClusterTimesMs.reset(false);
7979
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007980 if (mProcStateTimeMs != null) {
7981 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
7982 if (counters != null) {
7983 counters.reset(false);
7984 }
7985 }
7986 }
7987 if (mProcStateScreenOffTimeMs != null) {
7988 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
7989 if (counters != null) {
7990 counters.reset(false);
7991 }
7992 }
7993 }
7994
Adam Lesinski5f056f62016-07-14 16:56:08 -07007995 resetLongCounterIfNotNull(mMobileRadioApWakeupCount, false);
7996 resetLongCounterIfNotNull(mWifiRadioApWakeupCount, false);
7997
Dianne Hackbornd953c532014-08-16 18:17:38 -07007998 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
7999 for (int iw=wakeStats.size()-1; iw>=0; iw--) {
8000 Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07008001 if (wl.reset()) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008002 wakeStats.removeAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07008003 } else {
8004 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008005 }
8006 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07008007 mWakelockStats.cleanup();
Bookatz2bffb5b2017-04-13 11:59:33 -07008008 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008009 for (int is=syncStats.size()-1; is>=0; is--) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008010 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008011 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008012 syncStats.removeAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008013 timer.detach();
8014 } else {
8015 active = true;
8016 }
8017 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07008018 mSyncStats.cleanup();
Bookatzaa4594a2017-03-24 12:39:56 -07008019 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008020 for (int ij=jobStats.size()-1; ij>=0; ij--) {
Bookatzaa4594a2017-03-24 12:39:56 -07008021 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008022 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008023 jobStats.removeAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008024 timer.detach();
8025 } else {
8026 active = true;
8027 }
8028 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07008029 mJobStats.cleanup();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008030 mJobCompletions.clear();
Amith Yamasani977e11f2018-02-16 11:29:54 -08008031
8032 mJobsDeferredEventCount.reset(false);
8033 mJobsDeferredCount.reset(false);
8034 mJobsFreshnessTimeMs.reset(false);
8035 for (int ij = 0; ij < JOB_FRESHNESS_BUCKETS.length; ij++) {
8036 if (mJobsFreshnessBuckets[ij] != null) {
8037 mJobsFreshnessBuckets[ij].reset(false);
8038 }
8039 }
8040
Dianne Hackborn61659e52014-07-09 16:13:01 -07008041 for (int ise=mSensorStats.size()-1; ise>=0; ise--) {
8042 Sensor s = mSensorStats.valueAt(ise);
8043 if (s.reset()) {
8044 mSensorStats.removeAt(ise);
8045 } else {
8046 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008047 }
8048 }
Amith Yamasani977e11f2018-02-16 11:29:54 -08008049
Dianne Hackborn61659e52014-07-09 16:13:01 -07008050 for (int ip=mProcessStats.size()-1; ip>=0; ip--) {
8051 Proc proc = mProcessStats.valueAt(ip);
Dianne Hackborna8d10942015-11-19 17:55:19 -08008052 proc.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008053 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08008054 mProcessStats.clear();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008055 if (mPids.size() > 0) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008056 for (int i=mPids.size()-1; i>=0; i--) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008057 Pid pid = mPids.valueAt(i);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008058 if (pid.mWakeNesting > 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008059 active = true;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008060 } else {
8061 mPids.removeAt(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008062 }
8063 }
8064 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008065 if (mPackageStats.size() > 0) {
8066 Iterator<Map.Entry<String, Pkg>> it = mPackageStats.entrySet().iterator();
8067 while (it.hasNext()) {
8068 Map.Entry<String, Pkg> pkgEntry = it.next();
8069 Pkg p = pkgEntry.getValue();
8070 p.detach();
8071 if (p.mServiceStats.size() > 0) {
8072 Iterator<Map.Entry<String, Pkg.Serv>> it2
8073 = p.mServiceStats.entrySet().iterator();
8074 while (it2.hasNext()) {
8075 Map.Entry<String, Pkg.Serv> servEntry = it2.next();
8076 servEntry.getValue().detach();
8077 }
8078 }
8079 }
8080 mPackageStats.clear();
8081 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008082
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08008083 mLastStepUserTime = mLastStepSystemTime = 0;
8084 mCurStepUserTime = mCurStepSystemTime = 0;
8085
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008086 if (!active) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008087 if (mWifiRunningTimer != null) {
8088 mWifiRunningTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008089 }
8090 if (mFullWifiLockTimer != null) {
8091 mFullWifiLockTimer.detach();
8092 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008093 if (mWifiScanTimer != null) {
8094 mWifiScanTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008095 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008096 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8097 if (mWifiBatchedScanTimer[i] != null) {
8098 mWifiBatchedScanTimer[i].detach();
8099 }
8100 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008101 if (mWifiMulticastTimer != null) {
8102 mWifiMulticastTimer.detach();
8103 }
8104 if (mAudioTurnedOnTimer != null) {
8105 mAudioTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008106 mAudioTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008107 }
8108 if (mVideoTurnedOnTimer != null) {
8109 mVideoTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008110 mVideoTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008111 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008112 if (mFlashlightTurnedOnTimer != null) {
8113 mFlashlightTurnedOnTimer.detach();
8114 mFlashlightTurnedOnTimer = null;
8115 }
8116 if (mCameraTurnedOnTimer != null) {
8117 mCameraTurnedOnTimer.detach();
8118 mCameraTurnedOnTimer = null;
8119 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008120 if (mForegroundActivityTimer != null) {
8121 mForegroundActivityTimer.detach();
8122 mForegroundActivityTimer = null;
8123 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008124 if (mForegroundServiceTimer != null) {
8125 mForegroundServiceTimer.detach();
8126 mForegroundServiceTimer = null;
8127 }
Bookatzc8c44962017-05-11 12:12:54 -07008128 if (mAggregatedPartialWakelockTimer != null) {
8129 mAggregatedPartialWakelockTimer.detach();
8130 mAggregatedPartialWakelockTimer = null;
8131 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008132 if (mBluetoothScanTimer != null) {
8133 mBluetoothScanTimer.detach();
8134 mBluetoothScanTimer = null;
8135 }
Bookatzb1f04f32017-05-19 13:57:32 -07008136 if (mBluetoothUnoptimizedScanTimer != null) {
8137 mBluetoothUnoptimizedScanTimer.detach();
8138 mBluetoothUnoptimizedScanTimer = null;
8139 }
Bookatz956f36bf2017-04-28 09:48:17 -07008140 if (mBluetoothScanResultCounter != null) {
8141 mBluetoothScanResultCounter.detach();
8142 mBluetoothScanResultCounter = null;
8143 }
Bookatzb1f04f32017-05-19 13:57:32 -07008144 if (mBluetoothScanResultBgCounter != null) {
8145 mBluetoothScanResultBgCounter.detach();
8146 mBluetoothScanResultBgCounter = null;
8147 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008148 if (mUserActivityCounters != null) {
8149 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
8150 mUserActivityCounters[i].detach();
8151 }
8152 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008153 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008154 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008155 mNetworkByteActivityCounters[i].detach();
8156 mNetworkPacketActivityCounters[i].detach();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008157 }
8158 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008159
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008160 if (mWifiControllerActivity != null) {
8161 mWifiControllerActivity.detach();
Adam Lesinskie08af192015-03-25 16:42:59 -07008162 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008163
8164 if (mBluetoothControllerActivity != null) {
8165 mBluetoothControllerActivity.detach();
8166 }
8167
8168 if (mModemControllerActivity != null) {
8169 mModemControllerActivity.detach();
8170 }
8171
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008172 mPids.clear();
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008173
8174 mUserCpuTime.detach();
8175 mSystemCpuTime.detach();
Adam Lesinski6832f392015-09-05 18:05:40 -07008176
Sudheer Shankaaf857412017-07-21 00:14:24 -07008177 if (mCpuClusterSpeedTimesUs != null) {
8178 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008179 if (cpuSpeeds != null) {
8180 for (LongSamplingCounter c : cpuSpeeds) {
8181 if (c != null) {
8182 c.detach();
8183 }
8184 }
8185 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008186 }
8187 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008188
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008189 if (mCpuFreqTimeMs != null) {
8190 mCpuFreqTimeMs.detach();
8191 }
8192 if (mScreenOffCpuFreqTimeMs != null) {
8193 mScreenOffCpuFreqTimeMs.detach();
8194 }
Mike Ma3d422c32017-10-25 11:08:57 -07008195 mCpuActiveTimeMs.detach();
8196 mCpuClusterTimesMs.detach();
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008197
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008198 if (mProcStateTimeMs != null) {
8199 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8200 if (counters != null) {
8201 counters.detach();
8202 }
8203 }
8204 }
8205 if (mProcStateScreenOffTimeMs != null) {
8206 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8207 if (counters != null) {
8208 counters.detach();
8209 }
8210 }
8211 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008212 detachLongCounterIfNotNull(mMobileRadioApWakeupCount);
8213 detachLongCounterIfNotNull(mWifiRadioApWakeupCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008214 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008215
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008216 return !active;
8217 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008218
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008219 void writeJobCompletionsToParcelLocked(Parcel out) {
8220 int NJC = mJobCompletions.size();
8221 out.writeInt(NJC);
8222 for (int ijc=0; ijc<NJC; ijc++) {
8223 out.writeString(mJobCompletions.keyAt(ijc));
8224 SparseIntArray types = mJobCompletions.valueAt(ijc);
8225 int NT = types.size();
8226 out.writeInt(NT);
8227 for (int it=0; it<NT; it++) {
8228 out.writeInt(types.keyAt(it));
8229 out.writeInt(types.valueAt(it));
8230 }
8231 }
8232 }
8233
Bookatz867c0d72017-03-07 18:23:42 -08008234 void writeToParcelLocked(Parcel out, long uptimeUs, long elapsedRealtimeUs) {
8235 mOnBatteryBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatzc8c44962017-05-11 12:12:54 -07008236 mOnBatteryScreenOffBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08008237
Dianne Hackbornd953c532014-08-16 18:17:38 -07008238 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
8239 int NW = wakeStats.size();
Dianne Hackborn61659e52014-07-09 16:13:01 -07008240 out.writeInt(NW);
8241 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008242 out.writeString(wakeStats.keyAt(iw));
8243 Uid.Wakelock wakelock = wakeStats.valueAt(iw);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008244 wakelock.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008245 }
8246
Bookatz2bffb5b2017-04-13 11:59:33 -07008247 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008248 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008249 out.writeInt(NS);
8250 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008251 out.writeString(syncStats.keyAt(is));
Bookatz2bffb5b2017-04-13 11:59:33 -07008252 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008253 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
8254 }
8255
Bookatzaa4594a2017-03-24 12:39:56 -07008256 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008257 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008258 out.writeInt(NJ);
8259 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008260 out.writeString(jobStats.keyAt(ij));
Bookatzaa4594a2017-03-24 12:39:56 -07008261 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008262 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
8263 }
8264
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008265 writeJobCompletionsToParcelLocked(out);
8266
Amith Yamasani977e11f2018-02-16 11:29:54 -08008267 mJobsDeferredEventCount.writeToParcel(out);
8268 mJobsDeferredCount.writeToParcel(out);
8269 mJobsFreshnessTimeMs.writeToParcel(out);
8270 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
8271 Counter.writeCounterToParcel(out, mJobsFreshnessBuckets[i]);
8272 }
8273
Dianne Hackborn61659e52014-07-09 16:13:01 -07008274 int NSE = mSensorStats.size();
8275 out.writeInt(NSE);
8276 for (int ise=0; ise<NSE; ise++) {
8277 out.writeInt(mSensorStats.keyAt(ise));
8278 Uid.Sensor sensor = mSensorStats.valueAt(ise);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008279 sensor.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008280 }
8281
Dianne Hackborn61659e52014-07-09 16:13:01 -07008282 int NP = mProcessStats.size();
8283 out.writeInt(NP);
8284 for (int ip=0; ip<NP; ip++) {
8285 out.writeString(mProcessStats.keyAt(ip));
8286 Uid.Proc proc = mProcessStats.valueAt(ip);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008287 proc.writeToParcelLocked(out);
8288 }
8289
8290 out.writeInt(mPackageStats.size());
8291 for (Map.Entry<String, Uid.Pkg> pkgEntry : mPackageStats.entrySet()) {
8292 out.writeString(pkgEntry.getKey());
8293 Uid.Pkg pkg = pkgEntry.getValue();
8294 pkg.writeToParcelLocked(out);
8295 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008296
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008297 if (mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008298 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008299 mWifiRunningTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008300 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008301 out.writeInt(0);
8302 }
8303 if (mFullWifiLockTimer != null) {
8304 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008305 mFullWifiLockTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008306 } else {
8307 out.writeInt(0);
8308 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008309 if (mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008310 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008311 mWifiScanTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008312 } else {
8313 out.writeInt(0);
8314 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008315 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8316 if (mWifiBatchedScanTimer[i] != null) {
8317 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008318 mWifiBatchedScanTimer[i].writeToParcel(out, elapsedRealtimeUs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07008319 } else {
8320 out.writeInt(0);
8321 }
8322 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008323 if (mWifiMulticastTimer != null) {
8324 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008325 mWifiMulticastTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008326 } else {
8327 out.writeInt(0);
8328 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008329
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008330 if (mAudioTurnedOnTimer != null) {
8331 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008332 mAudioTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008333 } else {
8334 out.writeInt(0);
8335 }
8336 if (mVideoTurnedOnTimer != null) {
8337 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008338 mVideoTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008339 } else {
8340 out.writeInt(0);
8341 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008342 if (mFlashlightTurnedOnTimer != null) {
8343 out.writeInt(1);
8344 mFlashlightTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
8345 } else {
8346 out.writeInt(0);
8347 }
8348 if (mCameraTurnedOnTimer != null) {
8349 out.writeInt(1);
8350 mCameraTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
8351 } else {
8352 out.writeInt(0);
8353 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008354 if (mForegroundActivityTimer != null) {
8355 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008356 mForegroundActivityTimer.writeToParcel(out, elapsedRealtimeUs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008357 } else {
8358 out.writeInt(0);
8359 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008360 if (mForegroundServiceTimer != null) {
8361 out.writeInt(1);
8362 mForegroundServiceTimer.writeToParcel(out, elapsedRealtimeUs);
8363 } else {
8364 out.writeInt(0);
8365 }
Bookatzc8c44962017-05-11 12:12:54 -07008366 if (mAggregatedPartialWakelockTimer != null) {
8367 out.writeInt(1);
8368 mAggregatedPartialWakelockTimer.writeToParcel(out, elapsedRealtimeUs);
8369 } else {
8370 out.writeInt(0);
8371 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008372 if (mBluetoothScanTimer != null) {
8373 out.writeInt(1);
8374 mBluetoothScanTimer.writeToParcel(out, elapsedRealtimeUs);
8375 } else {
8376 out.writeInt(0);
8377 }
Bookatzb1f04f32017-05-19 13:57:32 -07008378 if (mBluetoothUnoptimizedScanTimer != null) {
8379 out.writeInt(1);
8380 mBluetoothUnoptimizedScanTimer.writeToParcel(out, elapsedRealtimeUs);
8381 } else {
8382 out.writeInt(0);
8383 }
Bookatz956f36bf2017-04-28 09:48:17 -07008384 if (mBluetoothScanResultCounter != null) {
8385 out.writeInt(1);
8386 mBluetoothScanResultCounter.writeToParcel(out);
8387 } else {
8388 out.writeInt(0);
8389 }
Bookatzb1f04f32017-05-19 13:57:32 -07008390 if (mBluetoothScanResultBgCounter != null) {
8391 out.writeInt(1);
8392 mBluetoothScanResultBgCounter.writeToParcel(out);
8393 } else {
8394 out.writeInt(0);
8395 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07008396 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8397 if (mProcessStateTimer[i] != null) {
8398 out.writeInt(1);
8399 mProcessStateTimer[i].writeToParcel(out, elapsedRealtimeUs);
8400 } else {
8401 out.writeInt(0);
8402 }
8403 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008404 if (mVibratorOnTimer != null) {
8405 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008406 mVibratorOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008407 } else {
8408 out.writeInt(0);
8409 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008410 if (mUserActivityCounters != null) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07008411 out.writeInt(1);
8412 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
8413 mUserActivityCounters[i].writeToParcel(out);
8414 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008415 } else {
8416 out.writeInt(0);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008417 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008418 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008419 out.writeInt(1);
8420 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008421 mNetworkByteActivityCounters[i].writeToParcel(out);
8422 mNetworkPacketActivityCounters[i].writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008423 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08008424 mMobileRadioActiveTime.writeToParcel(out);
8425 mMobileRadioActiveCount.writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008426 } else {
8427 out.writeInt(0);
8428 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008429
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008430 if (mWifiControllerActivity != null) {
8431 out.writeInt(1);
8432 mWifiControllerActivity.writeToParcel(out, 0);
8433 } else {
8434 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07008435 }
8436
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008437 if (mBluetoothControllerActivity != null) {
8438 out.writeInt(1);
8439 mBluetoothControllerActivity.writeToParcel(out, 0);
8440 } else {
8441 out.writeInt(0);
8442 }
8443
8444 if (mModemControllerActivity != null) {
8445 out.writeInt(1);
8446 mModemControllerActivity.writeToParcel(out, 0);
8447 } else {
8448 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07008449 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008450
8451 mUserCpuTime.writeToParcel(out);
8452 mSystemCpuTime.writeToParcel(out);
8453
Sudheer Shankaaf857412017-07-21 00:14:24 -07008454 if (mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008455 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -07008456 out.writeInt(mCpuClusterSpeedTimesUs.length);
8457 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008458 if (cpuSpeeds != null) {
8459 out.writeInt(1);
8460 out.writeInt(cpuSpeeds.length);
8461 for (LongSamplingCounter c : cpuSpeeds) {
8462 if (c != null) {
8463 out.writeInt(1);
8464 c.writeToParcel(out);
8465 } else {
8466 out.writeInt(0);
8467 }
8468 }
8469 } else {
8470 out.writeInt(0);
8471 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008472 }
Adam Lesinski6832f392015-09-05 18:05:40 -07008473 } else {
8474 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008475 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008476
Sudheer Shanka59f5c002017-05-15 10:57:15 -07008477 LongSamplingCounterArray.writeToParcel(out, mCpuFreqTimeMs);
8478 LongSamplingCounterArray.writeToParcel(out, mScreenOffCpuFreqTimeMs);
Mike Ma3d422c32017-10-25 11:08:57 -07008479
8480 mCpuActiveTimeMs.writeToParcel(out);
8481 mCpuClusterTimesMs.writeToParcel(out);
8482
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008483 if (mProcStateTimeMs != null) {
8484 out.writeInt(mProcStateTimeMs.length);
8485 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8486 LongSamplingCounterArray.writeToParcel(out, counters);
8487 }
8488 } else {
8489 out.writeInt(0);
8490 }
8491 if (mProcStateScreenOffTimeMs != null) {
8492 out.writeInt(mProcStateScreenOffTimeMs.length);
8493 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8494 LongSamplingCounterArray.writeToParcel(out, counters);
8495 }
8496 } else {
8497 out.writeInt(0);
8498 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008499
Adam Lesinski5f056f62016-07-14 16:56:08 -07008500 if (mMobileRadioApWakeupCount != null) {
8501 out.writeInt(1);
8502 mMobileRadioApWakeupCount.writeToParcel(out);
8503 } else {
8504 out.writeInt(0);
8505 }
8506
8507 if (mWifiRadioApWakeupCount != null) {
8508 out.writeInt(1);
8509 mWifiRadioApWakeupCount.writeToParcel(out);
8510 } else {
8511 out.writeInt(0);
8512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008513 }
8514
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008515 void readJobCompletionsFromParcelLocked(Parcel in) {
8516 int numJobCompletions = in.readInt();
8517 mJobCompletions.clear();
8518 for (int j = 0; j < numJobCompletions; j++) {
8519 String jobName = in.readString();
8520 int numTypes = in.readInt();
8521 if (numTypes > 0) {
8522 SparseIntArray types = new SparseIntArray();
8523 for (int k = 0; k < numTypes; k++) {
8524 int type = in.readInt();
8525 int count = in.readInt();
8526 types.put(type, count);
8527 }
8528 mJobCompletions.put(jobName, types);
8529 }
8530 }
8531 }
8532
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008533 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase, Parcel in) {
Bookatz867c0d72017-03-07 18:23:42 -08008534 mOnBatteryBackgroundTimeBase.readFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -07008535 mOnBatteryScreenOffBackgroundTimeBase.readFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -08008536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008537 int numWakelocks = in.readInt();
8538 mWakelockStats.clear();
8539 for (int j = 0; j < numWakelocks; j++) {
8540 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008541 Uid.Wakelock wakelock = new Wakelock(mBsi, this);
Bookatz5b5ec322017-05-26 09:40:38 -07008542 wakelock.readFromParcelLocked(
8543 timeBase, screenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase, in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07008544 mWakelockStats.add(wakelockName, wakelock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008545 }
8546
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008547 int numSyncs = in.readInt();
8548 mSyncStats.clear();
8549 for (int j = 0; j < numSyncs; j++) {
8550 String syncName = in.readString();
8551 if (in.readInt() != 0) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008552 mSyncStats.add(syncName, new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
8553 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008554 }
8555 }
8556
8557 int numJobs = in.readInt();
8558 mJobStats.clear();
8559 for (int j = 0; j < numJobs; j++) {
8560 String jobName = in.readString();
8561 if (in.readInt() != 0) {
Bookatzaa4594a2017-03-24 12:39:56 -07008562 mJobStats.add(jobName, new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
8563 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008564 }
8565 }
8566
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008567 readJobCompletionsFromParcelLocked(in);
8568
Amith Yamasani977e11f2018-02-16 11:29:54 -08008569 mJobsDeferredEventCount = new Counter(mBsi.mOnBatteryTimeBase, in);
8570 mJobsDeferredCount = new Counter(mBsi.mOnBatteryTimeBase, in);
8571 mJobsFreshnessTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8572 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
8573 mJobsFreshnessBuckets[i] = Counter.readCounterFromParcel(mBsi.mOnBatteryTimeBase,
8574 in);
8575 }
8576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008577 int numSensors = in.readInt();
8578 mSensorStats.clear();
8579 for (int k = 0; k < numSensors; k++) {
8580 int sensorNumber = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008581 Uid.Sensor sensor = new Sensor(mBsi, this, sensorNumber);
Bookatz867c0d72017-03-07 18:23:42 -08008582 sensor.readFromParcelLocked(mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
8583 in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008584 mSensorStats.put(sensorNumber, sensor);
8585 }
8586
8587 int numProcs = in.readInt();
8588 mProcessStats.clear();
8589 for (int k = 0; k < numProcs; k++) {
8590 String processName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008591 Uid.Proc proc = new Proc(mBsi, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008592 proc.readFromParcelLocked(in);
8593 mProcessStats.put(processName, proc);
8594 }
8595
8596 int numPkgs = in.readInt();
8597 mPackageStats.clear();
8598 for (int l = 0; l < numPkgs; l++) {
8599 String packageName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008600 Uid.Pkg pkg = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008601 pkg.readFromParcelLocked(in);
8602 mPackageStats.put(packageName, pkg);
8603 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008604
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008605 mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008606 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008607 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
8608 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008609 } else {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008610 mWifiRunningTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008611 }
8612 mFullWifiLockOut = false;
8613 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008614 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
8615 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008616 } else {
8617 mFullWifiLockTimer = null;
8618 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008619 mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008620 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08008621 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
8622 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
8623 in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008624 } else {
Nick Pelly6ccaa542012-06-15 15:22:47 -07008625 mWifiScanTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008626 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008627 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
8628 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8629 if (in.readInt() != 0) {
8630 makeWifiBatchedScanBin(i, in);
8631 } else {
8632 mWifiBatchedScanTimer[i] = null;
8633 }
8634 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008635 mWifiMulticastEnabled = false;
8636 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008637 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_MULTICAST_ENABLED,
8638 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008639 } else {
8640 mWifiMulticastTimer = null;
8641 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008642 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008643 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
8644 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008645 } else {
8646 mAudioTurnedOnTimer = null;
8647 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008648 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008649 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
8650 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008651 } else {
8652 mVideoTurnedOnTimer = null;
8653 }
8654 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008655 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8656 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008657 } else {
8658 mFlashlightTurnedOnTimer = null;
8659 }
8660 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008661 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
8662 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008663 } else {
8664 mCameraTurnedOnTimer = null;
8665 }
8666 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008667 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8668 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008669 } else {
8670 mForegroundActivityTimer = null;
8671 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008672 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008673 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8674 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase, in);
8675 } else {
8676 mForegroundServiceTimer = null;
8677 }
8678 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -07008679 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
8680 AGGREGATED_WAKE_TYPE_PARTIAL, null,
8681 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase,
8682 in);
8683 } else {
8684 mAggregatedPartialWakelockTimer = null;
8685 }
8686 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08008687 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
8688 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
8689 mOnBatteryBackgroundTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008690 } else {
8691 mBluetoothScanTimer = null;
8692 }
Bookatz956f36bf2017-04-28 09:48:17 -07008693 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -07008694 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
8695 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
8696 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in);
8697 } else {
8698 mBluetoothUnoptimizedScanTimer = null;
8699 }
8700 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -07008701 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase, in);
8702 } else {
8703 mBluetoothScanResultCounter = null;
8704 }
Bookatzb1f04f32017-05-19 13:57:32 -07008705 if (in.readInt() != 0) {
8706 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase, in);
8707 } else {
8708 mBluetoothScanResultBgCounter = null;
8709 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08008710 mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07008711 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8712 if (in.readInt() != 0) {
8713 makeProcessState(i, in);
8714 } else {
8715 mProcessStateTimer[i] = null;
8716 }
8717 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008718 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008719 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
8720 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008721 } else {
8722 mVibratorOnTimer = null;
8723 }
8724 if (in.readInt() != 0) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07008725 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
8726 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08008727 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008728 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008729 } else {
8730 mUserActivityCounters = null;
Dianne Hackborn617f8772009-03-31 15:04:46 -07008731 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008732 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008733 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
8734 mNetworkPacketActivityCounters
8735 = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008736 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008737 mNetworkByteActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08008738 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008739 mNetworkPacketActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08008740 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008741 }
Joe Onoratoabded112016-02-08 16:49:39 -08008742 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8743 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008744 } else {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008745 mNetworkByteActivityCounters = null;
8746 mNetworkPacketActivityCounters = null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008747 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008748
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008749 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008750 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008751 NUM_WIFI_TX_LEVELS, in);
8752 } else {
8753 mWifiControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07008754 }
8755
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008756 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008757 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008758 NUM_BT_TX_LEVELS, in);
8759 } else {
8760 mBluetoothControllerActivity = null;
8761 }
8762
8763 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008764 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008765 ModemActivityInfo.TX_POWER_LEVELS, in);
8766 } else {
8767 mModemControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07008768 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008769
Joe Onoratoabded112016-02-08 16:49:39 -08008770 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8771 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008772
Adam Lesinski6832f392015-09-05 18:05:40 -07008773 if (in.readInt() != 0) {
8774 int numCpuClusters = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008775 if (mBsi.mPowerProfile != null && mBsi.mPowerProfile.getNumCpuClusters() != numCpuClusters) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008776 throw new ParcelFormatException("Incompatible number of cpu clusters");
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008777 }
Adam Lesinski6832f392015-09-05 18:05:40 -07008778
Sudheer Shankaaf857412017-07-21 00:14:24 -07008779 mCpuClusterSpeedTimesUs = new LongSamplingCounter[numCpuClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -07008780 for (int cluster = 0; cluster < numCpuClusters; cluster++) {
8781 if (in.readInt() != 0) {
8782 int numSpeeds = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008783 if (mBsi.mPowerProfile != null &&
8784 mBsi.mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != numSpeeds) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008785 throw new ParcelFormatException("Incompatible number of cpu speeds");
8786 }
8787
8788 final LongSamplingCounter[] cpuSpeeds = new LongSamplingCounter[numSpeeds];
Sudheer Shankaaf857412017-07-21 00:14:24 -07008789 mCpuClusterSpeedTimesUs[cluster] = cpuSpeeds;
Adam Lesinski6832f392015-09-05 18:05:40 -07008790 for (int speed = 0; speed < numSpeeds; speed++) {
8791 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008792 cpuSpeeds[speed] = new LongSamplingCounter(
8793 mBsi.mOnBatteryTimeBase, in);
Adam Lesinski6832f392015-09-05 18:05:40 -07008794 }
8795 }
Adam Lesinskia57a5402015-09-28 10:21:33 -07008796 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008797 mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -07008798 }
8799 }
8800 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008801 mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008802 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008803
Sudheer Shanka59f5c002017-05-15 10:57:15 -07008804 mCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(in, mBsi.mOnBatteryTimeBase);
8805 mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(
8806 in, mBsi.mOnBatteryScreenOffTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008807
Mike Ma3d422c32017-10-25 11:08:57 -07008808 mCpuActiveTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8809 mCpuClusterTimesMs = new LongSamplingCounterArray(mBsi.mOnBatteryTimeBase, in);
8810
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008811 int length = in.readInt();
8812 if (length == NUM_PROCESS_STATE) {
8813 mProcStateTimeMs = new LongSamplingCounterArray[length];
8814 for (int procState = 0; procState < length; ++procState) {
8815 mProcStateTimeMs[procState] = LongSamplingCounterArray.readFromParcel(
8816 in, mBsi.mOnBatteryTimeBase);
8817 }
8818 } else {
8819 mProcStateTimeMs = null;
8820 }
8821 length = in.readInt();
8822 if (length == NUM_PROCESS_STATE) {
8823 mProcStateScreenOffTimeMs = new LongSamplingCounterArray[length];
8824 for (int procState = 0; procState < length; ++procState) {
8825 mProcStateScreenOffTimeMs[procState] = LongSamplingCounterArray.readFromParcel(
8826 in, mBsi.mOnBatteryScreenOffTimeBase);
8827 }
8828 } else {
8829 mProcStateScreenOffTimeMs = null;
8830 }
8831
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008832 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07008833 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8834 } else {
8835 mMobileRadioApWakeupCount = null;
8836 }
8837
8838 if (in.readInt() != 0) {
8839 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8840 } else {
8841 mWifiRadioApWakeupCount = null;
8842 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008843 }
8844
Amith Yamasani977e11f2018-02-16 11:29:54 -08008845 public void noteJobsDeferredLocked(int numDeferred, long sinceLast) {
8846 mJobsDeferredEventCount.addAtomic(1);
8847 mJobsDeferredCount.addAtomic(numDeferred);
8848 if (sinceLast != 0) {
8849 // Add the total time, which can be divided by the event count to get an average
8850 mJobsFreshnessTimeMs.addCountLocked(sinceLast);
8851 // Also keep track of how many times there were in these different buckets.
8852 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
8853 if (sinceLast < JOB_FRESHNESS_BUCKETS[i]) {
8854 if (mJobsFreshnessBuckets[i] == null) {
8855 mJobsFreshnessBuckets[i] = new Counter(
8856 mBsi.mOnBatteryTimeBase);
8857 }
8858 mJobsFreshnessBuckets[i].addAtomic(1);
8859 break;
8860 }
8861 }
8862 }
8863 }
8864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008865 /**
8866 * The statistics associated with a particular wake lock.
8867 */
Joe Onoratoabded112016-02-08 16:49:39 -08008868 public static class Wakelock extends BatteryStats.Uid.Wakelock {
8869 /**
8870 * BatteryStatsImpl that we are associated with.
8871 */
8872 protected BatteryStatsImpl mBsi;
8873
8874 /**
8875 * BatteryStatsImpl that we are associated with.
8876 */
8877 protected Uid mUid;
8878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008879 /**
8880 * How long (in ms) this uid has been keeping the device partially awake.
Bookatz5b5ec322017-05-26 09:40:38 -07008881 * 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 -08008882 */
Bookatz5b5ec322017-05-26 09:40:38 -07008883 DualTimer mTimerPartial;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008884
8885 /**
8886 * How long (in ms) this uid has been keeping the device fully awake.
8887 */
Evan Millarc64edde2009-04-18 12:26:32 -07008888 StopwatchTimer mTimerFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008889
8890 /**
8891 * How long (in ms) this uid has had a window keeping the device awake.
8892 */
Evan Millarc64edde2009-04-18 12:26:32 -07008893 StopwatchTimer mTimerWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008894
8895 /**
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008896 * How long (in ms) this uid has had a draw wake lock.
Adam Lesinski9425fe22015-06-19 12:02:13 -07008897 */
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008898 StopwatchTimer mTimerDraw;
Adam Lesinski9425fe22015-06-19 12:02:13 -07008899
Joe Onoratoabded112016-02-08 16:49:39 -08008900 public Wakelock(BatteryStatsImpl bsi, Uid uid) {
8901 mBsi = bsi;
8902 mUid = uid;
8903 }
8904
Adam Lesinski9425fe22015-06-19 12:02:13 -07008905 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008906 * Reads a possibly null Timer from a Parcel. The timer is associated with the
8907 * proper timer pool from the given BatteryStatsImpl object.
8908 *
8909 * @param in the Parcel to be read from.
8910 * return a new Timer, or null.
8911 */
Joe Onorato92fd23f2016-07-25 11:18:42 -07008912 private StopwatchTimer readStopwatchTimerFromParcel(int type,
8913 ArrayList<StopwatchTimer> pool, TimeBase timeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008914 if (in.readInt() == 0) {
8915 return null;
8916 }
8917
Joe Onoratoabded112016-02-08 16:49:39 -08008918 return new StopwatchTimer(mBsi.mClocks, mUid, type, pool, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008919 }
8920
Joe Onorato92fd23f2016-07-25 11:18:42 -07008921 /**
8922 * Reads a possibly null Timer from a Parcel. The timer is associated with the
8923 * proper timer pool from the given BatteryStatsImpl object.
8924 *
8925 * @param in the Parcel to be read from.
8926 * return a new Timer, or null.
8927 */
Bookatz5b5ec322017-05-26 09:40:38 -07008928 private DualTimer readDualTimerFromParcel(int type, ArrayList<StopwatchTimer> pool,
8929 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07008930 if (in.readInt() == 0) {
8931 return null;
8932 }
8933
Bookatz5b5ec322017-05-26 09:40:38 -07008934 return new DualTimer(mBsi.mClocks, mUid, type, pool, timeBase, bgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07008935 }
8936
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008937 boolean reset() {
8938 boolean wlactive = false;
8939 if (mTimerFull != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008940 wlactive |= !mTimerFull.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008941 }
8942 if (mTimerPartial != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008943 wlactive |= !mTimerPartial.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008944 }
8945 if (mTimerWindow != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008946 wlactive |= !mTimerWindow.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008947 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008948 if (mTimerDraw != null) {
8949 wlactive |= !mTimerDraw.reset(false);
Adam Lesinski9425fe22015-06-19 12:02:13 -07008950 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008951 if (!wlactive) {
8952 if (mTimerFull != null) {
8953 mTimerFull.detach();
8954 mTimerFull = null;
8955 }
8956 if (mTimerPartial != null) {
8957 mTimerPartial.detach();
8958 mTimerPartial = null;
8959 }
8960 if (mTimerWindow != null) {
8961 mTimerWindow.detach();
8962 mTimerWindow = null;
8963 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008964 if (mTimerDraw != null) {
8965 mTimerDraw.detach();
8966 mTimerDraw = null;
Adam Lesinski9425fe22015-06-19 12:02:13 -07008967 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008968 }
8969 return !wlactive;
8970 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008971
Bookatz5b5ec322017-05-26 09:40:38 -07008972 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase,
8973 TimeBase screenOffBgTimeBase, Parcel in) {
8974 mTimerPartial = readDualTimerFromParcel(WAKE_TYPE_PARTIAL,
8975 mBsi.mPartialTimers, screenOffTimeBase, screenOffBgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07008976 mTimerFull = readStopwatchTimerFromParcel(WAKE_TYPE_FULL,
8977 mBsi.mFullTimers, timeBase, in);
8978 mTimerWindow = readStopwatchTimerFromParcel(WAKE_TYPE_WINDOW,
8979 mBsi.mWindowTimers, timeBase, in);
8980 mTimerDraw = readStopwatchTimerFromParcel(WAKE_TYPE_DRAW,
8981 mBsi.mDrawTimers, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008982 }
8983
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008984 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
8985 Timer.writeTimerToParcel(out, mTimerPartial, elapsedRealtimeUs);
8986 Timer.writeTimerToParcel(out, mTimerFull, elapsedRealtimeUs);
8987 Timer.writeTimerToParcel(out, mTimerWindow, elapsedRealtimeUs);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008988 Timer.writeTimerToParcel(out, mTimerDraw, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008989 }
8990
8991 @Override
8992 public Timer getWakeTime(int type) {
8993 switch (type) {
8994 case WAKE_TYPE_FULL: return mTimerFull;
8995 case WAKE_TYPE_PARTIAL: return mTimerPartial;
8996 case WAKE_TYPE_WINDOW: return mTimerWindow;
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008997 case WAKE_TYPE_DRAW: return mTimerDraw;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008998 default: throw new IllegalArgumentException("type = " + type);
8999 }
9000 }
9001 }
9002
Joe Onoratoabded112016-02-08 16:49:39 -08009003 public static class Sensor extends BatteryStats.Uid.Sensor {
9004 /**
9005 * BatteryStatsImpl that we are associated with.
9006 */
9007 protected BatteryStatsImpl mBsi;
9008
9009 /**
Bookatz867c0d72017-03-07 18:23:42 -08009010 * Uid that we are associated with.
Joe Onoratoabded112016-02-08 16:49:39 -08009011 */
9012 protected Uid mUid;
9013
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009014 final int mHandle;
Bookatz867c0d72017-03-07 18:23:42 -08009015 DualTimer mTimer;
Amith Yamasaniab9ad192016-12-06 12:46:59 -08009016
Joe Onoratoabded112016-02-08 16:49:39 -08009017 public Sensor(BatteryStatsImpl bsi, Uid uid, int handle) {
9018 mBsi = bsi;
9019 mUid = uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009020 mHandle = handle;
9021 }
9022
Bookatz867c0d72017-03-07 18:23:42 -08009023 private DualTimer readTimersFromParcel(
9024 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009025 if (in.readInt() == 0) {
9026 return null;
9027 }
9028
Joe Onoratoabded112016-02-08 16:49:39 -08009029 ArrayList<StopwatchTimer> pool = mBsi.mSensorTimers.get(mHandle);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009030 if (pool == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07009031 pool = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08009032 mBsi.mSensorTimers.put(mHandle, pool);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009033 }
Bookatz867c0d72017-03-07 18:23:42 -08009034 return new DualTimer(mBsi.mClocks, mUid, 0, pool, timeBase, bgTimeBase, in);
Amith Yamasaniab9ad192016-12-06 12:46:59 -08009035 }
9036
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009037 boolean reset() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009038 if (mTimer.reset(true)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009039 mTimer = null;
9040 return true;
9041 }
9042 return false;
9043 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009044
Bookatz867c0d72017-03-07 18:23:42 -08009045 void readFromParcelLocked(TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
9046 mTimer = readTimersFromParcel(timeBase, bgTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009047 }
9048
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009049 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07009050 Timer.writeTimerToParcel(out, mTimer, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009051 }
9052
9053 @Override
9054 public Timer getSensorTime() {
Bookatzaa4594a2017-03-24 12:39:56 -07009055 return mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009056 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009057
9058 @Override
Bookatz867c0d72017-03-07 18:23:42 -08009059 public Timer getSensorBackgroundTime() {
9060 if (mTimer == null) {
9061 return null;
9062 }
9063 return mTimer.getSubTimer();
Amith Yamasaniab9ad192016-12-06 12:46:59 -08009064 }
9065
9066 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009067 public int getHandle() {
9068 return mHandle;
9069 }
9070 }
9071
9072 /**
9073 * The statistics associated with a particular process.
9074 */
Joe Onoratoabded112016-02-08 16:49:39 -08009075 public static class Proc extends BatteryStats.Uid.Proc implements TimeBaseObs {
9076 /**
9077 * BatteryStatsImpl that we are associated with.
9078 */
9079 protected BatteryStatsImpl mBsi;
9080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009081 /**
Dianne Hackborncd0e3352014-08-07 17:08:09 -07009082 * The name of this process.
9083 */
9084 final String mName;
9085
9086 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -08009087 * Remains true until removed from the stats.
9088 */
9089 boolean mActive = true;
9090
9091 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07009092 * Total time (in ms) spent executing in user code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009093 */
9094 long mUserTime;
9095
9096 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07009097 * Total time (in ms) spent executing in kernel code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009098 */
9099 long mSystemTime;
9100
9101 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07009102 * Amount of time (in ms) the process was running in the foreground.
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009103 */
9104 long mForegroundTime;
9105
9106 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009107 * Number of times the process has been started.
9108 */
9109 int mStarts;
9110
9111 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009112 * Number of times the process has crashed.
9113 */
9114 int mNumCrashes;
9115
9116 /**
9117 * Number of times the process has had an ANR.
9118 */
9119 int mNumAnrs;
9120
9121 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009122 * The amount of user time loaded from a previous save.
9123 */
9124 long mLoadedUserTime;
9125
9126 /**
9127 * The amount of system time loaded from a previous save.
9128 */
9129 long mLoadedSystemTime;
9130
9131 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009132 * The amount of foreground time loaded from a previous save.
9133 */
9134 long mLoadedForegroundTime;
9135
9136 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009137 * The number of times the process has started from a previous save.
9138 */
9139 int mLoadedStarts;
9140
9141 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009142 * Number of times the process has crashed from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009143 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009144 int mLoadedNumCrashes;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009145
9146 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009147 * Number of times the process has had an ANR from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009148 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009149 int mLoadedNumAnrs;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009150
9151 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009152 * The amount of user time when last unplugged.
9153 */
9154 long mUnpluggedUserTime;
9155
9156 /**
9157 * The amount of system time when last unplugged.
9158 */
9159 long mUnpluggedSystemTime;
9160
9161 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009162 * The amount of foreground time since unplugged.
9163 */
9164 long mUnpluggedForegroundTime;
9165
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009166 /**
9167 * The number of times the process has started before unplugged.
9168 */
9169 int mUnpluggedStarts;
9170
Dianne Hackborn61659e52014-07-09 16:13:01 -07009171 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009172 * Number of times the process has crashed before unplugged.
9173 */
9174 int mUnpluggedNumCrashes;
9175
9176 /**
9177 * Number of times the process has had an ANR before unplugged.
9178 */
9179 int mUnpluggedNumAnrs;
9180
Dianne Hackborn287952c2010-09-22 22:34:31 -07009181 ArrayList<ExcessivePower> mExcessivePower;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009182
Joe Onoratoabded112016-02-08 16:49:39 -08009183 public Proc(BatteryStatsImpl bsi, String name) {
9184 mBsi = bsi;
Dianne Hackborncd0e3352014-08-07 17:08:09 -07009185 mName = name;
Joe Onoratoabded112016-02-08 16:49:39 -08009186 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009187 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07009188
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009189 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009190 mUnpluggedUserTime = mUserTime;
9191 mUnpluggedSystemTime = mSystemTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009192 mUnpluggedForegroundTime = mForegroundTime;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009193 mUnpluggedStarts = mStarts;
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009194 mUnpluggedNumCrashes = mNumCrashes;
9195 mUnpluggedNumAnrs = mNumAnrs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009196 }
9197
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009198 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009199 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009200
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009201 void detach() {
Dianne Hackborn099bc622014-01-22 13:39:16 -08009202 mActive = false;
Joe Onoratoabded112016-02-08 16:49:39 -08009203 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009204 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009205
Dianne Hackborn287952c2010-09-22 22:34:31 -07009206 public int countExcessivePowers() {
9207 return mExcessivePower != null ? mExcessivePower.size() : 0;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009208 }
9209
Dianne Hackborn287952c2010-09-22 22:34:31 -07009210 public ExcessivePower getExcessivePower(int i) {
9211 if (mExcessivePower != null) {
9212 return mExcessivePower.get(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009213 }
9214 return null;
9215 }
9216
Dianne Hackborn287952c2010-09-22 22:34:31 -07009217 public void addExcessiveCpu(long overTime, long usedTime) {
9218 if (mExcessivePower == null) {
9219 mExcessivePower = new ArrayList<ExcessivePower>();
9220 }
9221 ExcessivePower ew = new ExcessivePower();
9222 ew.type = ExcessivePower.TYPE_CPU;
9223 ew.overTime = overTime;
9224 ew.usedTime = usedTime;
9225 mExcessivePower.add(ew);
9226 }
9227
9228 void writeExcessivePowerToParcelLocked(Parcel out) {
9229 if (mExcessivePower == null) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009230 out.writeInt(0);
9231 return;
9232 }
9233
Dianne Hackborn287952c2010-09-22 22:34:31 -07009234 final int N = mExcessivePower.size();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009235 out.writeInt(N);
9236 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009237 ExcessivePower ew = mExcessivePower.get(i);
9238 out.writeInt(ew.type);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009239 out.writeLong(ew.overTime);
9240 out.writeLong(ew.usedTime);
9241 }
9242 }
9243
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009244 void readExcessivePowerFromParcelLocked(Parcel in) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009245 final int N = in.readInt();
9246 if (N == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009247 mExcessivePower = null;
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009248 return;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009249 }
9250
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08009251 if (N > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009252 throw new ParcelFormatException(
9253 "File corrupt: too many excessive power entries " + N);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08009254 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009255
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009256 mExcessivePower = new ArrayList<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009257 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009258 ExcessivePower ew = new ExcessivePower();
9259 ew.type = in.readInt();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009260 ew.overTime = in.readLong();
9261 ew.usedTime = in.readLong();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009262 mExcessivePower.add(ew);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009263 }
9264 }
9265
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009266 void writeToParcelLocked(Parcel out) {
9267 out.writeLong(mUserTime);
9268 out.writeLong(mSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009269 out.writeLong(mForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009270 out.writeInt(mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009271 out.writeInt(mNumCrashes);
9272 out.writeInt(mNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009273 out.writeLong(mLoadedUserTime);
9274 out.writeLong(mLoadedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009275 out.writeLong(mLoadedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009276 out.writeInt(mLoadedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009277 out.writeInt(mLoadedNumCrashes);
9278 out.writeInt(mLoadedNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009279 out.writeLong(mUnpluggedUserTime);
9280 out.writeLong(mUnpluggedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009281 out.writeLong(mUnpluggedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009282 out.writeInt(mUnpluggedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009283 out.writeInt(mUnpluggedNumCrashes);
9284 out.writeInt(mUnpluggedNumAnrs);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009285 writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009286 }
9287
9288 void readFromParcelLocked(Parcel in) {
9289 mUserTime = in.readLong();
9290 mSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009291 mForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009292 mStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009293 mNumCrashes = in.readInt();
9294 mNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009295 mLoadedUserTime = in.readLong();
9296 mLoadedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009297 mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009298 mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009299 mLoadedNumCrashes = in.readInt();
9300 mLoadedNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009301 mUnpluggedUserTime = in.readLong();
9302 mUnpluggedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009303 mUnpluggedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009304 mUnpluggedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009305 mUnpluggedNumCrashes = in.readInt();
9306 mUnpluggedNumAnrs = in.readInt();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009307 readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009308 }
9309
Adam Lesinski06af1fa2015-05-05 17:35:35 -07009310 public void addCpuTimeLocked(int utime, int stime) {
Sudheer Shankac57729a2018-02-09 15:44:42 -08009311 addCpuTimeLocked(utime, stime, mBsi.mOnBatteryTimeBase.isRunning());
9312 }
9313
9314 public void addCpuTimeLocked(int utime, int stime, boolean isRunning) {
9315 if (isRunning) {
9316 mUserTime += utime;
9317 mSystemTime += stime;
9318 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009319 }
9320
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009321 public void addForegroundTimeLocked(long ttime) {
9322 mForegroundTime += ttime;
9323 }
9324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009325 public void incStartsLocked() {
9326 mStarts++;
9327 }
9328
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009329 public void incNumCrashesLocked() {
9330 mNumCrashes++;
9331 }
9332
9333 public void incNumAnrsLocked() {
9334 mNumAnrs++;
9335 }
9336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009337 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -08009338 public boolean isActive() {
9339 return mActive;
9340 }
9341
9342 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009343 public long getUserTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009344 long val = mUserTime;
9345 if (which == STATS_CURRENT) {
9346 val -= mLoadedUserTime;
9347 } else if (which == STATS_SINCE_UNPLUGGED) {
9348 val -= mUnpluggedUserTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009349 }
9350 return val;
9351 }
9352
9353 @Override
9354 public long getSystemTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009355 long val = mSystemTime;
9356 if (which == STATS_CURRENT) {
9357 val -= mLoadedSystemTime;
9358 } else if (which == STATS_SINCE_UNPLUGGED) {
9359 val -= mUnpluggedSystemTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009360 }
9361 return val;
9362 }
9363
9364 @Override
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009365 public long getForegroundTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009366 long val = mForegroundTime;
9367 if (which == STATS_CURRENT) {
9368 val -= mLoadedForegroundTime;
9369 } else if (which == STATS_SINCE_UNPLUGGED) {
9370 val -= mUnpluggedForegroundTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009371 }
9372 return val;
9373 }
9374
9375 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009376 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009377 int val = mStarts;
9378 if (which == STATS_CURRENT) {
9379 val -= mLoadedStarts;
9380 } else if (which == STATS_SINCE_UNPLUGGED) {
9381 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009382 }
9383 return val;
9384 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07009385
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009386 @Override
9387 public int getNumCrashes(int which) {
9388 int val = mNumCrashes;
9389 if (which == STATS_CURRENT) {
9390 val -= mLoadedNumCrashes;
9391 } else if (which == STATS_SINCE_UNPLUGGED) {
9392 val -= mUnpluggedNumCrashes;
9393 }
9394 return val;
9395 }
9396
9397 @Override
9398 public int getNumAnrs(int which) {
9399 int val = mNumAnrs;
9400 if (which == STATS_CURRENT) {
9401 val -= mLoadedNumAnrs;
9402 } else if (which == STATS_SINCE_UNPLUGGED) {
9403 val -= mUnpluggedNumAnrs;
9404 }
9405 return val;
9406 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009407 }
9408
9409 /**
9410 * The statistics associated with a particular package.
9411 */
Joe Onoratoabded112016-02-08 16:49:39 -08009412 public static class Pkg extends BatteryStats.Uid.Pkg implements TimeBaseObs {
9413 /**
9414 * BatteryStatsImpl that we are associated with.
9415 */
9416 protected BatteryStatsImpl mBsi;
9417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009418 /**
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009419 * Number of times wakeup alarms have occurred for this app.
Bookatz98d4d5c2017-08-01 19:07:54 -07009420 * On screen-off timebase starting in report v25.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009421 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009422 ArrayMap<String, Counter> mWakeupAlarms = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009423
9424 /**
9425 * The statics we have collected for this package's services.
9426 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009427 final ArrayMap<String, Serv> mServiceStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009428
Joe Onoratoabded112016-02-08 16:49:39 -08009429 public Pkg(BatteryStatsImpl bsi) {
9430 mBsi = bsi;
9431 mBsi.mOnBatteryScreenOffTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009432 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009433
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009434 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009435 }
9436
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009437 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009438 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009439
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009440 void detach() {
Joe Onoratoabded112016-02-08 16:49:39 -08009441 mBsi.mOnBatteryScreenOffTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009442 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009444 void readFromParcelLocked(Parcel in) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009445 int numWA = in.readInt();
9446 mWakeupAlarms.clear();
9447 for (int i=0; i<numWA; i++) {
9448 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -07009449 mWakeupAlarms.put(tag, new Counter(mBsi.mOnBatteryScreenOffTimeBase, in));
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009450 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009451
9452 int numServs = in.readInt();
9453 mServiceStats.clear();
9454 for (int m = 0; m < numServs; m++) {
9455 String serviceName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08009456 Uid.Pkg.Serv serv = new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009457 mServiceStats.put(serviceName, serv);
9458
9459 serv.readFromParcelLocked(in);
9460 }
9461 }
9462
9463 void writeToParcelLocked(Parcel out) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009464 int numWA = mWakeupAlarms.size();
9465 out.writeInt(numWA);
9466 for (int i=0; i<numWA; i++) {
9467 out.writeString(mWakeupAlarms.keyAt(i));
9468 mWakeupAlarms.valueAt(i).writeToParcel(out);
9469 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009470
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009471 final int NS = mServiceStats.size();
9472 out.writeInt(NS);
9473 for (int i=0; i<NS; i++) {
9474 out.writeString(mServiceStats.keyAt(i));
9475 Uid.Pkg.Serv serv = mServiceStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009476 serv.writeToParcelLocked(out);
9477 }
9478 }
9479
9480 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009481 public ArrayMap<String, ? extends BatteryStats.Counter> getWakeupAlarmStats() {
9482 return mWakeupAlarms;
9483 }
9484
9485 public void noteWakeupAlarmLocked(String tag) {
9486 Counter c = mWakeupAlarms.get(tag);
9487 if (c == null) {
Bookatz98d4d5c2017-08-01 19:07:54 -07009488 c = new Counter(mBsi.mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009489 mWakeupAlarms.put(tag, c);
9490 }
9491 c.stepAtomic();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009492 }
9493
9494 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009495 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg.Serv> getServiceStats() {
9496 return mServiceStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009497 }
9498
9499 /**
9500 * The statistics associated with a particular service.
9501 */
Joe Onoratoabded112016-02-08 16:49:39 -08009502 public static class Serv extends BatteryStats.Uid.Pkg.Serv implements TimeBaseObs {
9503 /**
9504 * BatteryStatsImpl that we are associated with.
9505 */
9506 protected BatteryStatsImpl mBsi;
9507
9508 /**
9509 * The android package in which this service resides.
9510 */
9511 protected Pkg mPkg;
9512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009513 /**
9514 * Total time (ms in battery uptime) the service has been left started.
9515 */
Joe Onoratoabded112016-02-08 16:49:39 -08009516 protected long mStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009517
9518 /**
9519 * If service has been started and not yet stopped, this is
9520 * when it was started.
9521 */
Joe Onoratoabded112016-02-08 16:49:39 -08009522 protected long mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009523
9524 /**
9525 * True if we are currently running.
9526 */
Joe Onoratoabded112016-02-08 16:49:39 -08009527 protected boolean mRunning;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009528
9529 /**
9530 * Total number of times startService() has been called.
9531 */
Joe Onoratoabded112016-02-08 16:49:39 -08009532 protected int mStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009533
9534 /**
9535 * Total time (ms in battery uptime) the service has been left launched.
9536 */
Joe Onoratoabded112016-02-08 16:49:39 -08009537 protected long mLaunchedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009538
9539 /**
9540 * If service has been launched and not yet exited, this is
9541 * when it was launched (ms in battery uptime).
9542 */
Joe Onoratoabded112016-02-08 16:49:39 -08009543 protected long mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009544
9545 /**
9546 * True if we are currently launched.
9547 */
Joe Onoratoabded112016-02-08 16:49:39 -08009548 protected boolean mLaunched;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009549
9550 /**
9551 * Total number times the service has been launched.
9552 */
Joe Onoratoabded112016-02-08 16:49:39 -08009553 protected int mLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009554
9555 /**
9556 * The amount of time spent started loaded from a previous save
9557 * (ms in battery uptime).
9558 */
Joe Onoratoabded112016-02-08 16:49:39 -08009559 protected long mLoadedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009560
9561 /**
9562 * The number of starts loaded from a previous save.
9563 */
Joe Onoratoabded112016-02-08 16:49:39 -08009564 protected int mLoadedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009565
9566 /**
9567 * The number of launches loaded from a previous save.
9568 */
Joe Onoratoabded112016-02-08 16:49:39 -08009569 protected int mLoadedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009570
9571 /**
9572 * The amount of time spent started as of the last run (ms
9573 * in battery uptime).
9574 */
Joe Onoratoabded112016-02-08 16:49:39 -08009575 protected long mLastStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009576
9577 /**
9578 * The number of starts as of the last run.
9579 */
Joe Onoratoabded112016-02-08 16:49:39 -08009580 protected int mLastStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009581
9582 /**
9583 * The number of launches as of the last run.
9584 */
Joe Onoratoabded112016-02-08 16:49:39 -08009585 protected int mLastLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009586
9587 /**
9588 * The amount of time spent started when last unplugged (ms
9589 * in battery uptime).
9590 */
Joe Onoratoabded112016-02-08 16:49:39 -08009591 protected long mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009592
9593 /**
9594 * The number of starts when last unplugged.
9595 */
Joe Onoratoabded112016-02-08 16:49:39 -08009596 protected int mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009597
9598 /**
9599 * The number of launches when last unplugged.
9600 */
Joe Onoratoabded112016-02-08 16:49:39 -08009601 protected int mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009602
Joe Onoratoabded112016-02-08 16:49:39 -08009603 /**
9604 * Construct a Serv. Also adds it to the on-battery time base as a listener.
9605 */
9606 public Serv(BatteryStatsImpl bsi) {
9607 mBsi = bsi;
9608 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009609 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009610
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009611 public void onTimeStarted(long elapsedRealtime, long baseUptime,
9612 long baseRealtime) {
9613 mUnpluggedStartTime = getStartTimeToNowLocked(baseUptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009614 mUnpluggedStarts = mStarts;
9615 mUnpluggedLaunches = mLaunches;
9616 }
9617
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009618 public void onTimeStopped(long elapsedRealtime, long baseUptime,
9619 long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009620 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009621
Joe Onoratoabded112016-02-08 16:49:39 -08009622 /**
9623 * Remove this Serv as a listener from the time base.
9624 */
9625 public void detach() {
9626 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009627 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009628
Joe Onoratoabded112016-02-08 16:49:39 -08009629 public void readFromParcelLocked(Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009630 mStartTime = in.readLong();
9631 mRunningSince = in.readLong();
9632 mRunning = in.readInt() != 0;
9633 mStarts = in.readInt();
9634 mLaunchedTime = in.readLong();
9635 mLaunchedSince = in.readLong();
9636 mLaunched = in.readInt() != 0;
9637 mLaunches = in.readInt();
9638 mLoadedStartTime = in.readLong();
9639 mLoadedStarts = in.readInt();
9640 mLoadedLaunches = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07009641 mLastStartTime = 0;
9642 mLastStarts = 0;
9643 mLastLaunches = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009644 mUnpluggedStartTime = in.readLong();
9645 mUnpluggedStarts = in.readInt();
9646 mUnpluggedLaunches = in.readInt();
9647 }
9648
Joe Onoratoabded112016-02-08 16:49:39 -08009649 public void writeToParcelLocked(Parcel out) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009650 out.writeLong(mStartTime);
9651 out.writeLong(mRunningSince);
9652 out.writeInt(mRunning ? 1 : 0);
9653 out.writeInt(mStarts);
9654 out.writeLong(mLaunchedTime);
9655 out.writeLong(mLaunchedSince);
9656 out.writeInt(mLaunched ? 1 : 0);
9657 out.writeInt(mLaunches);
9658 out.writeLong(mLoadedStartTime);
9659 out.writeInt(mLoadedStarts);
9660 out.writeInt(mLoadedLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009661 out.writeLong(mUnpluggedStartTime);
9662 out.writeInt(mUnpluggedStarts);
9663 out.writeInt(mUnpluggedLaunches);
9664 }
9665
Joe Onoratoabded112016-02-08 16:49:39 -08009666 public long getLaunchTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009667 if (!mLaunched) return mLaunchedTime;
9668 return mLaunchedTime + batteryUptime - mLaunchedSince;
9669 }
9670
Joe Onoratoabded112016-02-08 16:49:39 -08009671 public long getStartTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009672 if (!mRunning) return mStartTime;
9673 return mStartTime + batteryUptime - mRunningSince;
9674 }
9675
9676 public void startLaunchedLocked() {
9677 if (!mLaunched) {
9678 mLaunches++;
Joe Onoratoabded112016-02-08 16:49:39 -08009679 mLaunchedSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009680 mLaunched = true;
9681 }
9682 }
9683
9684 public void stopLaunchedLocked() {
9685 if (mLaunched) {
Joe Onoratoabded112016-02-08 16:49:39 -08009686 long time = mBsi.getBatteryUptimeLocked() - mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009687 if (time > 0) {
9688 mLaunchedTime += time;
9689 } else {
9690 mLaunches--;
9691 }
9692 mLaunched = false;
9693 }
9694 }
9695
9696 public void startRunningLocked() {
9697 if (!mRunning) {
9698 mStarts++;
Joe Onoratoabded112016-02-08 16:49:39 -08009699 mRunningSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009700 mRunning = true;
9701 }
9702 }
9703
9704 public void stopRunningLocked() {
9705 if (mRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08009706 long time = mBsi.getBatteryUptimeLocked() - mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009707 if (time > 0) {
9708 mStartTime += time;
9709 } else {
9710 mStarts--;
9711 }
9712 mRunning = false;
9713 }
9714 }
9715
9716 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -08009717 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009718 }
9719
9720 @Override
9721 public int getLaunches(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009722 int val = mLaunches;
9723 if (which == STATS_CURRENT) {
9724 val -= mLoadedLaunches;
9725 } else if (which == STATS_SINCE_UNPLUGGED) {
9726 val -= mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009727 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009728 return val;
9729 }
9730
9731 @Override
9732 public long getStartTime(long now, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009733 long val = getStartTimeToNowLocked(now);
9734 if (which == STATS_CURRENT) {
9735 val -= mLoadedStartTime;
9736 } else if (which == STATS_SINCE_UNPLUGGED) {
9737 val -= mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009738 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009739 return val;
9740 }
9741
9742 @Override
9743 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009744 int val = mStarts;
9745 if (which == STATS_CURRENT) {
9746 val -= mLoadedStarts;
9747 } else if (which == STATS_SINCE_UNPLUGGED) {
9748 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009749 }
9750
9751 return val;
9752 }
9753 }
9754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009755 final Serv newServiceStatsLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08009756 return new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009757 }
9758 }
9759
9760 /**
9761 * Retrieve the statistics object for a particular process, creating
9762 * if needed.
9763 */
9764 public Proc getProcessStatsLocked(String name) {
9765 Proc ps = mProcessStats.get(name);
9766 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08009767 ps = new Proc(mBsi, name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009768 mProcessStats.put(name, ps);
9769 }
9770
9771 return ps;
9772 }
9773
Andreas Gampe3f24e692018-02-05 13:24:28 -08009774 @GuardedBy("mBsi")
Dianne Hackborna8d10942015-11-19 17:55:19 -08009775 public void updateUidProcessStateLocked(int procState) {
9776 int uidRunningState;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009777 // Make special note of Foreground Services
9778 final boolean userAwareService =
9779 (procState == ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009780 uidRunningState = BatteryStats.mapToInternalProcessState(procState);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009781
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009782 if (mProcessState == uidRunningState && userAwareService == mInForegroundService) {
9783 return;
9784 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08009785
Bookatz867c0d72017-03-07 18:23:42 -08009786 final long elapsedRealtimeMs = mBsi.mClocks.elapsedRealtime();
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009787 if (mProcessState != uidRunningState) {
9788 final long uptimeMs = mBsi.mClocks.uptimeMillis();
Dianne Hackborna8d10942015-11-19 17:55:19 -08009789
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009790 if (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
9791 mProcessStateTimer[mProcessState].stopRunningLocked(elapsedRealtimeMs);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009792
Sudheer Shanka5c19b892018-01-05 17:25:46 -08009793 if (mBsi.trackPerProcStateCpuTimes()) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009794 if (mBsi.mPendingUids.size() == 0) {
Sudheer Shankae544d162017-12-28 17:06:20 -08009795 mBsi.mExternalSync.scheduleReadProcStateCpuTimes(
9796 mBsi.mOnBatteryTimeBase.isRunning(),
Sudheer Shankac20379e2018-02-15 00:06:21 -08009797 mBsi.mOnBatteryScreenOffTimeBase.isRunning(),
9798 mBsi.mConstants.PROC_STATE_CPU_TIMES_READ_DELAY_MS);
Mike Ma234d1822018-03-13 18:53:21 -07009799 mBsi.mNumSingleUidCpuTimeReads++;
Sudheer Shankac20379e2018-02-15 00:06:21 -08009800 } else {
Mike Ma234d1822018-03-13 18:53:21 -07009801 mBsi.mNumBatchedSingleUidCpuTimeReads++;
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009802 }
9803 if (mBsi.mPendingUids.indexOfKey(mUid) < 0
9804 || ArrayUtils.contains(CRITICAL_PROC_STATES, mProcessState)) {
9805 mBsi.mPendingUids.put(mUid, mProcessState);
9806 }
9807 } else {
9808 mBsi.mPendingUids.clear();
9809 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07009810 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009811 mProcessState = uidRunningState;
9812 if (uidRunningState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
9813 if (mProcessStateTimer[uidRunningState] == null) {
9814 makeProcessState(uidRunningState, null);
9815 }
9816 mProcessStateTimer[uidRunningState].startRunningLocked(elapsedRealtimeMs);
9817 }
9818
9819 updateOnBatteryBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
9820 updateOnBatteryScreenOffBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009821 }
Bookatz867c0d72017-03-07 18:23:42 -08009822
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009823 if (userAwareService != mInForegroundService) {
9824 if (userAwareService) {
9825 noteForegroundServiceResumedLocked(elapsedRealtimeMs);
9826 } else {
9827 noteForegroundServicePausedLocked(elapsedRealtimeMs);
9828 }
9829 mInForegroundService = userAwareService;
9830 }
Bookatz867c0d72017-03-07 18:23:42 -08009831 }
9832
Bookatzc8c44962017-05-11 12:12:54 -07009833 /** Whether to consider Uid to be in the background for background timebase purposes. */
9834 public boolean isInBackground() {
Bookatz867c0d72017-03-07 18:23:42 -08009835 // Note that PROCESS_STATE_CACHED and ActivityManager.PROCESS_STATE_NONEXISTENT is
9836 // also considered to be 'background' for our purposes, because it's not foreground.
Bookatzc8c44962017-05-11 12:12:54 -07009837 return mProcessState >= PROCESS_STATE_BACKGROUND;
9838 }
9839
9840 public boolean updateOnBatteryBgTimeBase(long uptimeUs, long realtimeUs) {
9841 boolean on = mBsi.mOnBatteryTimeBase.isRunning() && isInBackground();
9842 return mOnBatteryBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
9843 }
9844
9845 public boolean updateOnBatteryScreenOffBgTimeBase(long uptimeUs, long realtimeUs) {
9846 boolean on = mBsi.mOnBatteryScreenOffTimeBase.isRunning() && isInBackground();
9847 return mOnBatteryScreenOffBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009848 }
9849
Dianne Hackbornb5e31652010-09-07 12:13:55 -07009850 public SparseArray<? extends Pid> getPidStats() {
9851 return mPids;
9852 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009853
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009854 public Pid getPidStatsLocked(int pid) {
9855 Pid p = mPids.get(pid);
9856 if (p == null) {
9857 p = new Pid();
9858 mPids.put(pid, p);
9859 }
9860 return p;
9861 }
9862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009863 /**
9864 * Retrieve the statistics object for a particular service, creating
9865 * if needed.
9866 */
9867 public Pkg getPackageStatsLocked(String name) {
9868 Pkg ps = mPackageStats.get(name);
9869 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08009870 ps = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009871 mPackageStats.put(name, ps);
9872 }
9873
9874 return ps;
9875 }
9876
9877 /**
9878 * Retrieve the statistics object for a particular service, creating
9879 * if needed.
9880 */
9881 public Pkg.Serv getServiceStatsLocked(String pkg, String serv) {
9882 Pkg ps = getPackageStatsLocked(pkg);
9883 Pkg.Serv ss = ps.mServiceStats.get(serv);
9884 if (ss == null) {
9885 ss = ps.newServiceStatsLocked();
9886 ps.mServiceStats.put(serv, ss);
9887 }
9888
9889 return ss;
9890 }
9891
Dianne Hackbornd953c532014-08-16 18:17:38 -07009892 public void readSyncSummaryFromParcelLocked(String name, Parcel in) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009893 DualTimer timer = mSyncStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07009894 timer.readSummaryFromParcelLocked(in);
9895 mSyncStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009896 }
9897
Dianne Hackbornd953c532014-08-16 18:17:38 -07009898 public void readJobSummaryFromParcelLocked(String name, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07009899 DualTimer timer = mJobStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07009900 timer.readSummaryFromParcelLocked(in);
9901 mJobStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009902 }
9903
Dianne Hackbornd953c532014-08-16 18:17:38 -07009904 public void readWakeSummaryFromParcelLocked(String wlName, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08009905 Wakelock wl = new Wakelock(mBsi, this);
Dianne Hackbornd953c532014-08-16 18:17:38 -07009906 mWakelockStats.add(wlName, wl);
9907 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009908 getWakelockTimerLocked(wl, WAKE_TYPE_FULL).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009909 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07009910 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009911 getWakelockTimerLocked(wl, WAKE_TYPE_PARTIAL).readSummaryFromParcelLocked(in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07009912 }
9913 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009914 getWakelockTimerLocked(wl, WAKE_TYPE_WINDOW).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009915 }
Adam Lesinski9425fe22015-06-19 12:02:13 -07009916 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009917 getWakelockTimerLocked(wl, WAKE_TYPE_DRAW).readSummaryFromParcelLocked(in);
Adam Lesinski9425fe22015-06-19 12:02:13 -07009918 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009919 }
9920
Bookatz867c0d72017-03-07 18:23:42 -08009921 public DualTimer getSensorTimerLocked(int sensor, boolean create) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009922 Sensor se = mSensorStats.get(sensor);
9923 if (se == null) {
9924 if (!create) {
9925 return null;
9926 }
Joe Onoratoabded112016-02-08 16:49:39 -08009927 se = new Sensor(mBsi, this, sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009928 mSensorStats.put(sensor, se);
9929 }
Bookatz867c0d72017-03-07 18:23:42 -08009930 DualTimer t = se.mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009931 if (t != null) {
9932 return t;
9933 }
Joe Onoratoabded112016-02-08 16:49:39 -08009934 ArrayList<StopwatchTimer> timers = mBsi.mSensorTimers.get(sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009935 if (timers == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07009936 timers = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08009937 mBsi.mSensorTimers.put(sensor, timers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009938 }
Bookatz867c0d72017-03-07 18:23:42 -08009939 t = new DualTimer(mBsi.mClocks, this, BatteryStats.SENSOR, timers,
9940 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009941 se.mTimer = t;
9942 return t;
9943 }
9944
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009945 public void noteStartSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009946 DualTimer t = mSyncStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009947 if (t != null) {
9948 t.startRunningLocked(elapsedRealtimeMs);
9949 }
9950 }
9951
9952 public void noteStopSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009953 DualTimer t = mSyncStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009954 if (t != null) {
9955 t.stopRunningLocked(elapsedRealtimeMs);
9956 }
9957 }
9958
9959 public void noteStartJobLocked(String name, long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07009960 DualTimer t = mJobStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009961 if (t != null) {
9962 t.startRunningLocked(elapsedRealtimeMs);
9963 }
9964 }
9965
Dianne Hackborn94326cb2017-06-28 16:17:20 -07009966 public void noteStopJobLocked(String name, long elapsedRealtimeMs, int stopReason) {
Bookatzaa4594a2017-03-24 12:39:56 -07009967 DualTimer t = mJobStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009968 if (t != null) {
9969 t.stopRunningLocked(elapsedRealtimeMs);
9970 }
Dianne Hackborn94326cb2017-06-28 16:17:20 -07009971 if (mBsi.mOnBatteryTimeBase.isRunning()) {
9972 SparseIntArray types = mJobCompletions.get(name);
9973 if (types == null) {
9974 types = new SparseIntArray();
9975 mJobCompletions.put(name, types);
9976 }
9977 int last = types.get(stopReason, 0);
9978 types.put(stopReason, last + 1);
9979 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009980 }
9981
Bookatz5b5ec322017-05-26 09:40:38 -07009982 public StopwatchTimer getWakelockTimerLocked(Wakelock wl, int type) {
9983 if (wl == null) {
9984 return null;
9985 }
9986 switch (type) {
9987 case WAKE_TYPE_PARTIAL: {
9988 DualTimer t = wl.mTimerPartial;
9989 if (t == null) {
9990 t = new DualTimer(mBsi.mClocks, this, WAKE_TYPE_PARTIAL,
9991 mBsi.mPartialTimers, mBsi.mOnBatteryScreenOffTimeBase,
9992 mOnBatteryScreenOffBackgroundTimeBase);
9993 wl.mTimerPartial = t;
9994 }
9995 return t;
9996 }
9997 case WAKE_TYPE_FULL: {
9998 StopwatchTimer t = wl.mTimerFull;
9999 if (t == null) {
10000 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_FULL,
10001 mBsi.mFullTimers, mBsi.mOnBatteryTimeBase);
10002 wl.mTimerFull = t;
10003 }
10004 return t;
10005 }
10006 case WAKE_TYPE_WINDOW: {
10007 StopwatchTimer t = wl.mTimerWindow;
10008 if (t == null) {
10009 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_WINDOW,
10010 mBsi.mWindowTimers, mBsi.mOnBatteryTimeBase);
10011 wl.mTimerWindow = t;
10012 }
10013 return t;
10014 }
10015 case WAKE_TYPE_DRAW: {
10016 StopwatchTimer t = wl.mTimerDraw;
10017 if (t == null) {
10018 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_DRAW,
10019 mBsi.mDrawTimers, mBsi.mOnBatteryTimeBase);
10020 wl.mTimerDraw = t;
10021 }
10022 return t;
10023 }
10024 default:
10025 throw new IllegalArgumentException("type=" + type);
10026 }
10027 }
10028
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010029 public void noteStartWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070010030 Wakelock wl = mWakelockStats.startObject(name);
10031 if (wl != null) {
Bookatz5b5ec322017-05-26 09:40:38 -070010032 getWakelockTimerLocked(wl, type).startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010033 }
Bookatzc8c44962017-05-11 12:12:54 -070010034 if (type == WAKE_TYPE_PARTIAL) {
10035 createAggregatedPartialWakelockTimerLocked().startRunningLocked(elapsedRealtimeMs);
10036 if (pid >= 0) {
10037 Pid p = getPidStatsLocked(pid);
10038 if (p.mWakeNesting++ == 0) {
10039 p.mWakeStartMs = elapsedRealtimeMs;
10040 }
Dianne Hackbornb8071d792010-09-09 16:45:15 -070010041 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010042 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010043 }
10044
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010045 public void noteStopWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070010046 Wakelock wl = mWakelockStats.stopObject(name);
10047 if (wl != null) {
Bookatzd6746242017-10-24 18:39:35 -070010048 StopwatchTimer wlt = getWakelockTimerLocked(wl, type);
10049 wlt.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010050 }
Bookatzc8c44962017-05-11 12:12:54 -070010051 if (type == WAKE_TYPE_PARTIAL) {
10052 if (mAggregatedPartialWakelockTimer != null) {
10053 mAggregatedPartialWakelockTimer.stopRunningLocked(elapsedRealtimeMs);
10054 }
10055 if (pid >= 0) {
10056 Pid p = mPids.get(pid);
10057 if (p != null && p.mWakeNesting > 0) {
10058 if (p.mWakeNesting-- == 1) {
10059 p.mWakeSumMs += elapsedRealtimeMs - p.mWakeStartMs;
10060 p.mWakeStartMs = 0;
10061 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -080010062 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010063 }
10064 }
10065 }
10066
Dianne Hackborn287952c2010-09-22 22:34:31 -070010067 public void reportExcessiveCpuLocked(String proc, long overTime, long usedTime) {
10068 Proc p = getProcessStatsLocked(proc);
10069 if (p != null) {
10070 p.addExcessiveCpu(overTime, usedTime);
10071 }
10072 }
10073
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010074 public void noteStartSensor(int sensor, long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -080010075 DualTimer t = getSensorTimerLocked(sensor, /* create= */ true);
Amith Yamasani154d1242017-02-16 10:01:48 -080010076 t.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010077 }
10078
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010079 public void noteStopSensor(int sensor, long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010080 // Don't create a timer if one doesn't already exist
Bookatz867c0d72017-03-07 18:23:42 -080010081 DualTimer t = getSensorTimerLocked(sensor, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010082 if (t != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010083 t.stopRunningLocked(elapsedRealtimeMs);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010084 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010085 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010086
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010087 public void noteStartGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -080010088 noteStartSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010089 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010090
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010091 public void noteStopGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -080010092 noteStopSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010093 }
10094
10095 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -080010096 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010097 }
10098 }
10099
Sudheer Shanka9b735c52017-05-09 18:26:18 -070010100 public long[] getCpuFreqs() {
10101 return mCpuFreqs;
10102 }
10103
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010104 public BatteryStatsImpl(File systemDir, Handler handler, PlatformIdleStateCallback cb,
10105 UserInfoProvider userInfoProvider) {
10106 this(new SystemClocks(), systemDir, handler, cb, userInfoProvider);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010107 }
10108
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010109 private BatteryStatsImpl(Clocks clocks, File systemDir, Handler handler,
10110 PlatformIdleStateCallback cb,
10111 UserInfoProvider userInfoProvider) {
Joe Onoratoabded112016-02-08 16:49:39 -080010112 init(clocks);
10113
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010114 if (systemDir != null) {
10115 mFile = new JournaledFile(new File(systemDir, "batterystats.bin"),
10116 new File(systemDir, "batterystats.bin.tmp"));
10117 } else {
10118 mFile = null;
10119 }
10120 mCheckinFile = new AtomicFile(new File(systemDir, "batterystats-checkin.bin"));
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010121 mDailyFile = new AtomicFile(new File(systemDir, "batterystats-daily.xml"));
Jeff Brown6f357d32014-01-15 20:40:55 -080010122 mHandler = new MyHandler(handler.getLooper());
Sudheer Shanka5c19b892018-01-05 17:25:46 -080010123 mConstants = new Constants(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010124 mStartCount++;
Joe Onoratoabded112016-02-08 16:49:39 -080010125 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -070010126 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -070010127 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010128 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010129 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010130 }
Joe Onoratoabded112016-02-08 16:49:39 -080010131 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase);
10132 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
10133 mOnBatteryTimeBase);
10134 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -11, null,
10135 mOnBatteryTimeBase);
10136 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
10137 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null, mOnBatteryTimeBase);
10138 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase);
10139 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase);
10140 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
10141 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i, null,
10142 mOnBatteryTimeBase);
10143 }
10144 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
10145 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010146 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010147 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010148 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010149 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010150 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010151 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
10152 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010153 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010154 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase, NUM_WIFI_TX_LEVELS);
10155 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
10156 NUM_BT_TX_LEVELS);
10157 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
10158 ModemActivityInfo.TX_POWER_LEVELS);
Joe Onoratoabded112016-02-08 16:49:39 -080010159 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null, mOnBatteryTimeBase);
10160 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
10161 mOnBatteryTimeBase);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010162 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010163 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase);
10164 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080010165 mWifiMulticastWakelockTimer = new StopwatchTimer(mClocks, null,
10166 WIFI_AGGREGATE_MULTICAST_ENABLED, null, mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -080010167 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase);
10168 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null, mOnBatteryTimeBase);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010169 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010170 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i, null,
Dianne Hackborn3251b902014-06-20 14:40:53 -070010171 mOnBatteryTimeBase);
10172 }
Joe Onoratoabded112016-02-08 16:49:39 -080010173 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
10174 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i, null,
10175 mOnBatteryTimeBase);
10176 }
10177 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
10178 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i, null,
10179 mOnBatteryTimeBase);
10180 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080010181 mWifiActiveTimer = new StopwatchTimer(mClocks, null, -900, null, mOnBatteryTimeBase);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080010182 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
10183 mGpsSignalQualityTimer[i] = new StopwatchTimer(mClocks, null, -1000-i, null,
10184 mOnBatteryTimeBase);
10185 }
Joe Onoratoabded112016-02-08 16:49:39 -080010186 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
10187 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
10188 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase);
10189 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase);
10190 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010191 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -070010192 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Mike Ma15313c92017-11-15 17:58:21 -080010193 mDischargeLightDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
10194 mDischargeDeepDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010195 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010196 mOnBattery = mOnBatteryInternal = false;
Joe Onoratoabded112016-02-08 16:49:39 -080010197 long uptime = mClocks.uptimeMillis() * 1000;
10198 long realtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010199 initTimes(uptime, realtime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070010200 mStartPlatformVersion = mEndPlatformVersion = Build.ID;
Evan Millar633a1742009-04-02 16:36:33 -070010201 mDischargeStartLevel = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010202 mDischargeUnplugLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010203 mDischargePlugLevel = -1;
Evan Millar633a1742009-04-02 16:36:33 -070010204 mDischargeCurrentLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010205 mCurrentBatteryLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010206 initDischarge();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010207 clearHistoryLocked();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010208 updateDailyDeadlineLocked();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010209 mPlatformIdleStateCallback = cb;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010210 mUserInfoProvider = userInfoProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010211 }
10212
10213 public BatteryStatsImpl(Parcel p) {
Joe Onoratoabded112016-02-08 16:49:39 -080010214 this(new SystemClocks(), p);
10215 }
10216
10217 public BatteryStatsImpl(Clocks clocks, Parcel p) {
10218 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070010219 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010220 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010221 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -070010222 mHandler = null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010223 mExternalSync = null;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080010224 mConstants = new Constants(mHandler);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010225 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010226 readFromParcel(p);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010227 mPlatformIdleStateCallback = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010228 }
10229
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010230 public void setPowerProfileLocked(PowerProfile profile) {
10231 mPowerProfile = profile;
Adam Lesinski6832f392015-09-05 18:05:40 -070010232
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010233 // We need to initialize the KernelCpuSpeedReaders to read from
10234 // the first cpu of each core. Once we have the PowerProfile, we have access to this
10235 // information.
10236 final int numClusters = mPowerProfile.getNumCpuClusters();
10237 mKernelCpuSpeedReaders = new KernelCpuSpeedReader[numClusters];
10238 int firstCpuOfCluster = 0;
10239 for (int i = 0; i < numClusters; i++) {
10240 final int numSpeedSteps = mPowerProfile.getNumSpeedStepsInCpuCluster(i);
10241 mKernelCpuSpeedReaders[i] = new KernelCpuSpeedReader(firstCpuOfCluster,
10242 numSpeedSteps);
10243 firstCpuOfCluster += mPowerProfile.getNumCoresInCpuCluster(i);
10244 }
Adam Lesinskif9b20a92016-06-17 17:30:01 -070010245
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010246 if (mEstimatedBatteryCapacity == -1) {
10247 // Initialize the estimated battery capacity to a known preset one.
10248 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
Adam Lesinskie08af192015-03-25 16:42:59 -070010249 }
10250 }
10251
Dianne Hackborn0d903a82010-09-07 23:51:03 -070010252 public void setCallback(BatteryCallback cb) {
10253 mCallback = cb;
10254 }
10255
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010256 public void setRadioScanningTimeoutLocked(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -070010257 if (mPhoneSignalScanningTimer != null) {
10258 mPhoneSignalScanningTimer.setTimeout(timeout);
10259 }
10260 }
10261
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070010262 public void setExternalStatsSyncLocked(ExternalStatsSync sync) {
10263 mExternalSync = sync;
10264 }
10265
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010266 public void updateDailyDeadlineLocked() {
10267 // Get the current time.
10268 long currentTime = mDailyStartTime = System.currentTimeMillis();
10269 Calendar calDeadline = Calendar.getInstance();
10270 calDeadline.setTimeInMillis(currentTime);
10271
10272 // Move time up to the next day, ranging from 1am to 3pm.
10273 calDeadline.set(Calendar.DAY_OF_YEAR, calDeadline.get(Calendar.DAY_OF_YEAR) + 1);
10274 calDeadline.set(Calendar.MILLISECOND, 0);
10275 calDeadline.set(Calendar.SECOND, 0);
10276 calDeadline.set(Calendar.MINUTE, 0);
10277 calDeadline.set(Calendar.HOUR_OF_DAY, 1);
10278 mNextMinDailyDeadline = calDeadline.getTimeInMillis();
10279 calDeadline.set(Calendar.HOUR_OF_DAY, 3);
10280 mNextMaxDailyDeadline = calDeadline.getTimeInMillis();
10281 }
10282
10283 public void recordDailyStatsIfNeededLocked(boolean settled) {
10284 long currentTime = System.currentTimeMillis();
10285 if (currentTime >= mNextMaxDailyDeadline) {
10286 recordDailyStatsLocked();
10287 } else if (settled && currentTime >= mNextMinDailyDeadline) {
10288 recordDailyStatsLocked();
10289 } else if (currentTime < (mDailyStartTime-(1000*60*60*24))) {
10290 recordDailyStatsLocked();
10291 }
10292 }
10293
10294 public void recordDailyStatsLocked() {
10295 DailyItem item = new DailyItem();
10296 item.mStartTime = mDailyStartTime;
10297 item.mEndTime = System.currentTimeMillis();
10298 boolean hasData = false;
10299 if (mDailyDischargeStepTracker.mNumStepDurations > 0) {
10300 hasData = true;
10301 item.mDischargeSteps = new LevelStepTracker(
10302 mDailyDischargeStepTracker.mNumStepDurations,
10303 mDailyDischargeStepTracker.mStepDurations);
10304 }
10305 if (mDailyChargeStepTracker.mNumStepDurations > 0) {
10306 hasData = true;
10307 item.mChargeSteps = new LevelStepTracker(
10308 mDailyChargeStepTracker.mNumStepDurations,
10309 mDailyChargeStepTracker.mStepDurations);
10310 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010311 if (mDailyPackageChanges != null) {
10312 hasData = true;
10313 item.mPackageChanges = mDailyPackageChanges;
10314 mDailyPackageChanges = null;
10315 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010316 mDailyDischargeStepTracker.init();
10317 mDailyChargeStepTracker.init();
10318 updateDailyDeadlineLocked();
10319
10320 if (hasData) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080010321 final long startTime = SystemClock.uptimeMillis();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010322 mDailyItems.add(item);
10323 while (mDailyItems.size() > MAX_DAILY_ITEMS) {
10324 mDailyItems.remove(0);
10325 }
10326 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
10327 try {
10328 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010010329 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010330 writeDailyItemsLocked(out);
Dianne Hackborne17b4452018-01-10 13:15:40 -080010331 final long initialTime = SystemClock.uptimeMillis() - startTime;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010332 BackgroundThread.getHandler().post(new Runnable() {
10333 @Override
10334 public void run() {
10335 synchronized (mCheckinFile) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080010336 final long startTime2 = SystemClock.uptimeMillis();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010337 FileOutputStream stream = null;
10338 try {
10339 stream = mDailyFile.startWrite();
10340 memStream.writeTo(stream);
10341 stream.flush();
10342 FileUtils.sync(stream);
10343 stream.close();
10344 mDailyFile.finishWrite(stream);
Dianne Hackborne17b4452018-01-10 13:15:40 -080010345 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
10346 "batterystats-daily",
10347 initialTime + SystemClock.uptimeMillis() - startTime2);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010348 } catch (IOException e) {
10349 Slog.w("BatteryStats",
10350 "Error writing battery daily items", e);
10351 mDailyFile.failWrite(stream);
10352 }
10353 }
10354 }
10355 });
10356 } catch (IOException e) {
10357 }
10358 }
10359 }
10360
10361 private void writeDailyItemsLocked(XmlSerializer out) throws IOException {
10362 StringBuilder sb = new StringBuilder(64);
10363 out.startDocument(null, true);
10364 out.startTag(null, "daily-items");
10365 for (int i=0; i<mDailyItems.size(); i++) {
10366 final DailyItem dit = mDailyItems.get(i);
10367 out.startTag(null, "item");
10368 out.attribute(null, "start", Long.toString(dit.mStartTime));
10369 out.attribute(null, "end", Long.toString(dit.mEndTime));
10370 writeDailyLevelSteps(out, "dis", dit.mDischargeSteps, sb);
10371 writeDailyLevelSteps(out, "chg", dit.mChargeSteps, sb);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010372 if (dit.mPackageChanges != null) {
10373 for (int j=0; j<dit.mPackageChanges.size(); j++) {
10374 PackageChange pc = dit.mPackageChanges.get(j);
10375 if (pc.mUpdate) {
10376 out.startTag(null, "upd");
10377 out.attribute(null, "pkg", pc.mPackageName);
Dianne Hackborn3accca02013-09-20 09:32:11 -070010378 out.attribute(null, "ver", Long.toString(pc.mVersionCode));
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010379 out.endTag(null, "upd");
10380 } else {
10381 out.startTag(null, "rem");
10382 out.attribute(null, "pkg", pc.mPackageName);
10383 out.endTag(null, "rem");
10384 }
10385 }
10386 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010387 out.endTag(null, "item");
10388 }
10389 out.endTag(null, "daily-items");
10390 out.endDocument();
10391 }
10392
10393 private void writeDailyLevelSteps(XmlSerializer out, String tag, LevelStepTracker steps,
10394 StringBuilder tmpBuilder) throws IOException {
10395 if (steps != null) {
10396 out.startTag(null, tag);
10397 out.attribute(null, "n", Integer.toString(steps.mNumStepDurations));
10398 for (int i=0; i<steps.mNumStepDurations; i++) {
10399 out.startTag(null, "s");
10400 tmpBuilder.setLength(0);
10401 steps.encodeEntryAt(i, tmpBuilder);
10402 out.attribute(null, "v", tmpBuilder.toString());
10403 out.endTag(null, "s");
10404 }
10405 out.endTag(null, tag);
10406 }
10407 }
10408
10409 public void readDailyStatsLocked() {
10410 Slog.d(TAG, "Reading daily items from " + mDailyFile.getBaseFile());
10411 mDailyItems.clear();
10412 FileInputStream stream;
10413 try {
10414 stream = mDailyFile.openRead();
10415 } catch (FileNotFoundException e) {
10416 return;
10417 }
10418 try {
10419 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010010420 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010421 readDailyItemsLocked(parser);
10422 } catch (XmlPullParserException e) {
10423 } finally {
10424 try {
10425 stream.close();
10426 } catch (IOException e) {
10427 }
10428 }
10429 }
10430
10431 private void readDailyItemsLocked(XmlPullParser parser) {
10432 try {
10433 int type;
10434 while ((type = parser.next()) != XmlPullParser.START_TAG
10435 && type != XmlPullParser.END_DOCUMENT) {
10436 ;
10437 }
10438
10439 if (type != XmlPullParser.START_TAG) {
10440 throw new IllegalStateException("no start tag found");
10441 }
10442
10443 int outerDepth = parser.getDepth();
10444 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10445 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10446 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10447 continue;
10448 }
10449
10450 String tagName = parser.getName();
10451 if (tagName.equals("item")) {
10452 readDailyItemTagLocked(parser);
10453 } else {
10454 Slog.w(TAG, "Unknown element under <daily-items>: "
10455 + parser.getName());
10456 XmlUtils.skipCurrentTag(parser);
10457 }
10458 }
10459
10460 } catch (IllegalStateException e) {
10461 Slog.w(TAG, "Failed parsing daily " + e);
10462 } catch (NullPointerException e) {
10463 Slog.w(TAG, "Failed parsing daily " + e);
10464 } catch (NumberFormatException e) {
10465 Slog.w(TAG, "Failed parsing daily " + e);
10466 } catch (XmlPullParserException e) {
10467 Slog.w(TAG, "Failed parsing daily " + e);
10468 } catch (IOException e) {
10469 Slog.w(TAG, "Failed parsing daily " + e);
10470 } catch (IndexOutOfBoundsException e) {
10471 Slog.w(TAG, "Failed parsing daily " + e);
10472 }
10473 }
10474
10475 void readDailyItemTagLocked(XmlPullParser parser) throws NumberFormatException,
10476 XmlPullParserException, IOException {
10477 DailyItem dit = new DailyItem();
10478 String attr = parser.getAttributeValue(null, "start");
10479 if (attr != null) {
10480 dit.mStartTime = Long.parseLong(attr);
10481 }
10482 attr = parser.getAttributeValue(null, "end");
10483 if (attr != null) {
10484 dit.mEndTime = Long.parseLong(attr);
10485 }
10486 int outerDepth = parser.getDepth();
10487 int type;
10488 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10489 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10490 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10491 continue;
10492 }
10493
10494 String tagName = parser.getName();
10495 if (tagName.equals("dis")) {
10496 readDailyItemTagDetailsLocked(parser, dit, false, "dis");
10497 } else if (tagName.equals("chg")) {
10498 readDailyItemTagDetailsLocked(parser, dit, true, "chg");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010499 } else if (tagName.equals("upd")) {
10500 if (dit.mPackageChanges == null) {
10501 dit.mPackageChanges = new ArrayList<>();
10502 }
10503 PackageChange pc = new PackageChange();
10504 pc.mUpdate = true;
10505 pc.mPackageName = parser.getAttributeValue(null, "pkg");
10506 String verStr = parser.getAttributeValue(null, "ver");
Dianne Hackborn3accca02013-09-20 09:32:11 -070010507 pc.mVersionCode = verStr != null ? Long.parseLong(verStr) : 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010508 dit.mPackageChanges.add(pc);
10509 XmlUtils.skipCurrentTag(parser);
10510 } else if (tagName.equals("rem")) {
10511 if (dit.mPackageChanges == null) {
10512 dit.mPackageChanges = new ArrayList<>();
10513 }
10514 PackageChange pc = new PackageChange();
10515 pc.mUpdate = false;
10516 pc.mPackageName = parser.getAttributeValue(null, "pkg");
10517 dit.mPackageChanges.add(pc);
10518 XmlUtils.skipCurrentTag(parser);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010519 } else {
10520 Slog.w(TAG, "Unknown element under <item>: "
10521 + parser.getName());
10522 XmlUtils.skipCurrentTag(parser);
10523 }
10524 }
10525 mDailyItems.add(dit);
10526 }
10527
10528 void readDailyItemTagDetailsLocked(XmlPullParser parser, DailyItem dit, boolean isCharge,
10529 String tag)
10530 throws NumberFormatException, XmlPullParserException, IOException {
10531 final String numAttr = parser.getAttributeValue(null, "n");
10532 if (numAttr == null) {
10533 Slog.w(TAG, "Missing 'n' attribute at " + parser.getPositionDescription());
10534 XmlUtils.skipCurrentTag(parser);
10535 return;
10536 }
10537 final int num = Integer.parseInt(numAttr);
10538 LevelStepTracker steps = new LevelStepTracker(num);
10539 if (isCharge) {
10540 dit.mChargeSteps = steps;
10541 } else {
10542 dit.mDischargeSteps = steps;
10543 }
10544 int i = 0;
10545 int outerDepth = parser.getDepth();
10546 int type;
10547 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10548 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10549 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10550 continue;
10551 }
10552
10553 String tagName = parser.getName();
10554 if ("s".equals(tagName)) {
10555 if (i < num) {
10556 String valueAttr = parser.getAttributeValue(null, "v");
10557 if (valueAttr != null) {
10558 steps.decodeEntryAt(i, valueAttr);
10559 i++;
10560 }
10561 }
10562 } else {
10563 Slog.w(TAG, "Unknown element under <" + tag + ">: "
10564 + parser.getName());
10565 XmlUtils.skipCurrentTag(parser);
10566 }
10567 }
10568 steps.mNumStepDurations = i;
10569 }
10570
10571 @Override
10572 public DailyItem getDailyItemLocked(int daysAgo) {
10573 int index = mDailyItems.size()-1-daysAgo;
10574 return index >= 0 ? mDailyItems.get(index) : null;
10575 }
10576
10577 @Override
10578 public long getCurrentDailyStartTime() {
10579 return mDailyStartTime;
10580 }
10581
10582 @Override
10583 public long getNextMinDailyDeadline() {
10584 return mNextMinDailyDeadline;
10585 }
10586
10587 @Override
10588 public long getNextMaxDailyDeadline() {
10589 return mNextMaxDailyDeadline;
10590 }
10591
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010592 @Override
10593 public boolean startIteratingOldHistoryLocked() {
10594 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
10595 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010596 if ((mHistoryIterator = mHistory) == null) {
10597 return false;
10598 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010599 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010600 mHistoryReadTmp.clear();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010601 mReadOverflow = false;
10602 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010603 return true;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010604 }
10605
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010606 @Override
10607 public boolean getNextOldHistoryLocked(HistoryItem out) {
10608 boolean end = mHistoryBuffer.dataPosition() >= mHistoryBuffer.dataSize();
10609 if (!end) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010610 readHistoryDelta(mHistoryBuffer, mHistoryReadTmp);
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010611 mReadOverflow |= mHistoryReadTmp.cmd == HistoryItem.CMD_OVERFLOW;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010612 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010613 HistoryItem cur = mHistoryIterator;
10614 if (cur == null) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010615 if (!mReadOverflow && !end) {
10616 Slog.w(TAG, "Old history ends before new history!");
10617 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010618 return false;
10619 }
10620 out.setTo(cur);
10621 mHistoryIterator = cur.next;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010622 if (!mReadOverflow) {
10623 if (end) {
10624 Slog.w(TAG, "New history ends before old history!");
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010625 } else if (!out.same(mHistoryReadTmp)) {
Dianne Hackborn8c841092013-06-24 13:46:13 -070010626 PrintWriter pw = new FastPrintWriter(new LogWriter(android.util.Log.WARN, TAG));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010627 pw.println("Histories differ!");
10628 pw.println("Old history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010629 (new HistoryPrinter()).printNextItem(pw, out, 0, false, true);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010630 pw.println("New history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010631 (new HistoryPrinter()).printNextItem(pw, mHistoryReadTmp, 0, false,
10632 true);
Dianne Hackborn8c841092013-06-24 13:46:13 -070010633 pw.flush();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010634 }
10635 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010636 return true;
10637 }
10638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010639 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010640 public void finishIteratingOldHistoryLocked() {
10641 mIteratingHistory = false;
10642 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010643 mHistoryIterator = null;
10644 }
10645
10646 public int getHistoryTotalSize() {
10647 return MAX_HISTORY_BUFFER;
10648 }
10649
10650 public int getHistoryUsedSize() {
10651 return mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010652 }
10653
10654 @Override
10655 public boolean startIteratingHistoryLocked() {
10656 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
10657 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010658 if (mHistoryBuffer.dataSize() <= 0) {
10659 return false;
10660 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010661 mHistoryBuffer.setDataPosition(0);
10662 mReadOverflow = false;
10663 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010664 mReadHistoryStrings = new String[mHistoryTagPool.size()];
10665 mReadHistoryUids = new int[mHistoryTagPool.size()];
10666 mReadHistoryChars = 0;
10667 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
10668 final HistoryTag tag = ent.getKey();
10669 final int idx = ent.getValue();
10670 mReadHistoryStrings[idx] = tag.string;
10671 mReadHistoryUids[idx] = tag.uid;
10672 mReadHistoryChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080010673 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010674 return true;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010675 }
10676
10677 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -080010678 public int getHistoryStringPoolSize() {
10679 return mReadHistoryStrings.length;
10680 }
10681
10682 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010683 public int getHistoryStringPoolBytes() {
10684 // Each entry is a fixed 12 bytes: 4 for index, 4 for uid, 4 for string size
10685 // Each string character is 2 bytes.
10686 return (mReadHistoryStrings.length * 12) + (mReadHistoryChars * 2);
10687 }
10688
10689 @Override
10690 public String getHistoryTagPoolString(int index) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080010691 return mReadHistoryStrings[index];
10692 }
10693
10694 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010695 public int getHistoryTagPoolUid(int index) {
10696 return mReadHistoryUids[index];
10697 }
10698
10699 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010700 public boolean getNextHistoryLocked(HistoryItem out) {
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010701 final int pos = mHistoryBuffer.dataPosition();
10702 if (pos == 0) {
10703 out.clear();
10704 }
10705 boolean end = pos >= mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010706 if (end) {
10707 return false;
10708 }
10709
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010710 final long lastRealtime = out.time;
10711 final long lastWalltime = out.currentTime;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010712 readHistoryDelta(mHistoryBuffer, out);
Dianne Hackborn37de0982014-05-09 09:32:18 -070010713 if (out.cmd != HistoryItem.CMD_CURRENT_TIME
10714 && out.cmd != HistoryItem.CMD_RESET && lastWalltime != 0) {
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010715 out.currentTime = lastWalltime + (out.time - lastRealtime);
10716 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010717 return true;
10718 }
10719
10720 @Override
10721 public void finishIteratingHistoryLocked() {
10722 mIteratingHistory = false;
10723 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn099bc622014-01-22 13:39:16 -080010724 mReadHistoryStrings = null;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010725 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010726
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010727 @Override
Dianne Hackbornb5e31652010-09-07 12:13:55 -070010728 public long getHistoryBaseTime() {
10729 return mHistoryBaseTime;
10730 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010731
Dianne Hackbornb5e31652010-09-07 12:13:55 -070010732 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010733 public int getStartCount() {
10734 return mStartCount;
10735 }
10736
10737 public boolean isOnBattery() {
10738 return mOnBattery;
10739 }
10740
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010741 public boolean isCharging() {
10742 return mCharging;
10743 }
10744
Mike Mac2f518a2017-09-19 16:06:03 -070010745 public boolean isScreenOn(int state) {
Chris Phoenix10a4a642017-09-25 13:21:00 -070010746 return state == Display.STATE_ON || state == Display.STATE_VR
10747 || state == Display.STATE_ON_SUSPEND;
Mike Mac2f518a2017-09-19 16:06:03 -070010748 }
10749
10750 public boolean isScreenOff(int state) {
10751 return state == Display.STATE_OFF;
10752 }
10753
10754 public boolean isScreenDoze(int state) {
10755 return state == Display.STATE_DOZE || state == Display.STATE_DOZE_SUSPEND;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010756 }
10757
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010758 void initTimes(long uptime, long realtime) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080010759 mStartClockTime = System.currentTimeMillis();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010760 mOnBatteryTimeBase.init(uptime, realtime);
10761 mOnBatteryScreenOffTimeBase.init(uptime, realtime);
Dianne Hackborn4590e522014-03-24 13:36:46 -070010762 mRealtime = 0;
10763 mUptime = 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010764 mRealtimeStart = realtime;
Dianne Hackborn4590e522014-03-24 13:36:46 -070010765 mUptimeStart = uptime;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010766 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010767
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010768 void initDischarge() {
10769 mLowDischargeAmountSinceCharge = 0;
10770 mHighDischargeAmountSinceCharge = 0;
10771 mDischargeAmountScreenOn = 0;
10772 mDischargeAmountScreenOnSinceCharge = 0;
10773 mDischargeAmountScreenOff = 0;
10774 mDischargeAmountScreenOffSinceCharge = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010775 mDischargeAmountScreenDoze = 0;
10776 mDischargeAmountScreenDozeSinceCharge = 0;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010777 mDischargeStepTracker.init();
10778 mChargeStepTracker.init();
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010779 mDischargeScreenOffCounter.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -070010780 mDischargeScreenDozeCounter.reset(false);
Mike Ma15313c92017-11-15 17:58:21 -080010781 mDischargeLightDozeCounter.reset(false);
10782 mDischargeDeepDozeCounter.reset(false);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010783 mDischargeCounter.reset(false);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010784 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010785
10786 public void resetAllStatsCmdLocked() {
10787 resetAllStatsLocked();
Joe Onoratoabded112016-02-08 16:49:39 -080010788 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -070010789 long uptime = mSecUptime * 1000;
Joe Onoratoabded112016-02-08 16:49:39 -080010790 long mSecRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010791 long realtime = mSecRealtime * 1000;
10792 mDischargeStartLevel = mHistoryCur.batteryLevel;
10793 pullPendingStateUpdatesLocked();
Dianne Hackborn40c87252014-03-19 16:55:40 -070010794 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010795 mDischargeCurrentLevel = mDischargeUnplugLevel = mDischargePlugLevel
10796 = mCurrentBatteryLevel = mHistoryCur.batteryLevel;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010797 mOnBatteryTimeBase.reset(uptime, realtime);
10798 mOnBatteryScreenOffTimeBase.reset(uptime, realtime);
10799 if ((mHistoryCur.states&HistoryItem.STATE_BATTERY_PLUGGED_FLAG) == 0) {
Mike Mac2f518a2017-09-19 16:06:03 -070010800 if (isScreenOn(mScreenState)) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010801 mDischargeScreenOnUnplugLevel = mHistoryCur.batteryLevel;
Mike Mac2f518a2017-09-19 16:06:03 -070010802 mDischargeScreenDozeUnplugLevel = 0;
10803 mDischargeScreenOffUnplugLevel = 0;
10804 } else if (isScreenDoze(mScreenState)) {
10805 mDischargeScreenOnUnplugLevel = 0;
10806 mDischargeScreenDozeUnplugLevel = mHistoryCur.batteryLevel;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010807 mDischargeScreenOffUnplugLevel = 0;
10808 } else {
10809 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010810 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010811 mDischargeScreenOffUnplugLevel = mHistoryCur.batteryLevel;
10812 }
10813 mDischargeAmountScreenOn = 0;
10814 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010815 mDischargeAmountScreenDoze = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010816 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070010817 initActiveHistoryEventsLocked(mSecRealtime, mSecUptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010818 }
10819
10820 private void resetAllStatsLocked() {
Adam Lesinski8ce36942016-05-26 16:05:35 -070010821 final long uptimeMillis = mClocks.uptimeMillis();
10822 final long elapsedRealtimeMillis = mClocks.elapsedRealtime();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010823 mStartCount = 0;
Adam Lesinski8ce36942016-05-26 16:05:35 -070010824 initTimes(uptimeMillis * 1000, elapsedRealtimeMillis * 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010825 mScreenOnTimer.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -070010826 mScreenDozeTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010827 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010828 mScreenBrightnessTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010829 }
Adam Lesinski1a76a622016-06-22 10:28:47 -070010830
10831 if (mPowerProfile != null) {
10832 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
10833 } else {
10834 mEstimatedBatteryCapacity = -1;
10835 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070010836 mMinLearnedBatteryCapacity = -1;
10837 mMaxLearnedBatteryCapacity = -1;
Jeff Browne95c3cd2014-05-02 16:59:26 -070010838 mInteractiveTimer.reset(false);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070010839 mPowerSaveModeEnabledTimer.reset(false);
Adam Lesinski8ce36942016-05-26 16:05:35 -070010840 mLastIdleTimeStart = elapsedRealtimeMillis;
Dianne Hackborn08c47a52015-10-15 12:38:14 -070010841 mLongestLightIdleTime = 0;
10842 mLongestFullIdleTime = 0;
10843 mDeviceIdleModeLightTimer.reset(false);
10844 mDeviceIdleModeFullTimer.reset(false);
10845 mDeviceLightIdlingTimer.reset(false);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010846 mDeviceIdlingTimer.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010847 mPhoneOnTimer.reset(false);
10848 mAudioOnTimer.reset(false);
10849 mVideoOnTimer.reset(false);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070010850 mFlashlightOnTimer.reset(false);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070010851 mCameraOnTimer.reset(false);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010852 mBluetoothScanTimer.reset(false);
Wink Saville52840902011-02-18 12:40:47 -080010853 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010854 mPhoneSignalStrengthsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010855 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010856 mPhoneSignalScanningTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010857 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010858 mPhoneDataConnectionsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010859 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010860 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010861 mNetworkByteActivityCounters[i].reset(false);
10862 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010863 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010864 mMobileRadioActiveTimer.reset(false);
10865 mMobileRadioActivePerAppTimer.reset(false);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010866 mMobileRadioActiveAdjustedTime.reset(false);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080010867 mMobileRadioActiveUnknownTime.reset(false);
10868 mMobileRadioActiveUnknownCount.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010869 mWifiOnTimer.reset(false);
10870 mGlobalWifiRunningTimer.reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010871 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010872 mWifiStateTimer[i].reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010873 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070010874 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
10875 mWifiSupplStateTimer[i].reset(false);
10876 }
10877 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
10878 mWifiSignalStrengthsTimer[i].reset(false);
10879 }
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080010880 mWifiMulticastWakelockTimer.reset(false);
Siddharth Rayb50a6842017-12-14 15:15:28 -080010881 mWifiActiveTimer.reset(false);
10882 mWifiActivity.reset(false);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080010883 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
10884 mGpsSignalQualityTimer[i].reset(false);
10885 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010886 mBluetoothActivity.reset(false);
10887 mModemActivity.reset(false);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080010888 mNumConnectivityChange = mLoadedNumConnectivityChange = mUnpluggedNumConnectivityChange = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010889
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010890 for (int i=0; i<mUidStats.size(); i++) {
Bookatz993a0be2017-07-21 09:03:23 -070010891 if (mUidStats.valueAt(i).reset(uptimeMillis * 1000, elapsedRealtimeMillis * 1000)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010892 mUidStats.remove(mUidStats.keyAt(i));
10893 i--;
10894 }
10895 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010896
Bookatz50df7112017-08-04 14:53:26 -070010897 if (mRpmStats.size() > 0) {
10898 for (SamplingTimer timer : mRpmStats.values()) {
10899 mOnBatteryTimeBase.remove(timer);
10900 }
10901 mRpmStats.clear();
10902 }
10903 if (mScreenOffRpmStats.size() > 0) {
10904 for (SamplingTimer timer : mScreenOffRpmStats.values()) {
10905 mOnBatteryScreenOffTimeBase.remove(timer);
10906 }
10907 mScreenOffRpmStats.clear();
10908 }
10909
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010910 if (mKernelWakelockStats.size() > 0) {
10911 for (SamplingTimer timer : mKernelWakelockStats.values()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010912 mOnBatteryScreenOffTimeBase.remove(timer);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010913 }
10914 mKernelWakelockStats.clear();
10915 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010916
James Carr3a226052016-07-01 14:49:52 -070010917 if (mKernelMemoryStats.size() > 0) {
10918 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
10919 mOnBatteryTimeBase.remove(mKernelMemoryStats.valueAt(i));
10920 }
10921 mKernelMemoryStats.clear();
10922 }
10923
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010924 if (mWakeupReasonStats.size() > 0) {
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070010925 for (SamplingTimer timer : mWakeupReasonStats.values()) {
10926 mOnBatteryTimeBase.remove(timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010927 }
10928 mWakeupReasonStats.clear();
10929 }
10930
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080010931 mLastHistoryStepDetails = null;
10932 mLastStepCpuUserTime = mLastStepCpuSystemTime = 0;
10933 mCurStepCpuUserTime = mCurStepCpuSystemTime = 0;
10934 mLastStepCpuUserTime = mCurStepCpuUserTime = 0;
10935 mLastStepCpuSystemTime = mCurStepCpuSystemTime = 0;
10936 mLastStepStatUserTime = mCurStepStatUserTime = 0;
10937 mLastStepStatSystemTime = mCurStepStatSystemTime = 0;
10938 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime = 0;
10939 mLastStepStatIrqTime = mCurStepStatIrqTime = 0;
10940 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime = 0;
10941 mLastStepStatIdleTime = mCurStepStatIdleTime = 0;
10942
Mike Ma234d1822018-03-13 18:53:21 -070010943 mNumAllUidCpuTimeReads = 0;
10944 mNumUidsRemoved = 0;
10945
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010946 initDischarge();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010947
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010948 clearHistoryLocked();
Fyodor Kupolov8aa51242018-04-23 12:44:51 -070010949 mHandler.sendEmptyMessage(MSG_REPORT_RESET_STATS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010950 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010951
Dianne Hackborn40c87252014-03-19 16:55:40 -070010952 private void initActiveHistoryEventsLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010953 for (int i=0; i<HistoryItem.EVENT_COUNT; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010954 if (!mRecordAllHistory && i == HistoryItem.EVENT_PROC) {
10955 // Not recording process starts/stops.
10956 continue;
10957 }
Dianne Hackborn37de0982014-05-09 09:32:18 -070010958 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(i);
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010959 if (active == null) {
10960 continue;
10961 }
Dianne Hackborn37de0982014-05-09 09:32:18 -070010962 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
10963 SparseIntArray uids = ent.getValue();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010964 for (int j=0; j<uids.size(); j++) {
Dianne Hackborn37de0982014-05-09 09:32:18 -070010965 addHistoryEventLocked(elapsedRealtimeMs, uptimeMs, i, ent.getKey(),
10966 uids.keyAt(j));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010967 }
10968 }
10969 }
10970 }
10971
Mike Mac2f518a2017-09-19 16:06:03 -070010972 void updateDischargeScreenLevelsLocked(int oldState, int newState) {
10973 updateOldDischargeScreenLevelLocked(oldState);
10974 updateNewDischargeScreenLevelLocked(newState);
10975 }
10976
10977 private void updateOldDischargeScreenLevelLocked(int state) {
10978 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010979 int diff = mDischargeScreenOnUnplugLevel - mDischargeCurrentLevel;
10980 if (diff > 0) {
10981 mDischargeAmountScreenOn += diff;
10982 mDischargeAmountScreenOnSinceCharge += diff;
10983 }
Mike Mac2f518a2017-09-19 16:06:03 -070010984 } else if (isScreenDoze(state)) {
10985 int diff = mDischargeScreenDozeUnplugLevel - mDischargeCurrentLevel;
10986 if (diff > 0) {
10987 mDischargeAmountScreenDoze += diff;
10988 mDischargeAmountScreenDozeSinceCharge += diff;
10989 }
10990 } else if (isScreenOff(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010991 int diff = mDischargeScreenOffUnplugLevel - mDischargeCurrentLevel;
10992 if (diff > 0) {
10993 mDischargeAmountScreenOff += diff;
10994 mDischargeAmountScreenOffSinceCharge += diff;
10995 }
10996 }
Mike Mac2f518a2017-09-19 16:06:03 -070010997 }
10998
10999 private void updateNewDischargeScreenLevelLocked(int state) {
11000 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011001 mDischargeScreenOnUnplugLevel = mDischargeCurrentLevel;
11002 mDischargeScreenOffUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070011003 mDischargeScreenDozeUnplugLevel = 0;
11004 } else if (isScreenDoze(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011005 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070011006 mDischargeScreenDozeUnplugLevel = mDischargeCurrentLevel;
11007 mDischargeScreenOffUnplugLevel = 0;
11008 } else if (isScreenOff(state)) {
11009 mDischargeScreenOnUnplugLevel = 0;
11010 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011011 mDischargeScreenOffUnplugLevel = mDischargeCurrentLevel;
11012 }
11013 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011014
Dianne Hackborna7c837f2014-01-15 16:20:44 -080011015 public void pullPendingStateUpdatesLocked() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -080011016 if (mOnBatteryInternal) {
Mike Mac2f518a2017-09-19 16:06:03 -070011017 updateDischargeScreenLevelsLocked(mScreenState, mScreenState);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080011018 }
Dianne Hackborna7c837f2014-01-15 16:20:44 -080011019 }
11020
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011021 private final NetworkStatsFactory mNetworkStatsFactory = new NetworkStatsFactory();
11022 private final Pools.Pool<NetworkStats> mNetworkStatsPool = new Pools.SynchronizedPool<>(6);
11023
11024 private final Object mWifiNetworkLock = new Object();
11025
11026 @GuardedBy("mWifiNetworkLock")
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011027 private String[] mWifiIfaces = EmptyArray.STRING;
11028
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011029 @GuardedBy("mWifiNetworkLock")
11030 private NetworkStats mLastWifiNetworkStats = new NetworkStats(0, -1);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011031
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011032 private final Object mModemNetworkLock = new Object();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011033
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011034 @GuardedBy("mModemNetworkLock")
11035 private String[] mModemIfaces = EmptyArray.STRING;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011036
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011037 @GuardedBy("mModemNetworkLock")
11038 private NetworkStats mLastModemNetworkStats = new NetworkStats(0, -1);
11039
11040 private NetworkStats readNetworkStatsLocked(String[] ifaces) {
11041 try {
11042 if (!ArrayUtils.isEmpty(ifaces)) {
11043 return mNetworkStatsFactory.readNetworkStatsDetail(NetworkStats.UID_ALL, ifaces,
11044 NetworkStats.TAG_NONE, mNetworkStatsPool.acquire());
11045 }
11046 } catch (IOException e) {
11047 Slog.e(TAG, "failed to read network stats for ifaces: " + Arrays.toString(ifaces));
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011048 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011049 return null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011050 }
11051
Chenjie Yu89083392018-01-11 14:53:31 -080011052 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011053 * Distribute WiFi energy info and network traffic to apps.
11054 * @param info The energy information from the WiFi controller.
11055 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011056 public void updateWifiState(@Nullable final WifiActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011057 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011058 Slog.d(TAG, "Updating wifi stats: " + Arrays.toString(mWifiIfaces));
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011059 }
11060
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011061 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070011062 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011063 synchronized (mWifiNetworkLock) {
11064 final NetworkStats latestStats = readNetworkStatsLocked(mWifiIfaces);
11065 if (latestStats != null) {
11066 delta = NetworkStats.subtract(latestStats, mLastWifiNetworkStats, null, null,
11067 mNetworkStatsPool.acquire());
11068 mNetworkStatsPool.release(mLastWifiNetworkStats);
11069 mLastWifiNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070011070 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011071 }
11072
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011073 synchronized (this) {
11074 if (!mOnBatteryInternal) {
11075 if (delta != null) {
11076 mNetworkStatsPool.release(delta);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011077 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011078 return;
11079 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011080
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011081 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
11082 SparseLongArray rxPackets = new SparseLongArray();
11083 SparseLongArray txPackets = new SparseLongArray();
11084 long totalTxPackets = 0;
11085 long totalRxPackets = 0;
11086 if (delta != null) {
11087 NetworkStats.Entry entry = new NetworkStats.Entry();
11088 final int size = delta.size();
11089 for (int i = 0; i < size; i++) {
11090 entry = delta.getValues(i, entry);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011091
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011092 if (DEBUG_ENERGY) {
11093 Slog.d(TAG, "Wifi uid " + entry.uid + ": delta rx=" + entry.rxBytes
11094 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
11095 + " txPackets=" + entry.txPackets);
11096 }
11097
11098 if (entry.rxBytes == 0 && entry.txBytes == 0) {
11099 // Skip the lookup below since there is no work to do.
11100 continue;
11101 }
11102
11103 final Uid u = getUidStatsLocked(mapUid(entry.uid));
11104 if (entry.rxBytes != 0) {
11105 u.noteNetworkActivityLocked(NETWORK_WIFI_RX_DATA, entry.rxBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -080011106 entry.rxPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011107 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11108 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_RX_DATA, entry.rxBytes,
11109 entry.rxPackets);
11110 }
11111 mNetworkByteActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
11112 entry.rxBytes);
11113 mNetworkPacketActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
11114 entry.rxPackets);
11115
11116 rxPackets.put(u.getUid(), entry.rxPackets);
11117
11118 // Sum the total number of packets so that the Rx Power can
11119 // be evenly distributed amongst the apps.
11120 totalRxPackets += entry.rxPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -080011121 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011122
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011123 if (entry.txBytes != 0) {
11124 u.noteNetworkActivityLocked(NETWORK_WIFI_TX_DATA, entry.txBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -080011125 entry.txPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011126 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11127 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_TX_DATA, entry.txBytes,
11128 entry.txPackets);
11129 }
11130 mNetworkByteActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
11131 entry.txBytes);
11132 mNetworkPacketActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
11133 entry.txPackets);
11134
11135 txPackets.put(u.getUid(), entry.txPackets);
11136
11137 // Sum the total number of packets so that the Tx Power can
11138 // be evenly distributed amongst the apps.
11139 totalTxPackets += entry.txPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -080011140 }
Adam Lesinskiba88e682015-12-08 12:06:55 -080011141 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011142 mNetworkStatsPool.release(delta);
11143 delta = null;
Adam Lesinskie08af192015-03-25 16:42:59 -070011144 }
11145
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011146 if (info != null) {
11147 mHasWifiReporting = true;
Adam Lesinskie08af192015-03-25 16:42:59 -070011148
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011149 // Measured in mAms
11150 final long txTimeMs = info.getControllerTxTimeMillis();
11151 final long rxTimeMs = info.getControllerRxTimeMillis();
Siddharth Rayb50a6842017-12-14 15:15:28 -080011152 final long scanTimeMs = info.getControllerScanTimeMillis();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011153 final long idleTimeMs = info.getControllerIdleTimeMillis();
11154 final long totalTimeMs = txTimeMs + rxTimeMs + idleTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -070011155
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011156 long leftOverRxTimeMs = rxTimeMs;
11157 long leftOverTxTimeMs = txTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -070011158
Adam Lesinskie08af192015-03-25 16:42:59 -070011159 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011160 Slog.d(TAG, "------ BEGIN WiFi power blaming ------");
11161 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
11162 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
11163 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms");
11164 Slog.d(TAG, " Total Time: " + totalTimeMs + " ms");
Siddharth Rayb50a6842017-12-14 15:15:28 -080011165 Slog.d(TAG, " Scan Time: " + scanTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070011166 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011167
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011168 long totalWifiLockTimeMs = 0;
11169 long totalScanTimeMs = 0;
11170
11171 // On the first pass, collect some totals so that we can normalize power
11172 // calculations if we need to.
11173 final int uidStatsSize = mUidStats.size();
11174 for (int i = 0; i < uidStatsSize; i++) {
11175 final Uid uid = mUidStats.valueAt(i);
11176
11177 // Sum the total scan power for all apps.
11178 totalScanTimeMs += uid.mWifiScanTimer.getTimeSinceMarkLocked(
11179 elapsedRealtimeMs * 1000) / 1000;
11180
11181 // Sum the total time holding wifi lock for all apps.
11182 totalWifiLockTimeMs += uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
11183 elapsedRealtimeMs * 1000) / 1000;
11184 }
11185
11186 if (DEBUG_ENERGY && totalScanTimeMs > rxTimeMs) {
11187 Slog.d(TAG,
11188 " !Estimated scan time > Actual rx time (" + totalScanTimeMs + " ms > "
11189 + rxTimeMs + " ms). Normalizing scan time.");
11190 }
11191 if (DEBUG_ENERGY && totalScanTimeMs > txTimeMs) {
11192 Slog.d(TAG,
11193 " !Estimated scan time > Actual tx time (" + totalScanTimeMs + " ms > "
11194 + txTimeMs + " ms). Normalizing scan time.");
11195 }
11196
11197 // Actually assign and distribute power usage to apps.
11198 for (int i = 0; i < uidStatsSize; i++) {
11199 final Uid uid = mUidStats.valueAt(i);
11200
11201 long scanTimeSinceMarkMs = uid.mWifiScanTimer.getTimeSinceMarkLocked(
11202 elapsedRealtimeMs * 1000) / 1000;
11203 if (scanTimeSinceMarkMs > 0) {
11204 // Set the new mark so that next time we get new data since this point.
11205 uid.mWifiScanTimer.setMark(elapsedRealtimeMs);
11206
11207 long scanRxTimeSinceMarkMs = scanTimeSinceMarkMs;
11208 long scanTxTimeSinceMarkMs = scanTimeSinceMarkMs;
11209
11210 // Our total scan time is more than the reported Tx/Rx time.
11211 // This is possible because the cost of a scan is approximate.
11212 // Let's normalize the result so that we evenly blame each app
11213 // scanning.
11214 //
11215 // This means that we may have apps that transmitted/received packets not be
11216 // blamed for this, but this is fine as scans are relatively more expensive.
11217 if (totalScanTimeMs > rxTimeMs) {
11218 scanRxTimeSinceMarkMs = (rxTimeMs * scanRxTimeSinceMarkMs) /
11219 totalScanTimeMs;
11220 }
11221 if (totalScanTimeMs > txTimeMs) {
11222 scanTxTimeSinceMarkMs = (txTimeMs * scanTxTimeSinceMarkMs) /
11223 totalScanTimeMs;
11224 }
11225
11226 if (DEBUG_ENERGY) {
11227 Slog.d(TAG, " ScanTime for UID " + uid.getUid() + ": Rx:"
11228 + scanRxTimeSinceMarkMs + " ms Tx:"
11229 + scanTxTimeSinceMarkMs + " ms)");
11230 }
11231
11232 ControllerActivityCounterImpl activityCounter =
11233 uid.getOrCreateWifiControllerActivityLocked();
11234 activityCounter.getRxTimeCounter().addCountLocked(scanRxTimeSinceMarkMs);
11235 activityCounter.getTxTimeCounters()[0].addCountLocked(
11236 scanTxTimeSinceMarkMs);
11237 leftOverRxTimeMs -= scanRxTimeSinceMarkMs;
11238 leftOverTxTimeMs -= scanTxTimeSinceMarkMs;
11239 }
11240
11241 // Distribute evenly the power consumed while Idle to each app holding a WiFi
11242 // lock.
11243 final long wifiLockTimeSinceMarkMs =
11244 uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
11245 elapsedRealtimeMs * 1000) / 1000;
11246 if (wifiLockTimeSinceMarkMs > 0) {
11247 // Set the new mark so that next time we get new data since this point.
11248 uid.mFullWifiLockTimer.setMark(elapsedRealtimeMs);
11249
11250 final long myIdleTimeMs = (wifiLockTimeSinceMarkMs * idleTimeMs)
11251 / totalWifiLockTimeMs;
11252 if (DEBUG_ENERGY) {
11253 Slog.d(TAG, " IdleTime for UID " + uid.getUid() + ": "
11254 + myIdleTimeMs + " ms");
11255 }
11256 uid.getOrCreateWifiControllerActivityLocked().getIdleTimeCounter()
11257 .addCountLocked(myIdleTimeMs);
11258 }
11259 }
11260
Adam Lesinskie08af192015-03-25 16:42:59 -070011261 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011262 Slog.d(TAG, " New RxPower: " + leftOverRxTimeMs + " ms");
11263 Slog.d(TAG, " New TxPower: " + leftOverTxTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070011264 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011265
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011266 // Distribute the remaining Tx power appropriately between all apps that transmitted
11267 // packets.
11268 for (int i = 0; i < txPackets.size(); i++) {
11269 final Uid uid = getUidStatsLocked(txPackets.keyAt(i));
11270 final long myTxTimeMs = (txPackets.valueAt(i) * leftOverTxTimeMs)
11271 / totalTxPackets;
11272 if (DEBUG_ENERGY) {
11273 Slog.d(TAG, " TxTime for UID " + uid.getUid() + ": " + myTxTimeMs + " ms");
11274 }
11275 uid.getOrCreateWifiControllerActivityLocked().getTxTimeCounters()[0]
11276 .addCountLocked(myTxTimeMs);
11277 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011278
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011279 // Distribute the remaining Rx power appropriately between all apps that received
11280 // packets.
11281 for (int i = 0; i < rxPackets.size(); i++) {
11282 final Uid uid = getUidStatsLocked(rxPackets.keyAt(i));
11283 final long myRxTimeMs = (rxPackets.valueAt(i) * leftOverRxTimeMs)
11284 / totalRxPackets;
11285 if (DEBUG_ENERGY) {
11286 Slog.d(TAG, " RxTime for UID " + uid.getUid() + ": " + myRxTimeMs + " ms");
11287 }
11288 uid.getOrCreateWifiControllerActivityLocked().getRxTimeCounter()
11289 .addCountLocked(myRxTimeMs);
11290 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011291
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011292 // Any left over power use will be picked up by the WiFi category in BatteryStatsHelper.
11293
11294
11295 // Update WiFi controller stats.
11296 mWifiActivity.getRxTimeCounter().addCountLocked(info.getControllerRxTimeMillis());
11297 mWifiActivity.getTxTimeCounters()[0].addCountLocked(
11298 info.getControllerTxTimeMillis());
Siddharth Rayb50a6842017-12-14 15:15:28 -080011299 mWifiActivity.getScanTimeCounter().addCountLocked(
11300 info.getControllerScanTimeMillis());
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011301 mWifiActivity.getIdleTimeCounter().addCountLocked(
11302 info.getControllerIdleTimeMillis());
11303
11304 // POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11305 final double opVolt = mPowerProfile.getAveragePower(
11306 PowerProfile.POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11307 if (opVolt != 0) {
11308 // We store the power drain as mAms.
11309 mWifiActivity.getPowerCounter().addCountLocked(
11310 (long) (info.getControllerEnergyUsed() / opVolt));
11311 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011312 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011313 }
11314 }
11315
Chenjie Yu89083392018-01-11 14:53:31 -080011316 private ModemActivityInfo mLastModemActivityInfo =
11317 new ModemActivityInfo(0, 0, 0, new int[0], 0, 0);
11318
Chenjie Yua54e54d2018-02-14 20:12:52 -080011319 private ModemActivityInfo getDeltaModemActivityInfo(ModemActivityInfo activityInfo) {
11320 if (activityInfo == null) {
11321 return null;
11322 }
11323 int[] txTimeMs = new int[ModemActivityInfo.TX_POWER_LEVELS];
11324 for (int i = 0; i < ModemActivityInfo.TX_POWER_LEVELS; i++) {
11325 txTimeMs[i] = activityInfo.getTxTimeMillis()[i]
11326 - mLastModemActivityInfo.getTxTimeMillis()[i];
11327 }
11328 ModemActivityInfo deltaInfo = new ModemActivityInfo(activityInfo.getTimestamp(),
11329 activityInfo.getSleepTimeMillis() - mLastModemActivityInfo.getSleepTimeMillis(),
11330 activityInfo.getIdleTimeMillis() - mLastModemActivityInfo.getIdleTimeMillis(),
11331 txTimeMs,
11332 activityInfo.getRxTimeMillis() - mLastModemActivityInfo.getRxTimeMillis(),
11333 activityInfo.getEnergyUsed() - mLastModemActivityInfo.getEnergyUsed());
11334 mLastModemActivityInfo = activityInfo;
11335 return deltaInfo;
11336 }
11337
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011338 /**
11339 * Distribute Cell radio energy info and network traffic to apps.
11340 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011341 public void updateMobileRadioState(@Nullable final ModemActivityInfo activityInfo) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011342 if (DEBUG_ENERGY) {
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011343 Slog.d(TAG, "Updating mobile radio stats with " + activityInfo);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011344 }
Chenjie Yua54e54d2018-02-14 20:12:52 -080011345 ModemActivityInfo deltaInfo = getDeltaModemActivityInfo(activityInfo);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011346
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011347 // Add modem tx power to history.
Chenjie Yua54e54d2018-02-14 20:12:52 -080011348 addModemTxPowerToHistory(deltaInfo);
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011349
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011350 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070011351 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011352 synchronized (mModemNetworkLock) {
11353 final NetworkStats latestStats = readNetworkStatsLocked(mModemIfaces);
11354 if (latestStats != null) {
11355 delta = NetworkStats.subtract(latestStats, mLastModemNetworkStats, null, null,
11356 mNetworkStatsPool.acquire());
11357 mNetworkStatsPool.release(mLastModemNetworkStats);
11358 mLastModemNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070011359 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011360 }
11361
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011362 synchronized (this) {
11363 if (!mOnBatteryInternal) {
11364 if (delta != null) {
11365 mNetworkStatsPool.release(delta);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011366 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011367 return;
Adam Lesinskie08af192015-03-25 16:42:59 -070011368 }
11369
Chenjie Yua54e54d2018-02-14 20:12:52 -080011370 if (deltaInfo != null) {
Siddharth Ray2038af82018-01-17 17:40:26 -080011371 mHasModemReporting = true;
11372 mModemActivity.getIdleTimeCounter().addCountLocked(
Chenjie Yua54e54d2018-02-14 20:12:52 -080011373 deltaInfo.getIdleTimeMillis());
Siddharth Rayed754702018-02-15 12:44:37 -080011374 mModemActivity.getSleepTimeCounter().addCountLocked(
11375 deltaInfo.getSleepTimeMillis());
Chenjie Yua54e54d2018-02-14 20:12:52 -080011376 mModemActivity.getRxTimeCounter().addCountLocked(deltaInfo.getRxTimeMillis());
Siddharth Ray2038af82018-01-17 17:40:26 -080011377 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
11378 mModemActivity.getTxTimeCounters()[lvl]
Chenjie Yua54e54d2018-02-14 20:12:52 -080011379 .addCountLocked(deltaInfo.getTxTimeMillis()[lvl]);
Siddharth Ray2038af82018-01-17 17:40:26 -080011380 }
11381
11382 // POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11383 final double opVolt = mPowerProfile.getAveragePower(
11384 PowerProfile.POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11385 if (opVolt != 0) {
11386 double energyUsed =
Chenjie Yua54e54d2018-02-14 20:12:52 -080011387 deltaInfo.getSleepTimeMillis() *
Siddharth Ray2038af82018-01-17 17:40:26 -080011388 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_SLEEP)
Chenjie Yua54e54d2018-02-14 20:12:52 -080011389 + deltaInfo.getIdleTimeMillis() *
Siddharth Ray2038af82018-01-17 17:40:26 -080011390 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_IDLE)
Chenjie Yua54e54d2018-02-14 20:12:52 -080011391 + deltaInfo.getRxTimeMillis() *
Siddharth Ray2038af82018-01-17 17:40:26 -080011392 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_RX);
Chenjie Yua54e54d2018-02-14 20:12:52 -080011393 int[] txTimeMs = deltaInfo.getTxTimeMillis();
Chenjie Yu89083392018-01-11 14:53:31 -080011394 for (int i = 0; i < Math.min(txTimeMs.length,
Chenjie Yua54e54d2018-02-14 20:12:52 -080011395 SignalStrength.NUM_SIGNAL_STRENGTH_BINS); i++) {
Chenjie Yu89083392018-01-11 14:53:31 -080011396 energyUsed += txTimeMs[i] * mPowerProfile.getAveragePower(
Chenjie Yua54e54d2018-02-14 20:12:52 -080011397 PowerProfile.POWER_MODEM_CONTROLLER_TX, i);
Siddharth Ray2038af82018-01-17 17:40:26 -080011398 }
11399
11400 // We store the power drain as mAms.
11401 mModemActivity.getPowerCounter().addCountLocked((long) energyUsed);
11402 }
11403 }
11404
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070011405 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011406 long radioTime = mMobileRadioActivePerAppTimer.getTimeSinceMarkLocked(
11407 elapsedRealtimeMs * 1000);
11408 mMobileRadioActivePerAppTimer.setMark(elapsedRealtimeMs);
11409
11410 long totalRxPackets = 0;
11411 long totalTxPackets = 0;
11412 if (delta != null) {
11413 NetworkStats.Entry entry = new NetworkStats.Entry();
11414 final int size = delta.size();
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011415 for (int i = 0; i < size; i++) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011416 entry = delta.getValues(i, entry);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011417 if (entry.rxPackets == 0 && entry.txPackets == 0) {
11418 continue;
11419 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011420
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011421 if (DEBUG_ENERGY) {
11422 Slog.d(TAG, "Mobile uid " + entry.uid + ": delta rx=" + entry.rxBytes
11423 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
11424 + " txPackets=" + entry.txPackets);
11425 }
11426
11427 totalRxPackets += entry.rxPackets;
11428 totalTxPackets += entry.txPackets;
11429
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011430 final Uid u = getUidStatsLocked(mapUid(entry.uid));
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011431 u.noteNetworkActivityLocked(NETWORK_MOBILE_RX_DATA, entry.rxBytes,
11432 entry.rxPackets);
11433 u.noteNetworkActivityLocked(NETWORK_MOBILE_TX_DATA, entry.txBytes,
11434 entry.txPackets);
11435 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11436 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_RX_DATA,
11437 entry.rxBytes, entry.rxPackets);
11438 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_TX_DATA,
11439 entry.txBytes, entry.txPackets);
11440 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011441
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011442 mNetworkByteActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
11443 entry.rxBytes);
11444 mNetworkByteActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
11445 entry.txBytes);
11446 mNetworkPacketActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
11447 entry.rxPackets);
11448 mNetworkPacketActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
11449 entry.txPackets);
11450 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011451
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011452 // Now distribute proportional blame to the apps that did networking.
11453 long totalPackets = totalRxPackets + totalTxPackets;
11454 if (totalPackets > 0) {
11455 for (int i = 0; i < size; i++) {
11456 entry = delta.getValues(i, entry);
11457 if (entry.rxPackets == 0 && entry.txPackets == 0) {
11458 continue;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011459 }
11460
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011461 final Uid u = getUidStatsLocked(mapUid(entry.uid));
11462
11463 // Distribute total radio active time in to this app.
11464 final long appPackets = entry.rxPackets + entry.txPackets;
11465 final long appRadioTime = (radioTime * appPackets) / totalPackets;
11466 u.noteMobileRadioActiveTimeLocked(appRadioTime);
11467
11468 // Remove this app from the totals, so that we don't lose any time
11469 // due to rounding.
11470 radioTime -= appRadioTime;
11471 totalPackets -= appPackets;
11472
Chenjie Yua54e54d2018-02-14 20:12:52 -080011473 if (deltaInfo != null) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011474 ControllerActivityCounterImpl activityCounter =
11475 u.getOrCreateModemControllerActivityLocked();
11476 if (totalRxPackets > 0 && entry.rxPackets > 0) {
Chenjie Yua54e54d2018-02-14 20:12:52 -080011477 final long rxMs = (entry.rxPackets * deltaInfo.getRxTimeMillis())
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011478 / totalRxPackets;
11479 activityCounter.getRxTimeCounter().addCountLocked(rxMs);
11480 }
11481
11482 if (totalTxPackets > 0 && entry.txPackets > 0) {
11483 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
11484 long txMs =
Chenjie Yua54e54d2018-02-14 20:12:52 -080011485 entry.txPackets * deltaInfo.getTxTimeMillis()[lvl];
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011486 txMs /= totalTxPackets;
11487 activityCounter.getTxTimeCounters()[lvl].addCountLocked(txMs);
11488 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011489 }
11490 }
11491 }
11492 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011493
11494 if (radioTime > 0) {
11495 // Whoops, there is some radio time we can't blame on an app!
11496 mMobileRadioActiveUnknownTime.addCountLocked(radioTime);
11497 mMobileRadioActiveUnknownCount.addCountLocked(1);
11498 }
11499
11500 mNetworkStatsPool.release(delta);
11501 delta = null;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011502 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011503 }
11504 }
11505
11506 /**
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011507 * Add modem tx power to history
11508 * Device is said to be in high cellular transmit power when it has spent most of the transmit
11509 * time at the highest power level.
11510 * @param activityInfo
11511 */
Siddharth Raya67fb562018-02-28 13:46:16 -080011512 private synchronized void addModemTxPowerToHistory(final ModemActivityInfo activityInfo) {
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011513 if (activityInfo == null) {
11514 return;
11515 }
11516 int[] txTimeMs = activityInfo.getTxTimeMillis();
11517 if (txTimeMs == null || txTimeMs.length != ModemActivityInfo.TX_POWER_LEVELS) {
11518 return;
11519 }
11520 final long elapsedRealtime = mClocks.elapsedRealtime();
11521 final long uptime = mClocks.uptimeMillis();
11522 int levelMaxTimeSpent = 0;
11523 for (int i = 1; i < txTimeMs.length; i++) {
11524 if (txTimeMs[i] > txTimeMs[levelMaxTimeSpent]) {
11525 levelMaxTimeSpent = i;
11526 }
11527 }
11528 if (levelMaxTimeSpent == ModemActivityInfo.TX_POWER_LEVELS - 1) {
11529 if (!mIsCellularTxPowerHigh) {
11530 mHistoryCur.states2 |= HistoryItem.STATE2_CELLULAR_HIGH_TX_POWER_FLAG;
11531 addHistoryRecordLocked(elapsedRealtime, uptime);
11532 mIsCellularTxPowerHigh = true;
11533 }
11534 return;
11535 }
11536 if (mIsCellularTxPowerHigh) {
11537 mHistoryCur.states2 &= ~HistoryItem.STATE2_CELLULAR_HIGH_TX_POWER_FLAG;
11538 addHistoryRecordLocked(elapsedRealtime, uptime);
11539 mIsCellularTxPowerHigh = false;
11540 }
11541 return;
11542 }
11543
Mike Ma561a8d92018-03-20 18:24:05 -070011544 private final class BluetoothActivityInfoCache {
11545 long idleTimeMs;
11546 long rxTimeMs;
11547 long txTimeMs;
11548 long energy;
11549
11550 SparseLongArray uidRxBytes = new SparseLongArray();
11551 SparseLongArray uidTxBytes = new SparseLongArray();
11552
11553 void set(BluetoothActivityEnergyInfo info) {
11554 idleTimeMs = info.getControllerIdleTimeMillis();
11555 rxTimeMs = info.getControllerRxTimeMillis();
11556 txTimeMs = info.getControllerTxTimeMillis();
11557 energy = info.getControllerEnergyUsed();
11558 if (info.getUidTraffic() != null) {
11559 for (UidTraffic traffic : info.getUidTraffic()) {
11560 uidRxBytes.put(traffic.getUid(), traffic.getRxBytes());
11561 uidTxBytes.put(traffic.getUid(), traffic.getTxBytes());
11562 }
11563 }
11564 }
11565 }
11566
11567 private final BluetoothActivityInfoCache mLastBluetoothActivityInfo
11568 = new BluetoothActivityInfoCache();
11569
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011570 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011571 * Distribute Bluetooth energy info and network traffic to apps.
Mike Ma561a8d92018-03-20 18:24:05 -070011572 *
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011573 * @param info The energy information from the bluetooth controller.
11574 */
11575 public void updateBluetoothStateLocked(@Nullable final BluetoothActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011576 if (DEBUG_ENERGY) {
Adam Lesinski50e47602015-12-04 17:04:54 -080011577 Slog.d(TAG, "Updating bluetooth stats: " + info);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011578 }
11579
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011580 if (info == null || !mOnBatteryInternal) {
11581 return;
11582 }
Adam Lesinskie283d332015-04-16 12:29:25 -070011583
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011584 mHasBluetoothReporting = true;
11585
Bookatz867c0d72017-03-07 18:23:42 -080011586 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Mike Ma561a8d92018-03-20 18:24:05 -070011587 final long rxTimeMs =
11588 info.getControllerRxTimeMillis() - mLastBluetoothActivityInfo.rxTimeMs;
11589 final long txTimeMs =
11590 info.getControllerTxTimeMillis() - mLastBluetoothActivityInfo.txTimeMs;
11591 final long idleTimeMs =
11592 info.getControllerIdleTimeMillis() - mLastBluetoothActivityInfo.idleTimeMs;
11593
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011594 if (DEBUG_ENERGY) {
11595 Slog.d(TAG, "------ BEGIN BLE power blaming ------");
11596 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
11597 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
Chenjie Yu89083392018-01-11 14:53:31 -080011598 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms");
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011599 }
11600
11601 long totalScanTimeMs = 0;
11602
11603 final int uidCount = mUidStats.size();
11604 for (int i = 0; i < uidCount; i++) {
11605 final Uid u = mUidStats.valueAt(i);
11606 if (u.mBluetoothScanTimer == null) {
11607 continue;
Adam Lesinskie283d332015-04-16 12:29:25 -070011608 }
Adam Lesinski50e47602015-12-04 17:04:54 -080011609
Bookatzaa4594a2017-03-24 12:39:56 -070011610 totalScanTimeMs += u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011611 elapsedRealtimeMs * 1000) / 1000;
11612 }
11613
11614 final boolean normalizeScanRxTime = (totalScanTimeMs > rxTimeMs);
11615 final boolean normalizeScanTxTime = (totalScanTimeMs > txTimeMs);
11616
11617 if (DEBUG_ENERGY) {
11618 Slog.d(TAG, "Normalizing scan power for RX=" + normalizeScanRxTime
11619 + " TX=" + normalizeScanTxTime);
11620 }
11621
11622 long leftOverRxTimeMs = rxTimeMs;
11623 long leftOverTxTimeMs = txTimeMs;
11624
11625 for (int i = 0; i < uidCount; i++) {
11626 final Uid u = mUidStats.valueAt(i);
11627 if (u.mBluetoothScanTimer == null) {
11628 continue;
11629 }
11630
Bookatzaa4594a2017-03-24 12:39:56 -070011631 long scanTimeSinceMarkMs = u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011632 elapsedRealtimeMs * 1000) / 1000;
11633 if (scanTimeSinceMarkMs > 0) {
11634 // Set the new mark so that next time we get new data since this point.
11635 u.mBluetoothScanTimer.setMark(elapsedRealtimeMs);
11636
11637 long scanTimeRxSinceMarkMs = scanTimeSinceMarkMs;
11638 long scanTimeTxSinceMarkMs = scanTimeSinceMarkMs;
11639
11640 if (normalizeScanRxTime) {
11641 // Scan time is longer than the total rx time in the controller,
11642 // so distribute the scan time proportionately. This means regular traffic
11643 // will not blamed, but scans are more expensive anyways.
11644 scanTimeRxSinceMarkMs = (rxTimeMs * scanTimeRxSinceMarkMs) / totalScanTimeMs;
11645 }
11646
11647 if (normalizeScanTxTime) {
11648 // Scan time is longer than the total tx time in the controller,
11649 // so distribute the scan time proportionately. This means regular traffic
11650 // will not blamed, but scans are more expensive anyways.
11651 scanTimeTxSinceMarkMs = (txTimeMs * scanTimeTxSinceMarkMs) / totalScanTimeMs;
11652 }
11653
11654 final ControllerActivityCounterImpl counter =
11655 u.getOrCreateBluetoothControllerActivityLocked();
11656 counter.getRxTimeCounter().addCountLocked(scanTimeRxSinceMarkMs);
11657 counter.getTxTimeCounters()[0].addCountLocked(scanTimeTxSinceMarkMs);
11658
11659 leftOverRxTimeMs -= scanTimeRxSinceMarkMs;
11660 leftOverTxTimeMs -= scanTimeTxSinceMarkMs;
11661 }
11662 }
11663
11664 if (DEBUG_ENERGY) {
Mike Ma561a8d92018-03-20 18:24:05 -070011665 Slog.d(TAG, "Left over time for traffic RX=" + leftOverRxTimeMs + " TX="
11666 + leftOverTxTimeMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011667 }
11668
11669 //
11670 // Now distribute blame to apps that did bluetooth traffic.
11671 //
11672
11673 long totalTxBytes = 0;
11674 long totalRxBytes = 0;
11675
11676 final UidTraffic[] uidTraffic = info.getUidTraffic();
Mike Ma561a8d92018-03-20 18:24:05 -070011677 final int numUids = uidTraffic != null ? uidTraffic.length : 0;
11678 for (int i = 0; i < numUids; i++) {
11679 final UidTraffic traffic = uidTraffic[i];
11680 final long rxBytes = traffic.getRxBytes() - mLastBluetoothActivityInfo.uidRxBytes.get(
11681 traffic.getUid());
11682 final long txBytes = traffic.getTxBytes() - mLastBluetoothActivityInfo.uidTxBytes.get(
11683 traffic.getUid());
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011684
11685 // Add to the global counters.
Mike Ma561a8d92018-03-20 18:24:05 -070011686 mNetworkByteActivityCounters[NETWORK_BT_RX_DATA].addCountLocked(rxBytes);
11687 mNetworkByteActivityCounters[NETWORK_BT_TX_DATA].addCountLocked(txBytes);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011688
11689 // Add to the UID counters.
11690 final Uid u = getUidStatsLocked(mapUid(traffic.getUid()));
Mike Ma561a8d92018-03-20 18:24:05 -070011691 u.noteNetworkActivityLocked(NETWORK_BT_RX_DATA, rxBytes, 0);
11692 u.noteNetworkActivityLocked(NETWORK_BT_TX_DATA, txBytes, 0);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011693
11694 // Calculate the total traffic.
Mike Ma561a8d92018-03-20 18:24:05 -070011695 totalRxBytes += rxBytes;
11696 totalTxBytes += txBytes;
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011697 }
11698
Mike Ma561a8d92018-03-20 18:24:05 -070011699 if ((totalTxBytes != 0 || totalRxBytes != 0) && (leftOverRxTimeMs != 0
11700 || leftOverTxTimeMs != 0)) {
11701 for (int i = 0; i < numUids; i++) {
11702 final UidTraffic traffic = uidTraffic[i];
11703 final int uid = traffic.getUid();
11704 final long rxBytes =
11705 traffic.getRxBytes() - mLastBluetoothActivityInfo.uidRxBytes.get(uid);
11706 final long txBytes =
11707 traffic.getTxBytes() - mLastBluetoothActivityInfo.uidTxBytes.get(uid);
Adam Lesinski50e47602015-12-04 17:04:54 -080011708
Mike Ma561a8d92018-03-20 18:24:05 -070011709 final Uid u = getUidStatsLocked(mapUid(uid));
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011710 final ControllerActivityCounterImpl counter =
11711 u.getOrCreateBluetoothControllerActivityLocked();
11712
Mike Ma561a8d92018-03-20 18:24:05 -070011713 if (totalRxBytes > 0 && rxBytes > 0) {
11714 final long timeRxMs = (leftOverRxTimeMs * rxBytes) / totalRxBytes;
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011715 if (DEBUG_ENERGY) {
Mike Ma561a8d92018-03-20 18:24:05 -070011716 Slog.d(TAG, "UID=" + uid + " rx_bytes=" + rxBytes + " rx_time=" + timeRxMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011717 }
11718 counter.getRxTimeCounter().addCountLocked(timeRxMs);
11719 leftOverRxTimeMs -= timeRxMs;
11720 }
11721
Mike Ma561a8d92018-03-20 18:24:05 -070011722 if (totalTxBytes > 0 && txBytes > 0) {
11723 final long timeTxMs = (leftOverTxTimeMs * txBytes) / totalTxBytes;
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011724 if (DEBUG_ENERGY) {
Mike Ma561a8d92018-03-20 18:24:05 -070011725 Slog.d(TAG, "UID=" + uid + " tx_bytes=" + txBytes + " tx_time=" + timeTxMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011726 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011727 counter.getTxTimeCounters()[0].addCountLocked(timeTxMs);
11728 leftOverTxTimeMs -= timeTxMs;
11729 }
Adam Lesinski50e47602015-12-04 17:04:54 -080011730 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011731 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011732
Chenjie Yu89083392018-01-11 14:53:31 -080011733 mBluetoothActivity.getRxTimeCounter().addCountLocked(rxTimeMs);
11734 mBluetoothActivity.getTxTimeCounters()[0].addCountLocked(txTimeMs);
11735 mBluetoothActivity.getIdleTimeCounter().addCountLocked(idleTimeMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011736
11737 // POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11738 final double opVolt = mPowerProfile.getAveragePower(
11739 PowerProfile.POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11740 if (opVolt != 0) {
11741 // We store the power drain as mAms.
11742 mBluetoothActivity.getPowerCounter().addCountLocked(
Mike Ma561a8d92018-03-20 18:24:05 -070011743 (long) ((info.getControllerEnergyUsed() - mLastBluetoothActivityInfo.energy)
11744 / opVolt));
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011745 }
Mike Ma561a8d92018-03-20 18:24:05 -070011746 mLastBluetoothActivityInfo.set(info);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011747 }
11748
11749 /**
Bookatz0b8a0502017-09-13 11:51:52 -070011750 * Read and record Resource Power Manager (RPM) state and voter times.
11751 * If RPM stats were fetched more recently than RPM_STATS_UPDATE_FREQ_MS ago, uses the old data
11752 * instead of fetching it anew.
Bookatz50df7112017-08-04 14:53:26 -070011753 */
11754 public void updateRpmStatsLocked() {
11755 if (mPlatformIdleStateCallback == null) return;
Bookatz0b8a0502017-09-13 11:51:52 -070011756 long now = SystemClock.elapsedRealtime();
11757 if (now - mLastRpmStatsUpdateTimeMs >= RPM_STATS_UPDATE_FREQ_MS) {
11758 mPlatformIdleStateCallback.fillLowPowerStats(mTmpRpmStats);
11759 mLastRpmStatsUpdateTimeMs = now;
11760 }
Bookatz50df7112017-08-04 14:53:26 -070011761
11762 for (Map.Entry<String, RpmStats.PowerStatePlatformSleepState> pstate
11763 : mTmpRpmStats.mPlatformLowPowerStats.entrySet()) {
11764
11765 // Update values for this platform state.
11766 final String pName = pstate.getKey();
11767 final long pTimeUs = pstate.getValue().mTimeMs * 1000;
11768 final int pCount = pstate.getValue().mCount;
11769 getRpmTimerLocked(pName).update(pTimeUs, pCount);
Bookatz82b341172017-09-07 19:06:08 -070011770 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11771 getScreenOffRpmTimerLocked(pName).update(pTimeUs, pCount);
11772 }
Bookatz50df7112017-08-04 14:53:26 -070011773
11774 // Update values for each voter of this platform state.
11775 for (Map.Entry<String, RpmStats.PowerStateElement> voter
11776 : pstate.getValue().mVoters.entrySet()) {
11777 final String vName = pName + "." + voter.getKey();
11778 final long vTimeUs = voter.getValue().mTimeMs * 1000;
11779 final int vCount = voter.getValue().mCount;
11780 getRpmTimerLocked(vName).update(vTimeUs, vCount);
Bookatz82b341172017-09-07 19:06:08 -070011781 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11782 getScreenOffRpmTimerLocked(vName).update(vTimeUs, vCount);
11783 }
Bookatz50df7112017-08-04 14:53:26 -070011784 }
11785 }
11786
11787 for (Map.Entry<String, RpmStats.PowerStateSubsystem> subsys
11788 : mTmpRpmStats.mSubsystemLowPowerStats.entrySet()) {
11789
11790 final String subsysName = subsys.getKey();
11791 for (Map.Entry<String, RpmStats.PowerStateElement> sstate
11792 : subsys.getValue().mStates.entrySet()) {
11793 final String name = subsysName + "." + sstate.getKey();
11794 final long timeUs = sstate.getValue().mTimeMs * 1000;
11795 final int count = sstate.getValue().mCount;
11796 getRpmTimerLocked(name).update(timeUs, count);
Bookatz82b341172017-09-07 19:06:08 -070011797 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11798 getScreenOffRpmTimerLocked(name).update(timeUs, count);
11799 }
Bookatz50df7112017-08-04 14:53:26 -070011800 }
11801 }
11802 }
11803
11804 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011805 * Read and distribute kernel wake lock use across apps.
11806 */
11807 public void updateKernelWakelocksLocked() {
11808 final KernelWakelockStats wakelockStats = mKernelWakelockReader.readKernelWakelockStats(
11809 mTmpWakelockStats);
11810 if (wakelockStats == null) {
11811 // Not crashing might make board bringup easier.
11812 Slog.w(TAG, "Couldn't get kernel wake lock stats");
11813 return;
11814 }
11815
11816 for (Map.Entry<String, KernelWakelockStats.Entry> ent : wakelockStats.entrySet()) {
11817 String name = ent.getKey();
11818 KernelWakelockStats.Entry kws = ent.getValue();
11819
11820 SamplingTimer kwlt = mKernelWakelockStats.get(name);
11821 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -070011822 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011823 mKernelWakelockStats.put(name, kwlt);
11824 }
Adam Lesinskid84ad302016-05-17 18:31:02 -070011825
Adam Lesinski757c6ea2016-04-21 09:55:41 -070011826 kwlt.update(kws.mTotalTime, kws.mCount);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011827 kwlt.setUpdateVersion(kws.mVersion);
11828 }
11829
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011830 int numWakelocksSetStale = 0;
Adam Lesinskid84ad302016-05-17 18:31:02 -070011831 // Set timers to stale if they didn't appear in /d/wakeup_sources (or /proc/wakelocks)
11832 // this time.
11833 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
11834 SamplingTimer st = ent.getValue();
11835 if (st.getUpdateVersion() != wakelockStats.kernelWakelockVersion) {
11836 st.endSample();
11837 numWakelocksSetStale++;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011838 }
11839 }
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011840
Adam Lesinskid84ad302016-05-17 18:31:02 -070011841 // Record whether we've seen a non-zero time (for debugging b/22716723).
11842 if (wakelockStats.isEmpty()) {
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011843 Slog.wtf(TAG, "All kernel wakelocks had time of zero");
11844 }
11845
11846 if (numWakelocksSetStale == mKernelWakelockStats.size()) {
11847 Slog.wtf(TAG, "All kernel wakelocks were set stale. new version=" +
11848 wakelockStats.kernelWakelockVersion);
11849 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011850 }
11851
Adam Lesinski72478f02015-06-17 15:39:43 -070011852 // We use an anonymous class to access these variables,
11853 // so they can't live on the stack or they'd have to be
11854 // final MutableLong objects (more allocations).
11855 // Used in updateCpuTimeLocked().
11856 long mTempTotalCpuUserTimeUs;
11857 long mTempTotalCpuSystemTimeUs;
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011858 long[][] mWakeLockAllocationsUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070011859
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011860 /**
James Carr3a226052016-07-01 14:49:52 -070011861 * Reads the newest memory stats from the kernel.
11862 */
11863 public void updateKernelMemoryBandwidthLocked() {
11864 mKernelMemoryBandwidthStats.updateStats();
11865 LongSparseLongArray bandwidthEntries = mKernelMemoryBandwidthStats.getBandwidthEntries();
11866 final int bandwidthEntryCount = bandwidthEntries.size();
11867 int index;
11868 for (int i = 0; i < bandwidthEntryCount; i++) {
11869 SamplingTimer timer;
11870 if ((index = mKernelMemoryStats.indexOfKey(bandwidthEntries.keyAt(i))) >= 0) {
11871 timer = mKernelMemoryStats.valueAt(index);
11872 } else {
11873 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
11874 mKernelMemoryStats.put(bandwidthEntries.keyAt(i), timer);
11875 }
11876 timer.update(bandwidthEntries.valueAt(i), 1);
11877 if (DEBUG_MEMORY) {
11878 Slog.d(TAG, String.format("Added entry %d and updated timer to: "
11879 + "mUnpluggedReportedTotalTime %d size %d", bandwidthEntries.keyAt(i),
11880 mKernelMemoryStats.get(
11881 bandwidthEntries.keyAt(i)).mUnpluggedReportedTotalTime,
11882 mKernelMemoryStats.size()));
11883 }
11884 }
11885 }
11886
Sudheer Shankac57729a2018-02-09 15:44:42 -080011887 public boolean isOnBatteryLocked() {
11888 return mOnBatteryTimeBase.isRunning();
11889 }
11890
11891 public boolean isOnBatteryScreenOffLocked() {
11892 return mOnBatteryScreenOffTimeBase.isRunning();
11893 }
11894
James Carr3a226052016-07-01 14:49:52 -070011895 /**
Adam Lesinski72478f02015-06-17 15:39:43 -070011896 * Read and distribute CPU usage across apps. If their are partial wakelocks being held
11897 * and we are on battery with screen off, we give more of the cpu time to those apps holding
11898 * wakelocks. If the screen is on, we just assign the actual cpu time an app used.
Sudheer Shankac57729a2018-02-09 15:44:42 -080011899 * It's possible this will be invoked after the internal battery/screen states are updated, so
11900 * passing the appropriate battery/screen states to try attribute the cpu times to correct
11901 * buckets.
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011902 */
Andreas Gampe3f24e692018-02-05 13:24:28 -080011903 @GuardedBy("this")
Sudheer Shankac57729a2018-02-09 15:44:42 -080011904 public void updateCpuTimeLocked(boolean onBattery, boolean onBatteryScreenOff) {
Adam Lesinski52290c9c2015-09-21 16:54:52 -070011905 if (mPowerProfile == null) {
11906 return;
11907 }
11908
Adam Lesinski72478f02015-06-17 15:39:43 -070011909 if (DEBUG_ENERGY_CPU) {
11910 Slog.d(TAG, "!Cpu updating!");
11911 }
11912
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011913 if (mCpuFreqs == null) {
11914 mCpuFreqs = mKernelUidCpuFreqTimeReader.readFreqs(mPowerProfile);
11915 }
11916
Sudheer Shanka38383232017-07-25 09:55:03 -070011917 // Calculate the wakelocks we have to distribute amongst. The system is excluded as it is
11918 // usually holding the wakelock on behalf of an app.
11919 // And Only distribute cpu power to wakelocks if the screen is off and we're on battery.
11920 ArrayList<StopwatchTimer> partialTimersToConsider = null;
Sudheer Shankac57729a2018-02-09 15:44:42 -080011921 if (onBatteryScreenOff) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011922 partialTimersToConsider = new ArrayList<>();
11923 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070011924 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070011925 // Since the collection and blaming of wakelocks can be scheduled to run after
11926 // some delay, the mPartialTimers list may have new entries. We can't blame
11927 // the newly added timer for past cpu time, so we only consider timers that
11928 // were present for one round of collection. Once a timer has gone through
11929 // a round of collection, its mInList field is set to true.
Adam Lesinski72478f02015-06-17 15:39:43 -070011930 if (timer.mInList && timer.mUid != null && timer.mUid.mUid != Process.SYSTEM_UID) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011931 partialTimersToConsider.add(timer);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011932 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011933 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011934 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011935 markPartialTimersAsEligible();
Adam Lesinski72478f02015-06-17 15:39:43 -070011936
Sudheer Shanka38383232017-07-25 09:55:03 -070011937 // When the battery is not on, we don't attribute the cpu times to any timers but we still
11938 // need to take the snapshots.
Sudheer Shankac57729a2018-02-09 15:44:42 -080011939 if (!onBattery) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011940 mKernelUidCpuTimeReader.readDelta(null);
11941 mKernelUidCpuFreqTimeReader.readDelta(null);
Mike Ma234d1822018-03-13 18:53:21 -070011942 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080011943 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
11944 mKernelUidCpuActiveTimeReader.readDelta(null);
11945 mKernelUidCpuClusterTimeReader.readDelta(null);
Mike Ma234d1822018-03-13 18:53:21 -070011946 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080011947 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011948 for (int cluster = mKernelCpuSpeedReaders.length - 1; cluster >= 0; --cluster) {
11949 mKernelCpuSpeedReaders[cluster].readDelta();
11950 }
11951 return;
11952 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011953
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070011954 mUserInfoProvider.refreshUserIds();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011955 final SparseLongArray updatedUids = mKernelUidCpuFreqTimeReader.perClusterTimesAvailable()
11956 ? null : new SparseLongArray();
Sudheer Shankac57729a2018-02-09 15:44:42 -080011957 readKernelUidCpuTimesLocked(partialTimersToConsider, updatedUids, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011958 // updatedUids=null means /proc/uid_time_in_state provides snapshots of per-cluster cpu
11959 // freqs, so no need to approximate these values.
11960 if (updatedUids != null) {
Sudheer Shankac57729a2018-02-09 15:44:42 -080011961 updateClusterSpeedTimes(updatedUids, onBattery);
Sudheer Shanka671985f2017-05-19 11:33:42 -070011962 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080011963 readKernelUidCpuFreqTimesLocked(partialTimersToConsider, onBattery, onBatteryScreenOff);
Mike Ma234d1822018-03-13 18:53:21 -070011964 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080011965 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
Sudheer Shankac57729a2018-02-09 15:44:42 -080011966 readKernelUidCpuActiveTimesLocked(onBattery);
11967 readKernelUidCpuClusterTimesLocked(onBattery);
Mike Ma234d1822018-03-13 18:53:21 -070011968 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080011969 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011970 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070011971
Sudheer Shanka38383232017-07-25 09:55:03 -070011972 /**
11973 * Mark the current partial timers as gone through a collection so that they will be
11974 * considered in the next cpu times distribution to wakelock holders.
11975 */
11976 @VisibleForTesting
11977 public void markPartialTimersAsEligible() {
11978 if (ArrayUtils.referenceEquals(mPartialTimers, mLastPartialTimers)) {
11979 // No difference, so each timer is now considered for the next collection.
11980 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
11981 mPartialTimers.get(i).mInList = true;
11982 }
11983 } else {
11984 // The lists are different, meaning we added (or removed a timer) since the last
11985 // collection.
11986 for (int i = mLastPartialTimers.size() - 1; i >= 0; --i) {
11987 mLastPartialTimers.get(i).mInList = false;
11988 }
11989 mLastPartialTimers.clear();
Adam Lesinski72478f02015-06-17 15:39:43 -070011990
Sudheer Shanka38383232017-07-25 09:55:03 -070011991 // Mark the current timers as gone through a collection.
11992 final int numPartialTimers = mPartialTimers.size();
11993 for (int i = 0; i < numPartialTimers; ++i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070011994 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070011995 timer.mInList = true;
11996 mLastPartialTimers.add(timer);
Adam Lesinski72478f02015-06-17 15:39:43 -070011997 }
11998 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011999 }
Adam Lesinski72478f02015-06-17 15:39:43 -070012000
Sudheer Shanka38383232017-07-25 09:55:03 -070012001 /**
12002 * Take snapshot of cpu times (aggregated over all uids) at different frequencies and
12003 * calculate cpu times spent by each uid at different frequencies.
12004 *
12005 * @param updatedUids The uids for which times spent at different frequencies are calculated.
12006 */
12007 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012008 public void updateClusterSpeedTimes(@NonNull SparseLongArray updatedUids, boolean onBattery) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070012009 long totalCpuClustersTimeMs = 0;
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012010 // Read the time spent for each cluster at various cpu frequencies.
Sudheer Shankaaf857412017-07-21 00:14:24 -070012011 final long[][] clusterSpeedTimesMs = new long[mKernelCpuSpeedReaders.length][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012012 for (int cluster = 0; cluster < mKernelCpuSpeedReaders.length; cluster++) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070012013 clusterSpeedTimesMs[cluster] = mKernelCpuSpeedReaders[cluster].readDelta();
12014 if (clusterSpeedTimesMs[cluster] != null) {
12015 for (int speed = clusterSpeedTimesMs[cluster].length - 1; speed >= 0; --speed) {
12016 totalCpuClustersTimeMs += clusterSpeedTimesMs[cluster][speed];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012017 }
12018 }
12019 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070012020 if (totalCpuClustersTimeMs != 0) {
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012021 // We have cpu times per freq aggregated over all uids but we need the times per uid.
12022 // So, we distribute total time spent by an uid to different cpu freqs based on the
12023 // amount of time cpu was running at that freq.
12024 final int updatedUidsCount = updatedUids.size();
12025 for (int i = 0; i < updatedUidsCount; ++i) {
12026 final Uid u = getUidStatsLocked(updatedUids.keyAt(i));
Sudheer Shankaaf857412017-07-21 00:14:24 -070012027 final long appCpuTimeUs = updatedUids.valueAt(i);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012028 // Add the cpu speeds to this UID.
12029 final int numClusters = mPowerProfile.getNumCpuClusters();
Sudheer Shanka38383232017-07-25 09:55:03 -070012030 if (u.mCpuClusterSpeedTimesUs == null ||
12031 u.mCpuClusterSpeedTimesUs.length != numClusters) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070012032 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012033 }
12034
Sudheer Shankaaf857412017-07-21 00:14:24 -070012035 for (int cluster = 0; cluster < clusterSpeedTimesMs.length; cluster++) {
12036 final int speedsInCluster = clusterSpeedTimesMs[cluster].length;
12037 if (u.mCpuClusterSpeedTimesUs[cluster] == null || speedsInCluster !=
12038 u.mCpuClusterSpeedTimesUs[cluster].length) {
12039 u.mCpuClusterSpeedTimesUs[cluster]
12040 = new LongSamplingCounter[speedsInCluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012041 }
12042
Sudheer Shankaaf857412017-07-21 00:14:24 -070012043 final LongSamplingCounter[] cpuSpeeds = u.mCpuClusterSpeedTimesUs[cluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012044 for (int speed = 0; speed < speedsInCluster; speed++) {
12045 if (cpuSpeeds[speed] == null) {
12046 cpuSpeeds[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
12047 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070012048 cpuSpeeds[speed].addCountLocked(appCpuTimeUs
12049 * clusterSpeedTimesMs[cluster][speed]
Sudheer Shankac57729a2018-02-09 15:44:42 -080012050 / totalCpuClustersTimeMs, onBattery);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012051 }
12052 }
12053 }
12054 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012055 }
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012056
Sudheer Shanka38383232017-07-25 09:55:03 -070012057 /**
12058 * Take a snapshot of the cpu times spent by each uid and update the corresponding counters.
12059 * If {@param partialTimers} is not null and empty, then we assign a portion of cpu times to
12060 * wakelock holders.
12061 *
12062 * @param partialTimers The wakelock holders among which the cpu times will be distributed.
12063 * @param updatedUids If not null, then the uids found in the snapshot will be added to this.
12064 */
12065 @VisibleForTesting
12066 public void readKernelUidCpuTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers,
Sudheer Shankac57729a2018-02-09 15:44:42 -080012067 @Nullable SparseLongArray updatedUids, boolean onBattery) {
Sudheer Shanka38383232017-07-25 09:55:03 -070012068 mTempTotalCpuUserTimeUs = mTempTotalCpuSystemTimeUs = 0;
12069 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
12070 final long startTimeMs = mClocks.uptimeMillis();
Adam Lesinski72478f02015-06-17 15:39:43 -070012071
Sudheer Shanka38383232017-07-25 09:55:03 -070012072 mKernelUidCpuTimeReader.readDelta((uid, userTimeUs, systemTimeUs) -> {
12073 uid = mapUid(uid);
12074 if (Process.isIsolated(uid)) {
12075 // This could happen if the isolated uid mapping was removed before that process
12076 // was actually killed.
12077 mKernelUidCpuTimeReader.removeUid(uid);
12078 Slog.d(TAG, "Got readings for an isolated uid with no mapping: " + uid);
12079 return;
12080 }
12081 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12082 Slog.d(TAG, "Got readings for an invalid user's uid " + uid);
12083 mKernelUidCpuTimeReader.removeUid(uid);
12084 return;
12085 }
12086 final Uid u = getUidStatsLocked(uid);
12087
12088 // Accumulate the total system and user time.
12089 mTempTotalCpuUserTimeUs += userTimeUs;
12090 mTempTotalCpuSystemTimeUs += systemTimeUs;
12091
12092 StringBuilder sb = null;
12093 if (DEBUG_ENERGY_CPU) {
12094 sb = new StringBuilder();
12095 sb.append(" got time for uid=").append(u.mUid).append(": u=");
12096 TimeUtils.formatDuration(userTimeUs / 1000, sb);
12097 sb.append(" s=");
12098 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
12099 sb.append("\n");
12100 }
12101
12102 if (numWakelocks > 0) {
12103 // We have wakelocks being held, so only give a portion of the
12104 // time to the process. The rest will be distributed among wakelock
12105 // holders.
12106 userTimeUs = (userTimeUs * WAKE_LOCK_WEIGHT) / 100;
12107 systemTimeUs = (systemTimeUs * WAKE_LOCK_WEIGHT) / 100;
12108 }
12109
12110 if (sb != null) {
12111 sb.append(" adding to uid=").append(u.mUid).append(": u=");
12112 TimeUtils.formatDuration(userTimeUs / 1000, sb);
12113 sb.append(" s=");
12114 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
12115 Slog.d(TAG, sb.toString());
12116 }
12117
Sudheer Shankac57729a2018-02-09 15:44:42 -080012118 u.mUserCpuTime.addCountLocked(userTimeUs, onBattery);
12119 u.mSystemCpuTime.addCountLocked(systemTimeUs, onBattery);
Sudheer Shanka38383232017-07-25 09:55:03 -070012120 if (updatedUids != null) {
12121 updatedUids.put(u.getUid(), userTimeUs + systemTimeUs);
12122 }
12123 });
12124
12125 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12126 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12127 Slog.d(TAG, "Reading cpu stats took " + elapsedTimeMs + "ms");
12128 }
12129
12130 if (numWakelocks > 0) {
12131 // Distribute a portion of the total cpu time to wakelock holders.
12132 mTempTotalCpuUserTimeUs = (mTempTotalCpuUserTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
12133 mTempTotalCpuSystemTimeUs =
12134 (mTempTotalCpuSystemTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
12135
12136 for (int i = 0; i < numWakelocks; ++i) {
12137 final StopwatchTimer timer = partialTimers.get(i);
12138 final int userTimeUs = (int) (mTempTotalCpuUserTimeUs / (numWakelocks - i));
12139 final int systemTimeUs = (int) (mTempTotalCpuSystemTimeUs / (numWakelocks - i));
12140
12141 if (DEBUG_ENERGY_CPU) {
12142 final StringBuilder sb = new StringBuilder();
12143 sb.append(" Distributing wakelock uid=").append(timer.mUid.mUid)
12144 .append(": u=");
12145 TimeUtils.formatDuration(userTimeUs / 1000, sb);
12146 sb.append(" s=");
12147 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
12148 Slog.d(TAG, sb.toString());
12149 }
12150
Sudheer Shankac57729a2018-02-09 15:44:42 -080012151 timer.mUid.mUserCpuTime.addCountLocked(userTimeUs, onBattery);
12152 timer.mUid.mSystemCpuTime.addCountLocked(systemTimeUs, onBattery);
Sudheer Shanka38383232017-07-25 09:55:03 -070012153 if (updatedUids != null) {
12154 final int uid = timer.mUid.getUid();
12155 updatedUids.put(uid, updatedUids.get(uid, 0) + userTimeUs + systemTimeUs);
12156 }
12157
12158 final Uid.Proc proc = timer.mUid.getProcessStatsLocked("*wakelock*");
Sudheer Shankac57729a2018-02-09 15:44:42 -080012159 proc.addCpuTimeLocked(userTimeUs / 1000, systemTimeUs / 1000, onBattery);
Sudheer Shanka38383232017-07-25 09:55:03 -070012160
12161 mTempTotalCpuUserTimeUs -= userTimeUs;
12162 mTempTotalCpuSystemTimeUs -= systemTimeUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070012163 }
12164 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070012165 }
12166
Sudheer Shanka38383232017-07-25 09:55:03 -070012167 /**
12168 * Take a snapshot of the cpu times spent by each uid in each freq and update the
12169 * corresponding counters.
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012170 *
12171 * @param partialTimers The wakelock holders among which the cpu freq times will be distributed.
Sudheer Shanka38383232017-07-25 09:55:03 -070012172 */
12173 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012174 public void readKernelUidCpuFreqTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers,
12175 boolean onBattery, boolean onBatteryScreenOff) {
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012176 final boolean perClusterTimesAvailable =
12177 mKernelUidCpuFreqTimeReader.perClusterTimesAvailable();
12178 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
12179 final int numClusters = mPowerProfile.getNumCpuClusters();
12180 mWakeLockAllocationsUs = null;
Sudheer Shankaac5b88f2017-12-11 15:36:35 -080012181 final long startTimeMs = mClocks.uptimeMillis();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012182 mKernelUidCpuFreqTimeReader.readDelta((uid, cpuFreqTimeMs) -> {
12183 uid = mapUid(uid);
12184 if (Process.isIsolated(uid)) {
12185 mKernelUidCpuFreqTimeReader.removeUid(uid);
12186 Slog.d(TAG, "Got freq readings for an isolated uid with no mapping: " + uid);
12187 return;
Sudheer Shanka38383232017-07-25 09:55:03 -070012188 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012189 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12190 Slog.d(TAG, "Got freq readings for an invalid user's uid " + uid);
12191 mKernelUidCpuFreqTimeReader.removeUid(uid);
12192 return;
12193 }
12194 final Uid u = getUidStatsLocked(uid);
12195 if (u.mCpuFreqTimeMs == null || u.mCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
12196 u.mCpuFreqTimeMs = new LongSamplingCounterArray(mOnBatteryTimeBase);
12197 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080012198 u.mCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012199 if (u.mScreenOffCpuFreqTimeMs == null ||
12200 u.mScreenOffCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
12201 u.mScreenOffCpuFreqTimeMs = new LongSamplingCounterArray(
12202 mOnBatteryScreenOffTimeBase);
12203 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080012204 u.mScreenOffCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs, onBatteryScreenOff);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012205
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012206 if (perClusterTimesAvailable) {
12207 if (u.mCpuClusterSpeedTimesUs == null ||
12208 u.mCpuClusterSpeedTimesUs.length != numClusters) {
12209 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070012210 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012211 if (numWakelocks > 0 && mWakeLockAllocationsUs == null) {
12212 mWakeLockAllocationsUs = new long[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070012213 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012214
12215 int freqIndex = 0;
12216 for (int cluster = 0; cluster < numClusters; ++cluster) {
12217 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
12218 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
12219 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
12220 u.mCpuClusterSpeedTimesUs[cluster]
12221 = new LongSamplingCounter[speedsInCluster];
12222 }
12223 if (numWakelocks > 0 && mWakeLockAllocationsUs[cluster] == null) {
12224 mWakeLockAllocationsUs[cluster] = new long[speedsInCluster];
12225 }
12226 final LongSamplingCounter[] cpuTimesUs = u.mCpuClusterSpeedTimesUs[cluster];
12227 for (int speed = 0; speed < speedsInCluster; ++speed) {
12228 if (cpuTimesUs[speed] == null) {
12229 cpuTimesUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
12230 }
12231 final long appAllocationUs;
12232 if (mWakeLockAllocationsUs != null) {
12233 appAllocationUs =
12234 (cpuFreqTimeMs[freqIndex] * 1000 * WAKE_LOCK_WEIGHT) / 100;
12235 mWakeLockAllocationsUs[cluster][speed] +=
12236 (cpuFreqTimeMs[freqIndex] * 1000 - appAllocationUs);
12237 } else {
12238 appAllocationUs = cpuFreqTimeMs[freqIndex] * 1000;
12239 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080012240 cpuTimesUs[speed].addCountLocked(appAllocationUs, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012241 freqIndex++;
12242 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012243 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012244 }
12245 });
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012246
Sudheer Shankaac5b88f2017-12-11 15:36:35 -080012247 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12248 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12249 Slog.d(TAG, "Reading cpu freq times took " + elapsedTimeMs + "ms");
12250 }
12251
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012252 if (mWakeLockAllocationsUs != null) {
12253 for (int i = 0; i < numWakelocks; ++i) {
12254 final Uid u = partialTimers.get(i).mUid;
12255 if (u.mCpuClusterSpeedTimesUs == null ||
12256 u.mCpuClusterSpeedTimesUs.length != numClusters) {
12257 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
12258 }
12259
12260 for (int cluster = 0; cluster < numClusters; ++cluster) {
12261 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
12262 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
12263 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
12264 u.mCpuClusterSpeedTimesUs[cluster]
12265 = new LongSamplingCounter[speedsInCluster];
12266 }
12267 final LongSamplingCounter[] cpuTimeUs = u.mCpuClusterSpeedTimesUs[cluster];
12268 for (int speed = 0; speed < speedsInCluster; ++speed) {
12269 if (cpuTimeUs[speed] == null) {
12270 cpuTimeUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
12271 }
12272 final long allocationUs =
12273 mWakeLockAllocationsUs[cluster][speed] / (numWakelocks - i);
Sudheer Shankac57729a2018-02-09 15:44:42 -080012274 cpuTimeUs[speed].addCountLocked(allocationUs, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012275 mWakeLockAllocationsUs[cluster][speed] -= allocationUs;
12276 }
12277 }
12278 }
12279 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012280 }
12281
Mike Ma3d422c32017-10-25 11:08:57 -070012282 /**
12283 * Take a snapshot of the cpu active times spent by each uid and update the corresponding
12284 * counters.
12285 */
12286 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012287 public void readKernelUidCpuActiveTimesLocked(boolean onBattery) {
Mike Ma3d422c32017-10-25 11:08:57 -070012288 final long startTimeMs = mClocks.uptimeMillis();
Mike Ma2ab01442018-02-13 14:22:47 -080012289 mKernelUidCpuActiveTimeReader.readDelta((uid, cpuActiveTimesMs) -> {
Mike Ma3d422c32017-10-25 11:08:57 -070012290 uid = mapUid(uid);
12291 if (Process.isIsolated(uid)) {
12292 mKernelUidCpuActiveTimeReader.removeUid(uid);
12293 Slog.w(TAG, "Got active times for an isolated uid with no mapping: " + uid);
12294 return;
12295 }
12296 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12297 Slog.w(TAG, "Got active times for an invalid user's uid " + uid);
12298 mKernelUidCpuActiveTimeReader.removeUid(uid);
12299 return;
12300 }
12301 final Uid u = getUidStatsLocked(uid);
Mike Ma2ab01442018-02-13 14:22:47 -080012302 u.mCpuActiveTimeMs.addCountLocked(cpuActiveTimesMs, onBattery);
Mike Ma3d422c32017-10-25 11:08:57 -070012303 });
12304
12305 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12306 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12307 Slog.d(TAG, "Reading cpu active times took " + elapsedTimeMs + "ms");
12308 }
12309 }
12310
12311 /**
12312 * Take a snapshot of the cpu cluster times spent by each uid and update the corresponding
12313 * counters.
12314 */
12315 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012316 public void readKernelUidCpuClusterTimesLocked(boolean onBattery) {
Mike Ma3d422c32017-10-25 11:08:57 -070012317 final long startTimeMs = mClocks.uptimeMillis();
Mike Ma2ab01442018-02-13 14:22:47 -080012318 mKernelUidCpuClusterTimeReader.readDelta((uid, cpuClusterTimesMs) -> {
Mike Ma3d422c32017-10-25 11:08:57 -070012319 uid = mapUid(uid);
12320 if (Process.isIsolated(uid)) {
12321 mKernelUidCpuClusterTimeReader.removeUid(uid);
12322 Slog.w(TAG, "Got cluster times for an isolated uid with no mapping: " + uid);
12323 return;
12324 }
12325 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12326 Slog.w(TAG, "Got cluster times for an invalid user's uid " + uid);
12327 mKernelUidCpuClusterTimeReader.removeUid(uid);
12328 return;
12329 }
12330 final Uid u = getUidStatsLocked(uid);
Mike Ma2ab01442018-02-13 14:22:47 -080012331 u.mCpuClusterTimesMs.addCountLocked(cpuClusterTimesMs, onBattery);
Mike Ma3d422c32017-10-25 11:08:57 -070012332 });
12333
12334 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12335 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12336 Slog.d(TAG, "Reading cpu cluster times took " + elapsedTimeMs + "ms");
12337 }
12338 }
12339
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012340 boolean setChargingLocked(boolean charging) {
12341 if (mCharging != charging) {
12342 mCharging = charging;
12343 if (charging) {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012344 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012345 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012346 mHistoryCur.states2 &= ~HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012347 }
12348 mHandler.sendEmptyMessage(MSG_REPORT_CHARGING);
12349 return true;
12350 }
12351 return false;
12352 }
12353
Andreas Gampe3f24e692018-02-05 13:24:28 -080012354 @GuardedBy("this")
Mike Mac2f518a2017-09-19 16:06:03 -070012355 protected void setOnBatteryLocked(final long mSecRealtime, final long mSecUptime,
12356 final boolean onBattery, final int oldStatus, final int level, final int chargeUAh) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012357 boolean doWrite = false;
12358 Message m = mHandler.obtainMessage(MSG_REPORT_POWER_CHANGE);
12359 m.arg1 = onBattery ? 1 : 0;
12360 mHandler.sendMessage(m);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012361
Dianne Hackborn40c87252014-03-19 16:55:40 -070012362 final long uptime = mSecUptime * 1000;
12363 final long realtime = mSecRealtime * 1000;
Mike Mac2f518a2017-09-19 16:06:03 -070012364 final int screenState = mScreenState;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012365 if (onBattery) {
12366 // We will reset our status if we are unplugging after the
12367 // battery was last full, or the level is at 100, or
12368 // we have gone through a significant charge (from a very low
12369 // level to a now very high level).
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080012370 boolean reset = false;
Dianne Hackborn9a755432014-05-15 17:05:22 -070012371 if (!mNoAutoReset && (oldStatus == BatteryManager.BATTERY_STATUS_FULL
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012372 || level >= 90
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070012373 || (mDischargeCurrentLevel < 20 && level >= 80)
12374 || (getHighDischargeAmountSinceCharge() >= 200
12375 && mHistoryBuffer.dataSize() >= MAX_HISTORY_BUFFER))) {
Dianne Hackborn73d6a822014-09-29 10:52:47 -070012376 Slog.i(TAG, "Resetting battery stats: level=" + level + " status=" + oldStatus
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070012377 + " dischargeLevel=" + mDischargeCurrentLevel
Dianne Hackborn73d6a822014-09-29 10:52:47 -070012378 + " lowAmount=" + getLowDischargeAmountSinceCharge()
12379 + " highAmount=" + getHighDischargeAmountSinceCharge());
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012380 // Before we write, collect a snapshot of the final aggregated
12381 // stats to be reported in the next checkin. Only do this if we have
12382 // a sufficient amount of data to make it interesting.
12383 if (getLowDischargeAmountSinceCharge() >= 20) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080012384 final long startTime = SystemClock.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012385 final Parcel parcel = Parcel.obtain();
12386 writeSummaryToParcel(parcel, true);
Dianne Hackborne17b4452018-01-10 13:15:40 -080012387 final long initialTime = SystemClock.uptimeMillis() - startTime;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012388 BackgroundThread.getHandler().post(new Runnable() {
12389 @Override public void run() {
12390 synchronized (mCheckinFile) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080012391 final long startTime2 = SystemClock.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012392 FileOutputStream stream = null;
12393 try {
12394 stream = mCheckinFile.startWrite();
12395 stream.write(parcel.marshall());
12396 stream.flush();
12397 FileUtils.sync(stream);
12398 stream.close();
12399 mCheckinFile.finishWrite(stream);
Dianne Hackborne17b4452018-01-10 13:15:40 -080012400 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
12401 "batterystats-checkin",
12402 initialTime + SystemClock.uptimeMillis() - startTime2);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012403 } catch (IOException e) {
12404 Slog.w("BatteryStats",
12405 "Error writing checkin battery statistics", e);
12406 mCheckinFile.failWrite(stream);
12407 } finally {
12408 parcel.recycle();
12409 }
12410 }
12411 }
12412 });
12413 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012414 doWrite = true;
12415 resetAllStatsLocked();
Ying Wai (Daniel) Fan442ab762017-01-31 22:00:10 -080012416 if (chargeUAh > 0 && level > 0) {
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012417 // Only use the reported coulomb charge value if it is supported and reported.
Ying Wai (Daniel) Fan9238b612017-01-18 15:50:19 -080012418 mEstimatedBatteryCapacity = (int) ((chargeUAh / 1000) / (level / 100.0));
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012419 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012420 mDischargeStartLevel = level;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080012421 reset = true;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012422 mDischargeStepTracker.init();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012423 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012424 if (mCharging) {
12425 setChargingLocked(false);
12426 }
12427 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080012428 mOnBattery = mOnBatteryInternal = true;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012429 mLastDischargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070012430 mMinDischargeStepLevel = level;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012431 mDischargeStepTracker.clearTime();
12432 mDailyDischargeStepTracker.clearTime();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012433 mInitStepMode = mCurStepMode;
12434 mModStepMode = 0;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012435 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012436 mHistoryCur.batteryLevel = (byte)level;
12437 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
12438 if (DEBUG_HISTORY) Slog.v(TAG, "Battery unplugged to: "
12439 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012440 if (reset) {
12441 mRecordingHistory = true;
12442 startRecordingHistory(mSecRealtime, mSecUptime, reset);
12443 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070012444 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012445 mDischargeCurrentLevel = mDischargeUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070012446 if (isScreenOn(screenState)) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012447 mDischargeScreenOnUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070012448 mDischargeScreenDozeUnplugLevel = 0;
12449 mDischargeScreenOffUnplugLevel = 0;
12450 } else if (isScreenDoze(screenState)) {
12451 mDischargeScreenOnUnplugLevel = 0;
12452 mDischargeScreenDozeUnplugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012453 mDischargeScreenOffUnplugLevel = 0;
12454 } else {
12455 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012456 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012457 mDischargeScreenOffUnplugLevel = level;
12458 }
12459 mDischargeAmountScreenOn = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012460 mDischargeAmountScreenDoze = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012461 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012462 updateTimeBasesLocked(true, screenState, uptime, realtime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012463 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012464 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080012465 mOnBattery = mOnBatteryInternal = false;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012466 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012467 mHistoryCur.batteryLevel = (byte)level;
12468 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
12469 if (DEBUG_HISTORY) Slog.v(TAG, "Battery plugged to: "
12470 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -070012471 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012472 mDischargeCurrentLevel = mDischargePlugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012473 if (level < mDischargeUnplugLevel) {
12474 mLowDischargeAmountSinceCharge += mDischargeUnplugLevel-level-1;
12475 mHighDischargeAmountSinceCharge += mDischargeUnplugLevel-level;
12476 }
Mike Mac2f518a2017-09-19 16:06:03 -070012477 updateDischargeScreenLevelsLocked(screenState, screenState);
12478 updateTimeBasesLocked(false, screenState, uptime, realtime);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012479 mChargeStepTracker.init();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012480 mLastChargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070012481 mMaxChargeStepLevel = level;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012482 mInitStepMode = mCurStepMode;
12483 mModStepMode = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012484 }
12485 if (doWrite || (mLastWriteTime + (60 * 1000)) < mSecRealtime) {
12486 if (mFile != null) {
12487 writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012488 }
12489 }
12490 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012491
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012492 private void startRecordingHistory(final long elapsedRealtimeMs, final long uptimeMs,
12493 boolean reset) {
12494 mRecordingHistory = true;
12495 mHistoryCur.currentTime = System.currentTimeMillis();
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012496 addHistoryBufferLocked(elapsedRealtimeMs,
Dianne Hackborn37de0982014-05-09 09:32:18 -070012497 reset ? HistoryItem.CMD_RESET : HistoryItem.CMD_CURRENT_TIME,
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012498 mHistoryCur);
12499 mHistoryCur.currentTime = 0;
12500 if (reset) {
12501 initActiveHistoryEventsLocked(elapsedRealtimeMs, uptimeMs);
12502 }
12503 }
12504
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012505 private void recordCurrentTimeChangeLocked(final long currentTime, final long elapsedRealtimeMs,
12506 final long uptimeMs) {
12507 if (mRecordingHistory) {
12508 mHistoryCur.currentTime = currentTime;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012509 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_CURRENT_TIME, mHistoryCur);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012510 mHistoryCur.currentTime = 0;
12511 }
12512 }
12513
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080012514 private void recordShutdownLocked(final long elapsedRealtimeMs, final long uptimeMs) {
12515 if (mRecordingHistory) {
12516 mHistoryCur.currentTime = System.currentTimeMillis();
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012517 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_SHUTDOWN, mHistoryCur);
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080012518 mHistoryCur.currentTime = 0;
12519 }
12520 }
12521
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012522 private void scheduleSyncExternalStatsLocked(String reason, int updateFlags) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012523 if (mExternalSync != null) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012524 mExternalSync.scheduleSync(reason, updateFlags);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070012525 }
12526 }
12527
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012528 // This should probably be exposed in the API, though it's not critical
Bookatz1a1b0462018-01-12 11:47:03 -080012529 public static final int BATTERY_PLUGGED_NONE = OsProtoEnums.BATTERY_PLUGGED_NONE; // = 0
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012530
Andreas Gampe3f24e692018-02-05 13:24:28 -080012531 @GuardedBy("this")
Bookatz8c6571b2017-10-24 15:04:41 -070012532 public void setBatteryStateLocked(final int status, final int health, final int plugType,
12533 final int level, /* not final */ int temp, final int volt, final int chargeUAh,
12534 final int chargeFullUAh) {
Adam Lesinski29ddfe52017-03-29 19:29:00 -070012535 // Temperature is encoded without the signed bit, so clamp any negative temperatures to 0.
12536 temp = Math.max(0, temp);
12537
Bookatz8c6571b2017-10-24 15:04:41 -070012538 reportChangesToStatsLog(mHaveBatteryLevel ? mHistoryCur : null,
Tej Singh40298312018-02-16 00:15:09 -080012539 status, plugType, level);
Bookatz8c6571b2017-10-24 15:04:41 -070012540
Sudheer Shankac57729a2018-02-09 15:44:42 -080012541 final boolean onBattery = isOnBattery(plugType, status);
Joe Onoratoabded112016-02-08 16:49:39 -080012542 final long uptime = mClocks.uptimeMillis();
12543 final long elapsedRealtime = mClocks.elapsedRealtime();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012544 if (!mHaveBatteryLevel) {
12545 mHaveBatteryLevel = true;
12546 // We start out assuming that the device is plugged in (not
12547 // on battery). If our first report is now that we are indeed
12548 // plugged in, then twiddle our state to correctly reflect that
12549 // since we won't be going through the full setOnBattery().
12550 if (onBattery == mOnBattery) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012551 if (onBattery) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012552 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012553 } else {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012554 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012555 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012556 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012557 // Always start out assuming charging, that will be updated later.
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012558 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012559 mHistoryCur.batteryStatus = (byte)status;
12560 mHistoryCur.batteryLevel = (byte)level;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012561 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012562 mMaxChargeStepLevel = mMinDischargeStepLevel =
12563 mLastChargeStepLevel = mLastDischargeStepLevel = level;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012564 mLastChargingStateLevel = level;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012565 } else if (mCurrentBatteryLevel != level || mOnBattery != onBattery) {
12566 recordDailyStatsIfNeededLocked(level >= 100 && onBattery);
12567 }
12568 int oldStatus = mHistoryCur.batteryStatus;
12569 if (onBattery) {
12570 mDischargeCurrentLevel = level;
12571 if (!mRecordingHistory) {
12572 mRecordingHistory = true;
12573 startRecordingHistory(elapsedRealtime, uptime, true);
12574 }
Todd Poynor1acf06a2017-12-07 19:19:35 -080012575 } else if (level < 96 &&
12576 status != BatteryManager.BATTERY_STATUS_UNKNOWN) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012577 if (!mRecordingHistory) {
12578 mRecordingHistory = true;
12579 startRecordingHistory(elapsedRealtime, uptime, true);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012580 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070012581 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012582 mCurrentBatteryLevel = level;
12583 if (mDischargePlugLevel < 0) {
12584 mDischargePlugLevel = level;
Marco Nelissend8593312009-04-30 14:45:06 -070012585 }
Adam Lesinski926969b2016-04-28 17:31:12 -070012586
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012587 if (onBattery != mOnBattery) {
12588 mHistoryCur.batteryLevel = (byte)level;
12589 mHistoryCur.batteryStatus = (byte)status;
12590 mHistoryCur.batteryHealth = (byte)health;
12591 mHistoryCur.batteryPlugType = (byte)plugType;
12592 mHistoryCur.batteryTemperature = (short)temp;
12593 mHistoryCur.batteryVoltage = (char)volt;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012594 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
12595 // Only record discharges
12596 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
12597 mDischargeCounter.addCountLocked(chargeDiff);
12598 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070012599 if (isScreenDoze(mScreenState)) {
12600 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
12601 }
Mike Ma15313c92017-11-15 17:58:21 -080012602 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
12603 mDischargeLightDozeCounter.addCountLocked(chargeDiff);
12604 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
12605 mDischargeDeepDozeCounter.addCountLocked(chargeDiff);
12606 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012607 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012608 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012609 setOnBatteryLocked(elapsedRealtime, uptime, onBattery, oldStatus, level, chargeUAh);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012610 } else {
12611 boolean changed = false;
12612 if (mHistoryCur.batteryLevel != level) {
12613 mHistoryCur.batteryLevel = (byte)level;
12614 changed = true;
Marco Nelissend8593312009-04-30 14:45:06 -070012615
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012616 // TODO(adamlesinski): Schedule the creation of a HistoryStepDetails record
12617 // which will pull external stats.
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012618 scheduleSyncExternalStatsLocked("battery-level", ExternalStatsSync.UPDATE_ALL);
Evan Millarc64edde2009-04-18 12:26:32 -070012619 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012620 if (mHistoryCur.batteryStatus != status) {
12621 mHistoryCur.batteryStatus = (byte)status;
12622 changed = true;
12623 }
12624 if (mHistoryCur.batteryHealth != health) {
12625 mHistoryCur.batteryHealth = (byte)health;
12626 changed = true;
12627 }
12628 if (mHistoryCur.batteryPlugType != plugType) {
12629 mHistoryCur.batteryPlugType = (byte)plugType;
12630 changed = true;
12631 }
12632 if (temp >= (mHistoryCur.batteryTemperature+10)
12633 || temp <= (mHistoryCur.batteryTemperature-10)) {
12634 mHistoryCur.batteryTemperature = (short)temp;
12635 changed = true;
12636 }
12637 if (volt > (mHistoryCur.batteryVoltage+20)
12638 || volt < (mHistoryCur.batteryVoltage-20)) {
12639 mHistoryCur.batteryVoltage = (char)volt;
12640 changed = true;
12641 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012642 if (chargeUAh >= (mHistoryCur.batteryChargeUAh+10)
12643 || chargeUAh <= (mHistoryCur.batteryChargeUAh-10)) {
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012644 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
12645 // Only record discharges
12646 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
12647 mDischargeCounter.addCountLocked(chargeDiff);
12648 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070012649 if (isScreenDoze(mScreenState)) {
12650 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
12651 }
Mike Ma15313c92017-11-15 17:58:21 -080012652 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
12653 mDischargeLightDozeCounter.addCountLocked(chargeDiff);
12654 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
12655 mDischargeDeepDozeCounter.addCountLocked(chargeDiff);
12656 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012657 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012658 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski926969b2016-04-28 17:31:12 -070012659 changed = true;
12660 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012661 long modeBits = (((long)mInitStepMode) << STEP_LEVEL_INITIAL_MODE_SHIFT)
12662 | (((long)mModStepMode) << STEP_LEVEL_MODIFIED_MODE_SHIFT)
12663 | (((long)(level&0xff)) << STEP_LEVEL_LEVEL_SHIFT);
12664 if (onBattery) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012665 changed |= setChargingLocked(false);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012666 if (mLastDischargeStepLevel != level && mMinDischargeStepLevel > level) {
12667 mDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
12668 modeBits, elapsedRealtime);
12669 mDailyDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
12670 modeBits, elapsedRealtime);
12671 mLastDischargeStepLevel = level;
12672 mMinDischargeStepLevel = level;
12673 mInitStepMode = mCurStepMode;
12674 mModStepMode = 0;
12675 }
12676 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012677 if (level >= 90) {
12678 // If the battery level is at least 90%, always consider the device to be
12679 // charging even if it happens to go down a level.
12680 changed |= setChargingLocked(true);
12681 mLastChargeStepLevel = level;
12682 } if (!mCharging) {
12683 if (mLastChargeStepLevel < level) {
12684 // We have not reporting that we are charging, but the level has now
12685 // gone up, so consider the state to be charging.
12686 changed |= setChargingLocked(true);
12687 mLastChargeStepLevel = level;
12688 }
12689 } else {
12690 if (mLastChargeStepLevel > level) {
12691 // We had reported that the device was charging, but here we are with
12692 // power connected and the level going down. Looks like the current
12693 // power supplied isn't enough, so consider the device to now be
12694 // discharging.
12695 changed |= setChargingLocked(false);
12696 mLastChargeStepLevel = level;
12697 }
12698 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012699 if (mLastChargeStepLevel != level && mMaxChargeStepLevel < level) {
12700 mChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
12701 modeBits, elapsedRealtime);
12702 mDailyChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
12703 modeBits, elapsedRealtime);
12704 mLastChargeStepLevel = level;
12705 mMaxChargeStepLevel = level;
12706 mInitStepMode = mCurStepMode;
12707 mModStepMode = 0;
Evan Millarc64edde2009-04-18 12:26:32 -070012708 }
12709 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012710 if (changed) {
12711 addHistoryRecordLocked(elapsedRealtime, uptime);
12712 }
Evan Millarc64edde2009-04-18 12:26:32 -070012713 }
Todd Poynor1acf06a2017-12-07 19:19:35 -080012714 if (!onBattery &&
12715 (status == BatteryManager.BATTERY_STATUS_FULL ||
12716 status == BatteryManager.BATTERY_STATUS_UNKNOWN)) {
12717 // We don't record history while we are plugged in and fully charged
12718 // (or when battery is not present). The next time we are
12719 // unplugged, history will be cleared.
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012720 mRecordingHistory = DEBUG;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080012721 }
Adam Lesinski041d9172016-12-12 12:03:56 -080012722
Jocelyn Dangc627d102017-04-14 13:15:14 -070012723 if (mMinLearnedBatteryCapacity == -1) {
12724 mMinLearnedBatteryCapacity = chargeFullUAh;
12725 } else {
12726 Math.min(mMinLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski041d9172016-12-12 12:03:56 -080012727 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070012728 mMaxLearnedBatteryCapacity = Math.max(mMaxLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski33dac552015-03-09 15:24:48 -070012729 }
12730
Sudheer Shankac57729a2018-02-09 15:44:42 -080012731 public static boolean isOnBattery(int plugType, int status) {
12732 return plugType == BATTERY_PLUGGED_NONE && status != BatteryManager.BATTERY_STATUS_UNKNOWN;
12733 }
12734
Bookatz8c6571b2017-10-24 15:04:41 -070012735 // Inform StatsLog of setBatteryState changes.
12736 // If this is the first reporting, pass in recentPast == null.
12737 private void reportChangesToStatsLog(HistoryItem recentPast,
Tej Singh40298312018-02-16 00:15:09 -080012738 final int status, final int plugType, final int level) {
Bookatz8c6571b2017-10-24 15:04:41 -070012739
12740 if (recentPast == null || recentPast.batteryStatus != status) {
12741 StatsLog.write(StatsLog.CHARGING_STATE_CHANGED, status);
12742 }
12743 if (recentPast == null || recentPast.batteryPlugType != plugType) {
12744 StatsLog.write(StatsLog.PLUGGED_STATE_CHANGED, plugType);
12745 }
12746 if (recentPast == null || recentPast.batteryLevel != level) {
12747 StatsLog.write(StatsLog.BATTERY_LEVEL_CHANGED, level);
12748 }
Bookatz8c6571b2017-10-24 15:04:41 -070012749 }
12750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012751 public long getAwakeTimeBattery() {
12752 return computeBatteryUptime(getBatteryUptimeLocked(), STATS_CURRENT);
12753 }
12754
12755 public long getAwakeTimePlugged() {
Joe Onoratoabded112016-02-08 16:49:39 -080012756 return (mClocks.uptimeMillis() * 1000) - getAwakeTimeBattery();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012757 }
12758
12759 @Override
12760 public long computeUptime(long curTime, int which) {
12761 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012762 case STATS_SINCE_CHARGED: return mUptime + (curTime-mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012763 case STATS_CURRENT: return (curTime-mUptimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070012764 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getUptimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012765 }
12766 return 0;
12767 }
12768
12769 @Override
12770 public long computeRealtime(long curTime, int which) {
12771 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012772 case STATS_SINCE_CHARGED: return mRealtime + (curTime-mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012773 case STATS_CURRENT: return (curTime-mRealtimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070012774 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getRealtimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012775 }
12776 return 0;
12777 }
12778
12779 @Override
12780 public long computeBatteryUptime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012781 return mOnBatteryTimeBase.computeUptime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012782 }
12783
12784 @Override
12785 public long computeBatteryRealtime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012786 return mOnBatteryTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012787 }
12788
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012789 @Override
12790 public long computeBatteryScreenOffUptime(long curTime, int which) {
12791 return mOnBatteryScreenOffTimeBase.computeUptime(curTime, which);
12792 }
12793
12794 @Override
12795 public long computeBatteryScreenOffRealtime(long curTime, int which) {
12796 return mOnBatteryScreenOffTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012797 }
12798
Dianne Hackborn260c5022014-04-29 11:23:16 -070012799 private long computeTimePerLevel(long[] steps, int numSteps) {
12800 // For now we'll do a simple average across all steps.
12801 if (numSteps <= 0) {
12802 return -1;
12803 }
12804 long total = 0;
12805 for (int i=0; i<numSteps; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012806 total += steps[i] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012807 }
12808 return total / numSteps;
12809 /*
12810 long[] buckets = new long[numSteps];
12811 int numBuckets = 0;
12812 int numToAverage = 4;
12813 int i = 0;
12814 while (i < numSteps) {
12815 long totalTime = 0;
12816 int num = 0;
12817 for (int j=0; j<numToAverage && (i+j)<numSteps; j++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012818 totalTime += steps[i+j] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012819 num++;
12820 }
12821 buckets[numBuckets] = totalTime / num;
12822 numBuckets++;
12823 numToAverage *= 2;
12824 i += num;
12825 }
12826 if (numBuckets < 1) {
12827 return -1;
12828 }
12829 long averageTime = buckets[numBuckets-1];
12830 for (i=numBuckets-2; i>=0; i--) {
12831 averageTime = (averageTime + buckets[i]) / 2;
12832 }
12833 return averageTime;
12834 */
12835 }
12836
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012837 @Override
12838 public long computeBatteryTimeRemaining(long curTime) {
12839 if (!mOnBattery) {
12840 return -1;
12841 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070012842 /* Simple implementation just looks at the average discharge per level across the
12843 entire sample period.
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012844 int discharge = (getLowDischargeAmountSinceCharge()+getHighDischargeAmountSinceCharge())/2;
12845 if (discharge < 2) {
12846 return -1;
12847 }
12848 long duration = computeBatteryRealtime(curTime, STATS_SINCE_CHARGED);
12849 if (duration < 1000*1000) {
12850 return -1;
12851 }
12852 long usPerLevel = duration/discharge;
12853 return usPerLevel * mCurrentBatteryLevel;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012854 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012855 if (mDischargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012856 return -1;
12857 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012858 long msPerLevel = mDischargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012859 if (msPerLevel <= 0) {
12860 return -1;
12861 }
12862 return (msPerLevel * mCurrentBatteryLevel) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012863 }
12864
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012865 @Override
12866 public LevelStepTracker getDischargeLevelStepTracker() {
12867 return mDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012868 }
12869
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012870 @Override
12871 public LevelStepTracker getDailyDischargeLevelStepTracker() {
12872 return mDailyDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012873 }
12874
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012875 @Override
12876 public long computeChargeTimeRemaining(long curTime) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012877 if (mOnBattery) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012878 // Not yet working.
12879 return -1;
12880 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070012881 /* Broken
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012882 int curLevel = mCurrentBatteryLevel;
12883 int plugLevel = mDischargePlugLevel;
12884 if (plugLevel < 0 || curLevel < (plugLevel+1)) {
12885 return -1;
12886 }
12887 long duration = computeBatteryRealtime(curTime, STATS_SINCE_UNPLUGGED);
12888 if (duration < 1000*1000) {
12889 return -1;
12890 }
12891 long usPerLevel = duration/(curLevel-plugLevel);
12892 return usPerLevel * (100-curLevel);
Dianne Hackborn260c5022014-04-29 11:23:16 -070012893 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012894 if (mChargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012895 return -1;
12896 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012897 long msPerLevel = mChargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012898 if (msPerLevel <= 0) {
12899 return -1;
12900 }
12901 return (msPerLevel * (100-mCurrentBatteryLevel)) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012902 }
12903
Siddharth Raya1fd0572017-11-13 14:20:47 -080012904 /*@hide */
12905 public CellularBatteryStats getCellularBatteryStats() {
12906 CellularBatteryStats s = new CellularBatteryStats();
12907 final int which = STATS_SINCE_CHARGED;
12908 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12909 final ControllerActivityCounter counter = getModemControllerActivity();
Siddharth Rayed754702018-02-15 12:44:37 -080012910 final long sleepTimeMs = counter.getSleepTimeCounter().getCountLocked(which);
Siddharth Raya1fd0572017-11-13 14:20:47 -080012911 final long idleTimeMs = counter.getIdleTimeCounter().getCountLocked(which);
12912 final long rxTimeMs = counter.getRxTimeCounter().getCountLocked(which);
12913 final long energyConsumedMaMs = counter.getPowerCounter().getCountLocked(which);
12914 long[] timeInRatMs = new long[BatteryStats.NUM_DATA_CONNECTION_TYPES];
12915 for (int i = 0; i < timeInRatMs.length; i++) {
12916 timeInRatMs[i] = getPhoneDataConnectionTime(i, rawRealTime, which) / 1000;
12917 }
12918 long[] timeInRxSignalStrengthLevelMs = new long[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
12919 for (int i = 0; i < timeInRxSignalStrengthLevelMs.length; i++) {
12920 timeInRxSignalStrengthLevelMs[i]
12921 = getPhoneSignalStrengthTime(i, rawRealTime, which) / 1000;
12922 }
12923 long[] txTimeMs = new long[Math.min(ModemActivityInfo.TX_POWER_LEVELS,
12924 counter.getTxTimeCounters().length)];
12925 long totalTxTimeMs = 0;
12926 for (int i = 0; i < txTimeMs.length; i++) {
12927 txTimeMs[i] = counter.getTxTimeCounters()[i].getCountLocked(which);
12928 totalTxTimeMs += txTimeMs[i];
12929 }
Siddharth Raya1fd0572017-11-13 14:20:47 -080012930 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
12931 s.setKernelActiveTimeMs(getMobileRadioActiveTime(rawRealTime, which) / 1000);
12932 s.setNumPacketsTx(getNetworkActivityPackets(NETWORK_MOBILE_TX_DATA, which));
12933 s.setNumBytesTx(getNetworkActivityBytes(NETWORK_MOBILE_TX_DATA, which));
12934 s.setNumPacketsRx(getNetworkActivityPackets(NETWORK_MOBILE_RX_DATA, which));
12935 s.setNumBytesRx(getNetworkActivityBytes(NETWORK_MOBILE_RX_DATA, which));
12936 s.setSleepTimeMs(sleepTimeMs);
12937 s.setIdleTimeMs(idleTimeMs);
12938 s.setRxTimeMs(rxTimeMs);
12939 s.setEnergyConsumedMaMs(energyConsumedMaMs);
12940 s.setTimeInRatMs(timeInRatMs);
12941 s.setTimeInRxSignalStrengthLevelMs(timeInRxSignalStrengthLevelMs);
12942 s.setTxTimeMs(txTimeMs);
12943 return s;
12944 }
12945
Siddharth Rayb50a6842017-12-14 15:15:28 -080012946 /*@hide */
12947 public WifiBatteryStats getWifiBatteryStats() {
12948 WifiBatteryStats s = new WifiBatteryStats();
12949 final int which = STATS_SINCE_CHARGED;
12950 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12951 final ControllerActivityCounter counter = getWifiControllerActivity();
12952 final long idleTimeMs = counter.getIdleTimeCounter().getCountLocked(which);
12953 final long scanTimeMs = counter.getScanTimeCounter().getCountLocked(which);
12954 final long rxTimeMs = counter.getRxTimeCounter().getCountLocked(which);
12955 final long txTimeMs = counter.getTxTimeCounters()[0].getCountLocked(which);
12956 final long totalControllerActivityTimeMs
12957 = computeBatteryRealtime(SystemClock.elapsedRealtime() * 1000, which) / 1000;
12958 final long sleepTimeMs
12959 = totalControllerActivityTimeMs - (idleTimeMs + rxTimeMs + txTimeMs);
12960 final long energyConsumedMaMs = counter.getPowerCounter().getCountLocked(which);
12961 long numAppScanRequest = 0;
12962 for (int i = 0; i < mUidStats.size(); i++) {
12963 numAppScanRequest += mUidStats.valueAt(i).mWifiScanTimer.getCountLocked(which);
12964 }
12965 long[] timeInStateMs = new long[NUM_WIFI_STATES];
12966 for (int i=0; i<NUM_WIFI_STATES; i++) {
12967 timeInStateMs[i] = getWifiStateTime(i, rawRealTime, which) / 1000;
12968 }
12969 long[] timeInSupplStateMs = new long[NUM_WIFI_SUPPL_STATES];
12970 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
12971 timeInSupplStateMs[i] = getWifiSupplStateTime(i, rawRealTime, which) / 1000;
12972 }
12973 long[] timeSignalStrengthTimeMs = new long[NUM_WIFI_SIGNAL_STRENGTH_BINS];
12974 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
12975 timeSignalStrengthTimeMs[i] = getWifiSignalStrengthTime(i, rawRealTime, which) / 1000;
12976 }
12977 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
12978 s.setKernelActiveTimeMs(getWifiActiveTime(rawRealTime, which) / 1000);
12979 s.setNumPacketsTx(getNetworkActivityPackets(NETWORK_WIFI_TX_DATA, which));
12980 s.setNumBytesTx(getNetworkActivityBytes(NETWORK_WIFI_TX_DATA, which));
12981 s.setNumPacketsRx(getNetworkActivityPackets(NETWORK_WIFI_RX_DATA, which));
12982 s.setNumBytesRx(getNetworkActivityBytes(NETWORK_WIFI_RX_DATA, which));
12983 s.setSleepTimeMs(sleepTimeMs);
12984 s.setIdleTimeMs(idleTimeMs);
12985 s.setRxTimeMs(rxTimeMs);
12986 s.setTxTimeMs(txTimeMs);
12987 s.setScanTimeMs(scanTimeMs);
12988 s.setEnergyConsumedMaMs(energyConsumedMaMs);
12989 s.setNumAppScanRequest(numAppScanRequest);
12990 s.setTimeInStateMs(timeInStateMs);
12991 s.setTimeInSupplicantStateMs(timeInSupplStateMs);
12992 s.setTimeInRxSignalStrengthLevelMs(timeSignalStrengthTimeMs);
12993 return s;
12994 }
12995
Siddharth Ray78ccaf52017-12-23 16:16:21 -080012996 /*@hide */
12997 public GpsBatteryStats getGpsBatteryStats() {
12998 GpsBatteryStats s = new GpsBatteryStats();
12999 final int which = STATS_SINCE_CHARGED;
13000 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
13001 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
13002 s.setEnergyConsumedMaMs(getGpsBatteryDrainMaMs());
13003 long[] time = new long[GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS];
13004 for (int i=0; i<time.length; i++) {
13005 time[i] = getGpsSignalQualityTime(i, rawRealTime, which) / 1000;
13006 }
13007 s.setTimeInGpsSignalQualityLevel(time);
13008 return s;
13009 }
13010
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013011 @Override
13012 public LevelStepTracker getChargeLevelStepTracker() {
13013 return mChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070013014 }
13015
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013016 @Override
13017 public LevelStepTracker getDailyChargeLevelStepTracker() {
13018 return mDailyChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070013019 }
13020
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013021 @Override
13022 public ArrayList<PackageChange> getDailyPackageChanges() {
13023 return mDailyPackageChanges;
13024 }
13025
Joe Onoratoe1acd632016-02-23 13:25:10 -080013026 protected long getBatteryUptimeLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080013027 return mOnBatteryTimeBase.getUptime(mClocks.uptimeMillis() * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013028 }
13029
13030 @Override
13031 public long getBatteryUptime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013032 return mOnBatteryTimeBase.getUptime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013033 }
13034
13035 @Override
13036 public long getBatteryRealtime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013037 return mOnBatteryTimeBase.getRealtime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013038 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -070013039
The Android Open Source Project10592532009-03-18 17:39:46 -070013040 @Override
Evan Millar633a1742009-04-02 16:36:33 -070013041 public int getDischargeStartLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070013042 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070013043 return getDischargeStartLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070013044 }
13045 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013046
Evan Millar633a1742009-04-02 16:36:33 -070013047 public int getDischargeStartLevelLocked() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013048 return mDischargeUnplugLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070013049 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013050
The Android Open Source Project10592532009-03-18 17:39:46 -070013051 @Override
Evan Millar633a1742009-04-02 16:36:33 -070013052 public int getDischargeCurrentLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070013053 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070013054 return getDischargeCurrentLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070013055 }
13056 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013057
Evan Millar633a1742009-04-02 16:36:33 -070013058 public int getDischargeCurrentLevelLocked() {
Dianne Hackborne4a59512010-12-07 11:08:07 -080013059 return mDischargeCurrentLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070013060 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013061
Amith Yamasanie43530a2009-08-21 13:11:37 -070013062 @Override
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013063 public int getLowDischargeAmountSinceCharge() {
13064 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080013065 int val = mLowDischargeAmountSinceCharge;
13066 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
13067 val += mDischargeUnplugLevel-mDischargeCurrentLevel-1;
13068 }
13069 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013070 }
13071 }
13072
13073 @Override
13074 public int getHighDischargeAmountSinceCharge() {
13075 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080013076 int val = mHighDischargeAmountSinceCharge;
13077 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
13078 val += mDischargeUnplugLevel-mDischargeCurrentLevel;
13079 }
13080 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013081 }
13082 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070013083
13084 @Override
13085 public int getDischargeAmount(int which) {
13086 int dischargeAmount = which == STATS_SINCE_CHARGED
13087 ? getHighDischargeAmountSinceCharge()
13088 : (getDischargeStartLevel() - getDischargeCurrentLevel());
13089 if (dischargeAmount < 0) {
13090 dischargeAmount = 0;
13091 }
13092 return dischargeAmount;
13093 }
13094
Mike Mac2f518a2017-09-19 16:06:03 -070013095 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013096 public int getDischargeAmountScreenOn() {
13097 synchronized(this) {
13098 int val = mDischargeAmountScreenOn;
Mike Mac2f518a2017-09-19 16:06:03 -070013099 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013100 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
13101 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
13102 }
13103 return val;
13104 }
13105 }
13106
Mike Mac2f518a2017-09-19 16:06:03 -070013107 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013108 public int getDischargeAmountScreenOnSinceCharge() {
13109 synchronized(this) {
13110 int val = mDischargeAmountScreenOnSinceCharge;
Mike Mac2f518a2017-09-19 16:06:03 -070013111 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013112 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
13113 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
13114 }
13115 return val;
13116 }
13117 }
13118
Mike Mac2f518a2017-09-19 16:06:03 -070013119 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013120 public int getDischargeAmountScreenOff() {
13121 synchronized(this) {
13122 int val = mDischargeAmountScreenOff;
Mike Mac2f518a2017-09-19 16:06:03 -070013123 if (mOnBattery && isScreenOff(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013124 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
13125 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
13126 }
Mike Mac2f518a2017-09-19 16:06:03 -070013127 // For backward compatibility, doze discharge is counted into screen off.
13128 return val + getDischargeAmountScreenDoze();
13129 }
13130 }
13131
13132 @Override
13133 public int getDischargeAmountScreenOffSinceCharge() {
13134 synchronized(this) {
13135 int val = mDischargeAmountScreenOffSinceCharge;
13136 if (mOnBattery && isScreenOff(mScreenState)
13137 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
13138 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
13139 }
13140 // For backward compatibility, doze discharge is counted into screen off.
13141 return val + getDischargeAmountScreenDozeSinceCharge();
13142 }
13143 }
13144
13145 @Override
13146 public int getDischargeAmountScreenDoze() {
13147 synchronized(this) {
13148 int val = mDischargeAmountScreenDoze;
13149 if (mOnBattery && isScreenDoze(mScreenState)
13150 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
13151 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
13152 }
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013153 return val;
13154 }
13155 }
13156
Mike Mac2f518a2017-09-19 16:06:03 -070013157 @Override
13158 public int getDischargeAmountScreenDozeSinceCharge() {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013159 synchronized(this) {
Mike Mac2f518a2017-09-19 16:06:03 -070013160 int val = mDischargeAmountScreenDozeSinceCharge;
13161 if (mOnBattery && isScreenDoze(mScreenState)
13162 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
13163 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013164 }
13165 return val;
13166 }
13167 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013168
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013169 /**
13170 * Retrieve the statistics object for a particular uid, creating if needed.
13171 */
13172 public Uid getUidStatsLocked(int uid) {
13173 Uid u = mUidStats.get(uid);
13174 if (u == null) {
Joe Onoratoabded112016-02-08 16:49:39 -080013175 u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013176 mUidStats.put(uid, u);
13177 }
13178 return u;
13179 }
13180
Sudheer Shankab2f83c12017-11-13 19:25:01 -080013181 /**
13182 * Retrieve the statistics object for a particular uid. Returns null if the object is not
13183 * available.
13184 */
13185 public Uid getAvailableUidStatsLocked(int uid) {
13186 Uid u = mUidStats.get(uid);
13187 return u;
13188 }
13189
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070013190 public void onCleanupUserLocked(int userId) {
13191 final int firstUidForUser = UserHandle.getUid(userId, 0);
13192 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
Mike Ma234d1822018-03-13 18:53:21 -070013193 mPendingRemovedUids.add(
13194 new UidToRemove(firstUidForUser, lastUidForUser, mClocks.elapsedRealtime()));
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070013195 }
13196
13197 public void onUserRemovedLocked(int userId) {
13198 final int firstUidForUser = UserHandle.getUid(userId, 0);
13199 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
13200 mUidStats.put(firstUidForUser, null);
13201 mUidStats.put(lastUidForUser, null);
13202 final int firstIndex = mUidStats.indexOfKey(firstUidForUser);
13203 final int lastIndex = mUidStats.indexOfKey(lastUidForUser);
13204 mUidStats.removeAtRange(firstIndex, lastIndex - firstIndex + 1);
13205 }
13206
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013207 /**
13208 * Remove the statistics object for a particular uid.
13209 */
13210 public void removeUidStatsLocked(int uid) {
13211 mUidStats.remove(uid);
Mike Ma234d1822018-03-13 18:53:21 -070013212 mPendingRemovedUids.add(new UidToRemove(uid, mClocks.elapsedRealtime()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013213 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -070013214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013215 /**
13216 * Retrieve the statistics object for a particular process, creating
13217 * if needed.
13218 */
13219 public Uid.Proc getProcessStatsLocked(int uid, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013220 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013221 Uid u = getUidStatsLocked(uid);
13222 return u.getProcessStatsLocked(name);
13223 }
13224
13225 /**
13226 * Retrieve the statistics object for a particular process, creating
13227 * if needed.
13228 */
13229 public Uid.Pkg getPackageStatsLocked(int uid, String pkg) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013230 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013231 Uid u = getUidStatsLocked(uid);
13232 return u.getPackageStatsLocked(pkg);
13233 }
13234
13235 /**
13236 * Retrieve the statistics object for a particular service, creating
13237 * if needed.
13238 */
13239 public Uid.Pkg.Serv getServiceStatsLocked(int uid, String pkg, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013240 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013241 Uid u = getUidStatsLocked(uid);
13242 return u.getServiceStatsLocked(pkg, name);
13243 }
13244
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013245 public void shutdownLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080013246 recordShutdownLocked(mClocks.elapsedRealtime(), mClocks.uptimeMillis());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013247 writeSyncLocked();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013248 mShuttingDown = true;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013249 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013250
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013251 public boolean trackPerProcStateCpuTimes() {
13252 return mConstants.TRACK_CPU_TIMES_BY_PROC_STATE && mPerProcStateCpuTimesAvailable;
13253 }
13254
13255 public void systemServicesReady(Context context) {
13256 mConstants.startObserving(context.getContentResolver());
Mike Mafbc01fc2018-04-02 10:28:28 -070013257 registerUsbStateReceiver(context);
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013258 }
13259
13260 @VisibleForTesting
13261 public final class Constants extends ContentObserver {
13262 public static final String KEY_TRACK_CPU_TIMES_BY_PROC_STATE
13263 = "track_cpu_times_by_proc_state";
Mike Mafae87da2018-01-19 20:07:20 -080013264 public static final String KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME
13265 = "track_cpu_active_cluster_time";
Sudheer Shankac20379e2018-02-15 00:06:21 -080013266 public static final String KEY_PROC_STATE_CPU_TIMES_READ_DELAY_MS
13267 = "proc_state_cpu_times_read_delay_ms";
Mike Ma2ab01442018-02-13 14:22:47 -080013268 public static final String KEY_KERNEL_UID_READERS_THROTTLE_TIME
13269 = "kernel_uid_readers_throttle_time";
Mike Ma234d1822018-03-13 18:53:21 -070013270 public static final String KEY_UID_REMOVE_DELAY_MS
13271 = "uid_remove_delay_ms";
Sudheer Shankae56013a2018-04-23 11:22:15 -070013272 public static final String KEY_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS
13273 = "external_stats_collection_rate_limit_ms";
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013274
13275 private static final boolean DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE = true;
Mike Mafae87da2018-01-19 20:07:20 -080013276 private static final boolean DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME = true;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013277 private static final long DEFAULT_PROC_STATE_CPU_TIMES_READ_DELAY_MS = 5_000;
Mike Ma2ab01442018-02-13 14:22:47 -080013278 private static final long DEFAULT_KERNEL_UID_READERS_THROTTLE_TIME = 10_000;
Mike Ma234d1822018-03-13 18:53:21 -070013279 private static final long DEFAULT_UID_REMOVE_DELAY_MS = 5L * 60L * 1000L;
Sudheer Shankae56013a2018-04-23 11:22:15 -070013280 private static final long DEFAULT_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS = 600_000;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013281
13282 public boolean TRACK_CPU_TIMES_BY_PROC_STATE = DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE;
Mike Mafae87da2018-01-19 20:07:20 -080013283 public boolean TRACK_CPU_ACTIVE_CLUSTER_TIME = DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013284 public long PROC_STATE_CPU_TIMES_READ_DELAY_MS = DEFAULT_PROC_STATE_CPU_TIMES_READ_DELAY_MS;
Mike Ma2ab01442018-02-13 14:22:47 -080013285 public long KERNEL_UID_READERS_THROTTLE_TIME = DEFAULT_KERNEL_UID_READERS_THROTTLE_TIME;
Mike Ma234d1822018-03-13 18:53:21 -070013286 public long UID_REMOVE_DELAY_MS = DEFAULT_UID_REMOVE_DELAY_MS;
Sudheer Shankae56013a2018-04-23 11:22:15 -070013287 public long EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS
13288 = DEFAULT_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013289
13290 private ContentResolver mResolver;
13291 private final KeyValueListParser mParser = new KeyValueListParser(',');
13292
13293 public Constants(Handler handler) {
13294 super(handler);
13295 }
13296
13297 public void startObserving(ContentResolver resolver) {
13298 mResolver = resolver;
13299 mResolver.registerContentObserver(
13300 Settings.Global.getUriFor(Settings.Global.BATTERY_STATS_CONSTANTS),
13301 false /* notifyForDescendants */, this);
13302 updateConstants();
13303 }
13304
13305 @Override
13306 public void onChange(boolean selfChange, Uri uri) {
13307 updateConstants();
13308 }
13309
13310 private void updateConstants() {
13311 synchronized (BatteryStatsImpl.this) {
13312 try {
13313 mParser.setString(Settings.Global.getString(mResolver,
13314 Settings.Global.BATTERY_STATS_CONSTANTS));
13315 } catch (IllegalArgumentException e) {
13316 // Failed to parse the settings string, log this and move on
13317 // with defaults.
13318 Slog.e(TAG, "Bad batterystats settings", e);
13319 }
13320
13321 updateTrackCpuTimesByProcStateLocked(TRACK_CPU_TIMES_BY_PROC_STATE,
13322 mParser.getBoolean(KEY_TRACK_CPU_TIMES_BY_PROC_STATE,
13323 DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE));
Mike Mafae87da2018-01-19 20:07:20 -080013324 TRACK_CPU_ACTIVE_CLUSTER_TIME = mParser.getBoolean(
13325 KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME, DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME);
Sudheer Shankac20379e2018-02-15 00:06:21 -080013326 updateProcStateCpuTimesReadDelayMs(PROC_STATE_CPU_TIMES_READ_DELAY_MS,
13327 mParser.getLong(KEY_PROC_STATE_CPU_TIMES_READ_DELAY_MS,
Mike Ma2ab01442018-02-13 14:22:47 -080013328 DEFAULT_PROC_STATE_CPU_TIMES_READ_DELAY_MS));
13329 updateKernelUidReadersThrottleTime(KERNEL_UID_READERS_THROTTLE_TIME,
13330 mParser.getLong(KEY_KERNEL_UID_READERS_THROTTLE_TIME,
13331 DEFAULT_KERNEL_UID_READERS_THROTTLE_TIME));
Mike Ma234d1822018-03-13 18:53:21 -070013332 updateUidRemoveDelay(
13333 mParser.getLong(KEY_UID_REMOVE_DELAY_MS, DEFAULT_UID_REMOVE_DELAY_MS));
Sudheer Shankae56013a2018-04-23 11:22:15 -070013334 EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS = mParser.getLong(
13335 KEY_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS,
13336 DEFAULT_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS);
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013337 }
13338 }
13339
13340 private void updateTrackCpuTimesByProcStateLocked(boolean wasEnabled, boolean isEnabled) {
13341 TRACK_CPU_TIMES_BY_PROC_STATE = isEnabled;
13342 if (isEnabled && !wasEnabled) {
13343 mKernelSingleUidTimeReader.markDataAsStale(true);
13344 mExternalSync.scheduleCpuSyncDueToSettingChange();
Sudheer Shankac20379e2018-02-15 00:06:21 -080013345
Mike Ma234d1822018-03-13 18:53:21 -070013346 mNumSingleUidCpuTimeReads = 0;
13347 mNumBatchedSingleUidCpuTimeReads = 0;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013348 mCpuTimeReadsTrackingStartTime = mClocks.uptimeMillis();
13349 }
13350 }
13351
13352 private void updateProcStateCpuTimesReadDelayMs(long oldDelayMillis, long newDelayMillis) {
13353 PROC_STATE_CPU_TIMES_READ_DELAY_MS = newDelayMillis;
13354 if (oldDelayMillis != newDelayMillis) {
Mike Ma234d1822018-03-13 18:53:21 -070013355 mNumSingleUidCpuTimeReads = 0;
13356 mNumBatchedSingleUidCpuTimeReads = 0;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013357 mCpuTimeReadsTrackingStartTime = mClocks.uptimeMillis();
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013358 }
13359 }
13360
Mike Ma2ab01442018-02-13 14:22:47 -080013361 private void updateKernelUidReadersThrottleTime(long oldTimeMs, long newTimeMs) {
13362 KERNEL_UID_READERS_THROTTLE_TIME = newTimeMs;
13363 if (oldTimeMs != newTimeMs) {
Mike Ma69d8b3e2018-02-23 14:51:26 -080013364 mKernelUidCpuTimeReader.setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
Mike Ma2ab01442018-02-13 14:22:47 -080013365 mKernelUidCpuFreqTimeReader.setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
13366 mKernelUidCpuActiveTimeReader.setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
13367 mKernelUidCpuClusterTimeReader
13368 .setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
13369 }
13370 }
13371
Mike Ma234d1822018-03-13 18:53:21 -070013372 private void updateUidRemoveDelay(long newTimeMs) {
13373 UID_REMOVE_DELAY_MS = newTimeMs;
13374 clearPendingRemovedUids();
13375 }
13376
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013377 public void dumpLocked(PrintWriter pw) {
13378 pw.print(KEY_TRACK_CPU_TIMES_BY_PROC_STATE); pw.print("=");
13379 pw.println(TRACK_CPU_TIMES_BY_PROC_STATE);
Mike Mafae87da2018-01-19 20:07:20 -080013380 pw.print(KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME); pw.print("=");
13381 pw.println(TRACK_CPU_ACTIVE_CLUSTER_TIME);
Sudheer Shankac20379e2018-02-15 00:06:21 -080013382 pw.print(KEY_PROC_STATE_CPU_TIMES_READ_DELAY_MS); pw.print("=");
13383 pw.println(PROC_STATE_CPU_TIMES_READ_DELAY_MS);
Mike Ma2ab01442018-02-13 14:22:47 -080013384 pw.print(KEY_KERNEL_UID_READERS_THROTTLE_TIME); pw.print("=");
13385 pw.println(KERNEL_UID_READERS_THROTTLE_TIME);
Sudheer Shankae56013a2018-04-23 11:22:15 -070013386 pw.print(KEY_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS); pw.print("=");
13387 pw.println(EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS);
13388 }
13389 }
13390
13391 public long getExternalStatsCollectionRateLimitMs() {
13392 synchronized (this) {
13393 return mConstants.EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013394 }
13395 }
13396
Andreas Gampe3f24e692018-02-05 13:24:28 -080013397 @GuardedBy("this")
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013398 public void dumpConstantsLocked(PrintWriter pw) {
13399 mConstants.dumpLocked(pw);
13400 }
13401
Mike Ma234d1822018-03-13 18:53:21 -070013402 @GuardedBy("this")
13403 public void dumpCpuStatsLocked(PrintWriter pw) {
13404 int size = mUidStats.size();
13405 pw.println("Per UID CPU user & system time in ms:");
13406 for (int i = 0; i < size; i++) {
13407 int u = mUidStats.keyAt(i);
13408 Uid uid = mUidStats.get(u);
13409 pw.print(" "); pw.print(u); pw.print(": ");
13410 pw.print(uid.getUserCpuTimeUs(STATS_SINCE_CHARGED) / 1000); pw.print(" ");
13411 pw.println(uid.getSystemCpuTimeUs(STATS_SINCE_CHARGED) / 1000);
13412 }
13413 pw.println("Per UID CPU active time in ms:");
13414 for (int i = 0; i < size; i++) {
13415 int u = mUidStats.keyAt(i);
13416 Uid uid = mUidStats.get(u);
13417 if (uid.getCpuActiveTime() > 0) {
13418 pw.print(" "); pw.print(u); pw.print(": "); pw.println(uid.getCpuActiveTime());
13419 }
13420 }
13421 pw.println("Per UID CPU cluster time in ms:");
13422 for (int i = 0; i < size; i++) {
13423 int u = mUidStats.keyAt(i);
13424 long[] times = mUidStats.get(u).getCpuClusterTimes();
13425 if (times != null) {
13426 pw.print(" "); pw.print(u); pw.print(": "); pw.println(Arrays.toString(times));
13427 }
13428 }
13429 pw.println("Per UID CPU frequency time in ms:");
13430 for (int i = 0; i < size; i++) {
13431 int u = mUidStats.keyAt(i);
13432 long[] times = mUidStats.get(u).getCpuFreqTimes(STATS_SINCE_CHARGED);
13433 if (times != null) {
13434 pw.print(" "); pw.print(u); pw.print(": "); pw.println(Arrays.toString(times));
13435 }
13436 }
13437 }
13438
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013439 Parcel mPendingWrite = null;
13440 final ReentrantLock mWriteLock = new ReentrantLock();
13441
13442 public void writeAsyncLocked() {
13443 writeLocked(false);
13444 }
13445
13446 public void writeSyncLocked() {
13447 writeLocked(true);
13448 }
13449
13450 void writeLocked(boolean sync) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013451 if (mFile == null) {
13452 Slog.w("BatteryStats", "writeLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013453 return;
13454 }
13455
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013456 if (mShuttingDown) {
13457 return;
13458 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013459
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013460 Parcel out = Parcel.obtain();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013461 writeSummaryToParcel(out, true);
Joe Onoratoabded112016-02-08 16:49:39 -080013462 mLastWriteTime = mClocks.elapsedRealtime();
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013463
13464 if (mPendingWrite != null) {
13465 mPendingWrite.recycle();
13466 }
13467 mPendingWrite = out;
13468
13469 if (sync) {
13470 commitPendingDataToDisk();
13471 } else {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013472 BackgroundThread.getHandler().post(new Runnable() {
13473 @Override public void run() {
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013474 commitPendingDataToDisk();
13475 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013476 });
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013477 }
13478 }
13479
13480 public void commitPendingDataToDisk() {
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070013481 final Parcel next;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013482 synchronized (this) {
13483 next = mPendingWrite;
13484 mPendingWrite = null;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070013485 if (next == null) {
13486 return;
13487 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013488 }
13489
Amith Yamasanid2450862017-02-07 15:58:24 -080013490 mWriteLock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013491 try {
Dianne Hackborne17b4452018-01-10 13:15:40 -080013492 final long startTime = SystemClock.uptimeMillis();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013493 FileOutputStream stream = new FileOutputStream(mFile.chooseForWrite());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013494 stream.write(next.marshall());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013495 stream.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070013496 FileUtils.sync(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013497 stream.close();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013498 mFile.commit();
Dianne Hackborne17b4452018-01-10 13:15:40 -080013499 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
13500 "batterystats", SystemClock.uptimeMillis() - startTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013501 } catch (IOException e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013502 Slog.w("BatteryStats", "Error writing battery statistics", e);
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013503 mFile.rollback();
13504 } finally {
13505 next.recycle();
13506 mWriteLock.unlock();
Suchi Amalapurapu8550f252009-09-29 15:20:32 -070013507 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013508 }
13509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013510 public void readLocked() {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013511 if (mDailyFile != null) {
13512 readDailyStatsLocked();
13513 }
13514
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013515 if (mFile == null) {
13516 Slog.w("BatteryStats", "readLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013517 return;
13518 }
13519
13520 mUidStats.clear();
13521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013522 try {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013523 File file = mFile.chooseForRead();
13524 if (!file.exists()) {
13525 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013526 }
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013527 FileInputStream stream = new FileInputStream(file);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013528
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013529 byte[] raw = BatteryStatsHelper.readFully(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013530 Parcel in = Parcel.obtain();
13531 in.unmarshall(raw, 0, raw.length);
13532 in.setDataPosition(0);
13533 stream.close();
13534
13535 readSummaryFromParcel(in);
Dianne Hackborn00e25212014-02-19 10:49:24 -080013536 } catch(Exception e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013537 Slog.e("BatteryStats", "Error reading battery statistics", e);
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013538 resetAllStatsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013539 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013540
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013541 mEndPlatformVersion = Build.ID;
13542
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013543 if (mHistoryBuffer.dataPosition() > 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013544 mRecordingHistory = true;
Joe Onoratoabded112016-02-08 16:49:39 -080013545 final long elapsedRealtime = mClocks.elapsedRealtime();
13546 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013547 if (USE_OLD_HISTORY) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013548 addHistoryRecordLocked(elapsedRealtime, uptime, HistoryItem.CMD_START, mHistoryCur);
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013549 }
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000013550 addHistoryBufferLocked(elapsedRealtime, HistoryItem.CMD_START, mHistoryCur);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013551 startRecordingHistory(elapsedRealtime, uptime, false);
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013552 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013553
13554 recordDailyStatsIfNeededLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013555 }
13556
13557 public int describeContents() {
13558 return 0;
13559 }
13560
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013561 void readHistory(Parcel in, boolean andOldHistory) throws ParcelFormatException {
Dianne Hackbornae384452011-06-28 12:33:48 -070013562 final long historyBaseTime = in.readLong();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013563
13564 mHistoryBuffer.setDataSize(0);
13565 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013566 mHistoryTagPool.clear();
13567 mNextHistoryTagIdx = 0;
13568 mNumHistoryTagChars = 0;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013569
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013570 int numTags = in.readInt();
13571 for (int i=0; i<numTags; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080013572 int idx = in.readInt();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013573 String str = in.readString();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013574 if (str == null) {
13575 throw new ParcelFormatException("null history tag string");
13576 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013577 int uid = in.readInt();
13578 HistoryTag tag = new HistoryTag();
13579 tag.string = str;
13580 tag.uid = uid;
13581 tag.poolIdx = idx;
13582 mHistoryTagPool.put(tag, idx);
13583 if (idx >= mNextHistoryTagIdx) {
13584 mNextHistoryTagIdx = idx+1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013585 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013586 mNumHistoryTagChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013587 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013588
13589 int bufSize = in.readInt();
13590 int curPos = in.dataPosition();
13591 if (bufSize >= (MAX_MAX_HISTORY_BUFFER*3)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013592 throw new ParcelFormatException("File corrupt: history data buffer too large " +
13593 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013594 } else if ((bufSize&~3) != bufSize) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013595 throw new ParcelFormatException("File corrupt: history data buffer not aligned " +
13596 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013597 } else {
13598 if (DEBUG_HISTORY) Slog.i(TAG, "***************** READING NEW HISTORY: " + bufSize
13599 + " bytes at " + curPos);
13600 mHistoryBuffer.appendFrom(in, curPos, bufSize);
13601 in.setDataPosition(curPos + bufSize);
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013602 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013603
Dianne Hackbornae384452011-06-28 12:33:48 -070013604 if (andOldHistory) {
13605 readOldHistory(in);
13606 }
13607
13608 if (DEBUG_HISTORY) {
13609 StringBuilder sb = new StringBuilder(128);
13610 sb.append("****************** OLD mHistoryBaseTime: ");
13611 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13612 Slog.i(TAG, sb.toString());
13613 }
13614 mHistoryBaseTime = historyBaseTime;
13615 if (DEBUG_HISTORY) {
13616 StringBuilder sb = new StringBuilder(128);
13617 sb.append("****************** NEW mHistoryBaseTime: ");
13618 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13619 Slog.i(TAG, sb.toString());
13620 }
13621
13622 // We are just arbitrarily going to insert 1 minute from the sample of
13623 // the last run until samples in this run.
13624 if (mHistoryBaseTime > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -080013625 long oldnow = mClocks.elapsedRealtime();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013626 mHistoryBaseTime = mHistoryBaseTime - oldnow + 1;
Dianne Hackbornae384452011-06-28 12:33:48 -070013627 if (DEBUG_HISTORY) {
13628 StringBuilder sb = new StringBuilder(128);
13629 sb.append("****************** ADJUSTED mHistoryBaseTime: ");
13630 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13631 Slog.i(TAG, sb.toString());
13632 }
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -070013633 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013634 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013635
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013636 void readOldHistory(Parcel in) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013637 if (!USE_OLD_HISTORY) {
13638 return;
13639 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013640 mHistory = mHistoryEnd = mHistoryCache = null;
13641 long time;
Conley Owens5e3357f2011-05-02 09:59:30 -070013642 while (in.dataAvail() > 0 && (time=in.readLong()) >= 0) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013643 HistoryItem rec = new HistoryItem(time, in);
13644 addHistoryRecordLocked(rec);
13645 }
13646 }
13647
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013648 void writeHistory(Parcel out, boolean inclData, boolean andOldHistory) {
Dianne Hackbornae384452011-06-28 12:33:48 -070013649 if (DEBUG_HISTORY) {
13650 StringBuilder sb = new StringBuilder(128);
13651 sb.append("****************** WRITING mHistoryBaseTime: ");
13652 TimeUtils.formatDuration(mHistoryBaseTime, sb);
Dianne Hackborn40c87252014-03-19 16:55:40 -070013653 sb.append(" mLastHistoryElapsedRealtime: ");
13654 TimeUtils.formatDuration(mLastHistoryElapsedRealtime, sb);
Dianne Hackbornae384452011-06-28 12:33:48 -070013655 Slog.i(TAG, sb.toString());
13656 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070013657 out.writeLong(mHistoryBaseTime + mLastHistoryElapsedRealtime);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013658 if (!inclData) {
13659 out.writeInt(0);
13660 out.writeInt(0);
13661 return;
13662 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013663 out.writeInt(mHistoryTagPool.size());
13664 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
13665 HistoryTag tag = ent.getKey();
Dianne Hackborn099bc622014-01-22 13:39:16 -080013666 out.writeInt(ent.getValue());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013667 out.writeString(tag.string);
13668 out.writeInt(tag.uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -080013669 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013670 out.writeInt(mHistoryBuffer.dataSize());
13671 if (DEBUG_HISTORY) Slog.i(TAG, "***************** WRITING HISTORY: "
13672 + mHistoryBuffer.dataSize() + " bytes at " + out.dataPosition());
13673 out.appendFrom(mHistoryBuffer, 0, mHistoryBuffer.dataSize());
Dianne Hackbornae384452011-06-28 12:33:48 -070013674
13675 if (andOldHistory) {
13676 writeOldHistory(out);
13677 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013678 }
13679
13680 void writeOldHistory(Parcel out) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013681 if (!USE_OLD_HISTORY) {
13682 return;
13683 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013684 HistoryItem rec = mHistory;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013685 while (rec != null) {
13686 if (rec.time >= 0) rec.writeToParcel(out, 0);
13687 rec = rec.next;
13688 }
13689 out.writeLong(-1);
13690 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013691
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013692 public void readSummaryFromParcel(Parcel in) throws ParcelFormatException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013693 final int version = in.readInt();
13694 if (version != VERSION) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013695 Slog.w("BatteryStats", "readFromParcel: version got " + version
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013696 + ", expected " + VERSION + "; erasing old stats");
13697 return;
13698 }
13699
Dianne Hackbornae384452011-06-28 12:33:48 -070013700 readHistory(in, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013702 mStartCount = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013703 mUptime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013704 mRealtime = in.readLong();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080013705 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013706 mStartPlatformVersion = in.readString();
13707 mEndPlatformVersion = in.readString();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013708 mOnBatteryTimeBase.readSummaryFromParcel(in);
13709 mOnBatteryScreenOffTimeBase.readSummaryFromParcel(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013710 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013711 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070013712 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013713 mCurrentBatteryLevel = in.readInt();
Adam Lesinskif9b20a92016-06-17 17:30:01 -070013714 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070013715 mMinLearnedBatteryCapacity = in.readInt();
13716 mMaxLearnedBatteryCapacity = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013717 mLowDischargeAmountSinceCharge = in.readInt();
13718 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013719 mDischargeAmountScreenOnSinceCharge = in.readInt();
13720 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070013721 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013722 mDischargeStepTracker.readFromParcel(in);
13723 mChargeStepTracker.readFromParcel(in);
13724 mDailyDischargeStepTracker.readFromParcel(in);
13725 mDailyChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070013726 mDischargeCounter.readSummaryFromParcelLocked(in);
13727 mDischargeScreenOffCounter.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070013728 mDischargeScreenDozeCounter.readSummaryFromParcelLocked(in);
Mike Ma15313c92017-11-15 17:58:21 -080013729 mDischargeLightDozeCounter.readSummaryFromParcelLocked(in);
13730 mDischargeDeepDozeCounter.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013731 int NPKG = in.readInt();
13732 if (NPKG > 0) {
13733 mDailyPackageChanges = new ArrayList<>(NPKG);
13734 while (NPKG > 0) {
13735 NPKG--;
13736 PackageChange pc = new PackageChange();
13737 pc.mPackageName = in.readString();
13738 pc.mUpdate = in.readInt() != 0;
Dianne Hackborn3accca02013-09-20 09:32:11 -070013739 pc.mVersionCode = in.readLong();
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013740 mDailyPackageChanges.add(pc);
13741 }
13742 } else {
13743 mDailyPackageChanges = null;
13744 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013745 mDailyStartTime = in.readLong();
13746 mNextMinDailyDeadline = in.readLong();
13747 mNextMaxDailyDeadline = in.readLong();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013749 mStartCount++;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013750
Jeff Browne95c3cd2014-05-02 16:59:26 -070013751 mScreenState = Display.STATE_UNKNOWN;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013752 mScreenOnTimer.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070013753 mScreenDozeTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn617f8772009-03-31 15:04:46 -070013754 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
13755 mScreenBrightnessTimer[i].readSummaryFromParcelLocked(in);
13756 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070013757 mInteractive = false;
13758 mInteractiveTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013759 mPhoneOn = false;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070013760 mPowerSaveModeEnabledTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070013761 mLongestLightIdleTime = in.readLong();
13762 mLongestFullIdleTime = in.readLong();
13763 mDeviceIdleModeLightTimer.readSummaryFromParcelLocked(in);
13764 mDeviceIdleModeFullTimer.readSummaryFromParcelLocked(in);
13765 mDeviceLightIdlingTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013766 mDeviceIdlingTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013767 mPhoneOnTimer.readSummaryFromParcelLocked(in);
Wink Saville52840902011-02-18 12:40:47 -080013768 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn627bba72009-03-24 22:32:56 -070013769 mPhoneSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
13770 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070013771 mPhoneSignalScanningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013772 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
13773 mPhoneDataConnectionsTimer[i].readSummaryFromParcelLocked(in);
13774 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013775 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013776 mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
13777 mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013778 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013779 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborne13c4c02014-02-11 17:18:35 -080013780 mMobileRadioActiveTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080013781 mMobileRadioActivePerAppTimer.readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013782 mMobileRadioActiveAdjustedTime.readSummaryFromParcelLocked(in);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013783 mMobileRadioActiveUnknownTime.readSummaryFromParcelLocked(in);
13784 mMobileRadioActiveUnknownCount.readSummaryFromParcelLocked(in);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080013785 mWifiMulticastWakelockTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070013786 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
The Android Open Source Project10592532009-03-18 17:39:46 -070013787 mWifiOn = false;
13788 mWifiOnTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013789 mGlobalWifiRunning = false;
13790 mGlobalWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080013791 for (int i=0; i<NUM_WIFI_STATES; i++) {
13792 mWifiStateTimer[i].readSummaryFromParcelLocked(in);
13793 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070013794 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
13795 mWifiSupplStateTimer[i].readSummaryFromParcelLocked(in);
13796 }
13797 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
13798 mWifiSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
13799 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080013800 mWifiActiveTimer.readSummaryFromParcelLocked(in);
13801 mWifiActivity.readSummaryFromParcel(in);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080013802 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
13803 mGpsSignalQualityTimer[i].readSummaryFromParcelLocked(in);
13804 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080013805 mBluetoothActivity.readSummaryFromParcel(in);
13806 mModemActivity.readSummaryFromParcel(in);
13807 mHasWifiReporting = in.readInt() != 0;
13808 mHasBluetoothReporting = in.readInt() != 0;
13809 mHasModemReporting = in.readInt() != 0;
Adam Lesinski33dac552015-03-09 15:24:48 -070013810
Dianne Hackborn1e01d162014-12-04 17:46:42 -080013811 mNumConnectivityChange = mLoadedNumConnectivityChange = in.readInt();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013812 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -070013813 mFlashlightOnTimer.readSummaryFromParcelLocked(in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013814 mCameraOnNesting = 0;
13815 mCameraOnTimer.readSummaryFromParcelLocked(in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013816 mBluetoothScanNesting = 0;
13817 mBluetoothScanTimer.readSummaryFromParcelLocked(in);
Siddharth Rayf5e796a2018-01-22 18:18:17 -080013818 mIsCellularTxPowerHigh = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013819
Bookatz50df7112017-08-04 14:53:26 -070013820 int NRPMS = in.readInt();
13821 if (NRPMS > 10000) {
13822 throw new ParcelFormatException("File corrupt: too many rpm stats " + NRPMS);
13823 }
13824 for (int irpm = 0; irpm < NRPMS; irpm++) {
13825 if (in.readInt() != 0) {
13826 String rpmName = in.readString();
13827 getRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
13828 }
13829 }
13830 int NSORPMS = in.readInt();
13831 if (NSORPMS > 10000) {
13832 throw new ParcelFormatException("File corrupt: too many screen-off rpm stats " + NSORPMS);
13833 }
13834 for (int irpm = 0; irpm < NSORPMS; irpm++) {
13835 if (in.readInt() != 0) {
13836 String rpmName = in.readString();
13837 getScreenOffRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
13838 }
13839 }
13840
Evan Millarc64edde2009-04-18 12:26:32 -070013841 int NKW = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013842 if (NKW > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013843 throw new ParcelFormatException("File corrupt: too many kernel wake locks " + NKW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013844 }
Evan Millarc64edde2009-04-18 12:26:32 -070013845 for (int ikw = 0; ikw < NKW; ikw++) {
13846 if (in.readInt() != 0) {
13847 String kwltName = in.readString();
13848 getKernelWakelockTimerLocked(kwltName).readSummaryFromParcelLocked(in);
13849 }
13850 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070013851
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013852 int NWR = in.readInt();
13853 if (NWR > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013854 throw new ParcelFormatException("File corrupt: too many wakeup reasons " + NWR);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013855 }
13856 for (int iwr = 0; iwr < NWR; iwr++) {
13857 if (in.readInt() != 0) {
13858 String reasonName = in.readString();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070013859 getWakeupReasonTimerLocked(reasonName).readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013860 }
13861 }
13862
James Carr3a226052016-07-01 14:49:52 -070013863 int NMS = in.readInt();
13864 for (int ims = 0; ims < NMS; ims++) {
13865 if (in.readInt() != 0) {
13866 long kmstName = in.readLong();
13867 getKernelMemoryTimerLocked(kmstName).readSummaryFromParcelLocked(in);
13868 }
13869 }
13870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013871 final int NU = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013872 if (NU > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013873 throw new ParcelFormatException("File corrupt: too many uids " + NU);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013874 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013875 for (int iu = 0; iu < NU; iu++) {
13876 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080013877 Uid u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013878 mUidStats.put(uid, u);
13879
Bookatz867c0d72017-03-07 18:23:42 -080013880 u.mOnBatteryBackgroundTimeBase.readSummaryFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -070013881 u.mOnBatteryScreenOffBackgroundTimeBase.readSummaryFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -080013882
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013883 u.mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013884 if (in.readInt() != 0) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013885 u.mWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013886 }
The Android Open Source Project10592532009-03-18 17:39:46 -070013887 u.mFullWifiLockOut = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013888 if (in.readInt() != 0) {
13889 u.mFullWifiLockTimer.readSummaryFromParcelLocked(in);
13890 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070013891 u.mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013892 if (in.readInt() != 0) {
Nick Pelly6ccaa542012-06-15 15:22:47 -070013893 u.mWifiScanTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013894 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070013895 u.mWifiBatchedScanBinStarted = Uid.NO_BATCHED_SCAN_STARTED;
13896 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
13897 if (in.readInt() != 0) {
13898 u.makeWifiBatchedScanBin(i, null);
13899 u.mWifiBatchedScanTimer[i].readSummaryFromParcelLocked(in);
13900 }
13901 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070013902 u.mWifiMulticastEnabled = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013903 if (in.readInt() != 0) {
13904 u.mWifiMulticastTimer.readSummaryFromParcelLocked(in);
13905 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013906 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013907 u.createAudioTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013908 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013909 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013910 u.createVideoTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13911 }
13912 if (in.readInt() != 0) {
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013913 u.createFlashlightTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13914 }
13915 if (in.readInt() != 0) {
13916 u.createCameraTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13917 }
13918 if (in.readInt() != 0) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013919 u.createForegroundActivityTimerLocked().readSummaryFromParcelLocked(in);
13920 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013921 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070013922 u.createForegroundServiceTimerLocked().readSummaryFromParcelLocked(in);
13923 }
13924 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -070013925 u.createAggregatedPartialWakelockTimerLocked().readSummaryFromParcelLocked(in);
13926 }
13927 if (in.readInt() != 0) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013928 u.createBluetoothScanTimerLocked().readSummaryFromParcelLocked(in);
13929 }
Bookatz956f36bf2017-04-28 09:48:17 -070013930 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -070013931 u.createBluetoothUnoptimizedScanTimerLocked().readSummaryFromParcelLocked(in);
13932 }
13933 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -070013934 u.createBluetoothScanResultCounterLocked().readSummaryFromParcelLocked(in);
13935 }
Bookatzb1f04f32017-05-19 13:57:32 -070013936 if (in.readInt() != 0) {
13937 u.createBluetoothScanResultBgCounterLocked().readSummaryFromParcelLocked(in);
13938 }
Dianne Hackborna8d10942015-11-19 17:55:19 -080013939 u.mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -070013940 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
13941 if (in.readInt() != 0) {
13942 u.makeProcessState(i, null);
13943 u.mProcessStateTimer[i].readSummaryFromParcelLocked(in);
13944 }
13945 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013946 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013947 u.createVibratorOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013948 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070013949
Dianne Hackborn617f8772009-03-31 15:04:46 -070013950 if (in.readInt() != 0) {
13951 if (u.mUserActivityCounters == null) {
13952 u.initUserActivityLocked();
13953 }
13954 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
13955 u.mUserActivityCounters[i].readSummaryFromParcelLocked(in);
13956 }
13957 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013958
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013959 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013960 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013961 u.initNetworkActivityLocked();
13962 }
13963 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013964 u.mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
13965 u.mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013966 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013967 u.mMobileRadioActiveTime.readSummaryFromParcelLocked(in);
13968 u.mMobileRadioActiveCount.readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013969 }
13970
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013971 u.mUserCpuTime.readSummaryFromParcelLocked(in);
13972 u.mSystemCpuTime.readSummaryFromParcelLocked(in);
13973
Adam Lesinski6832f392015-09-05 18:05:40 -070013974 if (in.readInt() != 0) {
13975 final int numClusters = in.readInt();
13976 if (mPowerProfile != null && mPowerProfile.getNumCpuClusters() != numClusters) {
13977 throw new ParcelFormatException("Incompatible cpu cluster arrangement");
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013978 }
Adam Lesinski6832f392015-09-05 18:05:40 -070013979
Sudheer Shankaaf857412017-07-21 00:14:24 -070013980 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -070013981 for (int cluster = 0; cluster < numClusters; cluster++) {
Adam Lesinski6832f392015-09-05 18:05:40 -070013982 if (in.readInt() != 0) {
Adam Lesinskia57a5402015-09-28 10:21:33 -070013983 final int NSB = in.readInt();
13984 if (mPowerProfile != null &&
13985 mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != NSB) {
13986 throw new ParcelFormatException("File corrupt: too many speed bins " +
13987 NSB);
13988 }
13989
Sudheer Shankaaf857412017-07-21 00:14:24 -070013990 u.mCpuClusterSpeedTimesUs[cluster] = new LongSamplingCounter[NSB];
Adam Lesinski6832f392015-09-05 18:05:40 -070013991 for (int speed = 0; speed < NSB; speed++) {
13992 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070013993 u.mCpuClusterSpeedTimesUs[cluster][speed] = new LongSamplingCounter(
Adam Lesinski6832f392015-09-05 18:05:40 -070013994 mOnBatteryTimeBase);
Sudheer Shankaaf857412017-07-21 00:14:24 -070013995 u.mCpuClusterSpeedTimesUs[cluster][speed].readSummaryFromParcelLocked(in);
Adam Lesinski6832f392015-09-05 18:05:40 -070013996 }
13997 }
Adam Lesinskia57a5402015-09-28 10:21:33 -070013998 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070013999 u.mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -070014000 }
14001 }
14002 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070014003 u.mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014004 }
14005
Sudheer Shanka59f5c002017-05-15 10:57:15 -070014006 u.mCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
14007 in, mOnBatteryTimeBase);
14008 u.mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
14009 in, mOnBatteryScreenOffTimeBase);
Mike Ma3d422c32017-10-25 11:08:57 -070014010
14011 u.mCpuActiveTimeMs.readSummaryFromParcelLocked(in);
14012 u.mCpuClusterTimesMs.readSummaryFromParcelLocked(in);
14013
Sudheer Shankab2f83c12017-11-13 19:25:01 -080014014 int length = in.readInt();
14015 if (length == Uid.NUM_PROCESS_STATE) {
14016 u.mProcStateTimeMs = new LongSamplingCounterArray[length];
14017 for (int procState = 0; procState < length; ++procState) {
14018 u.mProcStateTimeMs[procState]
14019 = LongSamplingCounterArray.readSummaryFromParcelLocked(
14020 in, mOnBatteryTimeBase);
14021 }
14022 } else {
14023 u.mProcStateTimeMs = null;
14024 }
14025 length = in.readInt();
14026 if (length == Uid.NUM_PROCESS_STATE) {
14027 u.mProcStateScreenOffTimeMs = new LongSamplingCounterArray[length];
14028 for (int procState = 0; procState < length; ++procState) {
14029 u.mProcStateScreenOffTimeMs[procState]
14030 = LongSamplingCounterArray.readSummaryFromParcelLocked(
14031 in, mOnBatteryScreenOffTimeBase);
14032 }
14033 } else {
14034 u.mProcStateScreenOffTimeMs = null;
14035 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070014036
14037 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -070014038 u.mMobileRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
14039 u.mMobileRadioApWakeupCount.readSummaryFromParcelLocked(in);
14040 } else {
14041 u.mMobileRadioApWakeupCount = null;
14042 }
14043
14044 if (in.readInt() != 0) {
14045 u.mWifiRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
14046 u.mWifiRadioApWakeupCount.readSummaryFromParcelLocked(in);
14047 } else {
14048 u.mWifiRadioApWakeupCount = null;
14049 }
14050
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014051 int NW = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070014052 if (NW > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014053 throw new ParcelFormatException("File corrupt: too many wake locks " + NW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014054 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014055 for (int iw = 0; iw < NW; iw++) {
14056 String wlName = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014057 u.readWakeSummaryFromParcelLocked(wlName, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014058 }
14059
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014060 int NS = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070014061 if (NS > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014062 throw new ParcelFormatException("File corrupt: too many syncs " + NS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014063 }
14064 for (int is = 0; is < NS; is++) {
14065 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014066 u.readSyncSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014067 }
14068
14069 int NJ = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070014070 if (NJ > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014071 throw new ParcelFormatException("File corrupt: too many job timers " + NJ);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014072 }
14073 for (int ij = 0; ij < NJ; ij++) {
14074 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014075 u.readJobSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014076 }
14077
Dianne Hackborn94326cb2017-06-28 16:17:20 -070014078 u.readJobCompletionsFromParcelLocked(in);
14079
Amith Yamasani977e11f2018-02-16 11:29:54 -080014080 u.mJobsDeferredEventCount.readSummaryFromParcelLocked(in);
14081 u.mJobsDeferredCount.readSummaryFromParcelLocked(in);
14082 u.mJobsFreshnessTimeMs.readSummaryFromParcelLocked(in);
14083 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
14084 if (in.readInt() != 0) {
14085 u.mJobsFreshnessBuckets[i] = new Counter(u.mBsi.mOnBatteryTimeBase);
14086 u.mJobsFreshnessBuckets[i].readSummaryFromParcelLocked(in);
14087 }
14088 }
14089
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014090 int NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014091 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014092 throw new ParcelFormatException("File corrupt: too many sensors " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014093 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014094 for (int is = 0; is < NP; is++) {
14095 int seNumber = in.readInt();
14096 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -080014097 u.getSensorTimerLocked(seNumber, true).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014098 }
14099 }
14100
14101 NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014102 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014103 throw new ParcelFormatException("File corrupt: too many processes " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014104 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014105 for (int ip = 0; ip < NP; ip++) {
14106 String procName = in.readString();
14107 Uid.Proc p = u.getProcessStatsLocked(procName);
14108 p.mUserTime = p.mLoadedUserTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014109 p.mSystemTime = p.mLoadedSystemTime = in.readLong();
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014110 p.mForegroundTime = p.mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014111 p.mStarts = p.mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014112 p.mNumCrashes = p.mLoadedNumCrashes = in.readInt();
14113 p.mNumAnrs = p.mLoadedNumAnrs = in.readInt();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014114 p.readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014115 }
14116
14117 NP = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014118 if (NP > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014119 throw new ParcelFormatException("File corrupt: too many packages " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014120 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014121 for (int ip = 0; ip < NP; ip++) {
14122 String pkgName = in.readString();
14123 Uid.Pkg p = u.getPackageStatsLocked(pkgName);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014124 final int NWA = in.readInt();
14125 if (NWA > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014126 throw new ParcelFormatException("File corrupt: too many wakeup alarms " + NWA);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014127 }
14128 p.mWakeupAlarms.clear();
14129 for (int iwa=0; iwa<NWA; iwa++) {
14130 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -070014131 Counter c = new Counter(mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014132 c.readSummaryFromParcelLocked(in);
14133 p.mWakeupAlarms.put(tag, c);
14134 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014135 NS = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014136 if (NS > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014137 throw new ParcelFormatException("File corrupt: too many services " + NS);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014138 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014139 for (int is = 0; is < NS; is++) {
14140 String servName = in.readString();
14141 Uid.Pkg.Serv s = u.getServiceStatsLocked(pkgName, servName);
14142 s.mStartTime = s.mLoadedStartTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014143 s.mStarts = s.mLoadedStarts = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014144 s.mLaunches = s.mLoadedLaunches = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014145 }
14146 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014147 }
14148 }
14149
14150 /**
14151 * Writes a summary of the statistics to a Parcel, in a format suitable to be written to
14152 * disk. This format does not allow a lossless round-trip.
14153 *
14154 * @param out the Parcel to be written to.
14155 */
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070014156 public void writeSummaryToParcel(Parcel out, boolean inclHistory) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080014157 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014158
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014159 // Pull the clock time. This may update the time and make a new history entry
14160 // if we had originally pulled a time before the RTC was set.
14161 long startClockTime = getStartClockTime();
14162
Joe Onoratoabded112016-02-08 16:49:39 -080014163 final long NOW_SYS = mClocks.uptimeMillis() * 1000;
14164 final long NOWREAL_SYS = mClocks.elapsedRealtime() * 1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014165
14166 out.writeInt(VERSION);
14167
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070014168 writeHistory(out, inclHistory, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014170 out.writeInt(mStartCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014171 out.writeLong(computeUptime(NOW_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014172 out.writeLong(computeRealtime(NOWREAL_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014173 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014174 out.writeString(mStartPlatformVersion);
14175 out.writeString(mEndPlatformVersion);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014176 mOnBatteryTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
14177 mOnBatteryScreenOffTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014178 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014179 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070014180 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014181 out.writeInt(mCurrentBatteryLevel);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014182 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070014183 out.writeInt(mMinLearnedBatteryCapacity);
14184 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborne4a59512010-12-07 11:08:07 -080014185 out.writeInt(getLowDischargeAmountSinceCharge());
14186 out.writeInt(getHighDischargeAmountSinceCharge());
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014187 out.writeInt(getDischargeAmountScreenOnSinceCharge());
14188 out.writeInt(getDischargeAmountScreenOffSinceCharge());
Mike Mac2f518a2017-09-19 16:06:03 -070014189 out.writeInt(getDischargeAmountScreenDozeSinceCharge());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014190 mDischargeStepTracker.writeToParcel(out);
14191 mChargeStepTracker.writeToParcel(out);
14192 mDailyDischargeStepTracker.writeToParcel(out);
14193 mDailyChargeStepTracker.writeToParcel(out);
Adam Lesinski67c134f2016-06-10 15:15:08 -070014194 mDischargeCounter.writeSummaryFromParcelLocked(out);
14195 mDischargeScreenOffCounter.writeSummaryFromParcelLocked(out);
Mike Mac2f518a2017-09-19 16:06:03 -070014196 mDischargeScreenDozeCounter.writeSummaryFromParcelLocked(out);
Mike Ma15313c92017-11-15 17:58:21 -080014197 mDischargeLightDozeCounter.writeSummaryFromParcelLocked(out);
14198 mDischargeDeepDozeCounter.writeSummaryFromParcelLocked(out);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014199 if (mDailyPackageChanges != null) {
14200 final int NPKG = mDailyPackageChanges.size();
14201 out.writeInt(NPKG);
14202 for (int i=0; i<NPKG; i++) {
14203 PackageChange pc = mDailyPackageChanges.get(i);
14204 out.writeString(pc.mPackageName);
14205 out.writeInt(pc.mUpdate ? 1 : 0);
Dianne Hackborn3accca02013-09-20 09:32:11 -070014206 out.writeLong(pc.mVersionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014207 }
14208 } else {
14209 out.writeInt(0);
14210 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014211 out.writeLong(mDailyStartTime);
14212 out.writeLong(mNextMinDailyDeadline);
14213 out.writeLong(mNextMaxDailyDeadline);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014214
14215 mScreenOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Mike Mac2f518a2017-09-19 16:06:03 -070014216 mScreenDozeTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070014217 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014218 mScreenBrightnessTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070014219 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070014220 mInteractiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070014221 mPowerSaveModeEnabledTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014222 out.writeLong(mLongestLightIdleTime);
14223 out.writeLong(mLongestFullIdleTime);
14224 mDeviceIdleModeLightTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14225 mDeviceIdleModeFullTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14226 mDeviceLightIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014227 mDeviceIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014228 mPhoneOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Wink Saville52840902011-02-18 12:40:47 -080014229 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014230 mPhoneSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070014231 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014232 mPhoneSignalScanningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070014233 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014234 mPhoneDataConnectionsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070014235 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014236 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014237 mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
14238 mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014239 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014240 mMobileRadioActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14241 mMobileRadioActivePerAppTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014242 mMobileRadioActiveAdjustedTime.writeSummaryFromParcelLocked(out);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080014243 mMobileRadioActiveUnknownTime.writeSummaryFromParcelLocked(out);
14244 mMobileRadioActiveUnknownCount.writeSummaryFromParcelLocked(out);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014245 mWifiMulticastWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014246 mWifiOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14247 mGlobalWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080014248 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014249 mWifiStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080014250 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014251 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
14252 mWifiSupplStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14253 }
14254 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
14255 mWifiSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14256 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014257 mWifiActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14258 mWifiActivity.writeSummaryToParcel(out);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014259 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14260 mGpsSignalQualityTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14261 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014262 mBluetoothActivity.writeSummaryToParcel(out);
14263 mModemActivity.writeSummaryToParcel(out);
14264 out.writeInt(mHasWifiReporting ? 1 : 0);
14265 out.writeInt(mHasBluetoothReporting ? 1 : 0);
14266 out.writeInt(mHasModemReporting ? 1 : 0);
14267
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014268 out.writeInt(mNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070014269 mFlashlightOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014270 mCameraOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014271 mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014272
Bookatz50df7112017-08-04 14:53:26 -070014273 out.writeInt(mRpmStats.size());
14274 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
14275 Timer rpmt = ent.getValue();
14276 if (rpmt != null) {
14277 out.writeInt(1);
14278 out.writeString(ent.getKey());
14279 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14280 } else {
14281 out.writeInt(0);
14282 }
14283 }
14284 out.writeInt(mScreenOffRpmStats.size());
14285 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
14286 Timer rpmt = ent.getValue();
14287 if (rpmt != null) {
14288 out.writeInt(1);
14289 out.writeString(ent.getKey());
14290 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14291 } else {
14292 out.writeInt(0);
14293 }
14294 }
14295
Evan Millarc64edde2009-04-18 12:26:32 -070014296 out.writeInt(mKernelWakelockStats.size());
14297 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
14298 Timer kwlt = ent.getValue();
14299 if (kwlt != null) {
14300 out.writeInt(1);
14301 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014302 kwlt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14303 } else {
14304 out.writeInt(0);
14305 }
14306 }
14307
14308 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014309 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
14310 SamplingTimer timer = ent.getValue();
14311 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014312 out.writeInt(1);
14313 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014314 timer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Evan Millarc64edde2009-04-18 12:26:32 -070014315 } else {
14316 out.writeInt(0);
14317 }
14318 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014319
James Carr3a226052016-07-01 14:49:52 -070014320 out.writeInt(mKernelMemoryStats.size());
14321 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
14322 Timer kmt = mKernelMemoryStats.valueAt(i);
14323 if (kmt != null) {
14324 out.writeInt(1);
14325 out.writeLong(mKernelMemoryStats.keyAt(i));
14326 kmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14327 } else {
14328 out.writeInt(0);
14329 }
14330 }
14331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014332 final int NU = mUidStats.size();
14333 out.writeInt(NU);
14334 for (int iu = 0; iu < NU; iu++) {
14335 out.writeInt(mUidStats.keyAt(iu));
14336 Uid u = mUidStats.valueAt(iu);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014337
Bookatz867c0d72017-03-07 18:23:42 -080014338 u.mOnBatteryBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatzc8c44962017-05-11 12:12:54 -070014339 u.mOnBatteryScreenOffBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatz867c0d72017-03-07 18:23:42 -080014340
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014341 if (u.mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014342 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014343 u.mWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014344 } else {
14345 out.writeInt(0);
14346 }
14347 if (u.mFullWifiLockTimer != null) {
14348 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014349 u.mFullWifiLockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014350 } else {
14351 out.writeInt(0);
14352 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070014353 if (u.mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014354 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014355 u.mWifiScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014356 } else {
14357 out.writeInt(0);
14358 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070014359 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
14360 if (u.mWifiBatchedScanTimer[i] != null) {
14361 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014362 u.mWifiBatchedScanTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Robert Greenwalta029ea12013-09-25 16:38:12 -070014363 } else {
14364 out.writeInt(0);
14365 }
14366 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014367 if (u.mWifiMulticastTimer != null) {
14368 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014369 u.mWifiMulticastTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014370 } else {
14371 out.writeInt(0);
14372 }
14373 if (u.mAudioTurnedOnTimer != null) {
14374 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014375 u.mAudioTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014376 } else {
14377 out.writeInt(0);
14378 }
14379 if (u.mVideoTurnedOnTimer != null) {
14380 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014381 u.mVideoTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014382 } else {
14383 out.writeInt(0);
14384 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014385 if (u.mFlashlightTurnedOnTimer != null) {
14386 out.writeInt(1);
14387 u.mFlashlightTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14388 } else {
14389 out.writeInt(0);
14390 }
14391 if (u.mCameraTurnedOnTimer != null) {
14392 out.writeInt(1);
14393 u.mCameraTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14394 } else {
14395 out.writeInt(0);
14396 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014397 if (u.mForegroundActivityTimer != null) {
14398 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014399 u.mForegroundActivityTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014400 } else {
14401 out.writeInt(0);
14402 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070014403 if (u.mForegroundServiceTimer != null) {
14404 out.writeInt(1);
14405 u.mForegroundServiceTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14406 } else {
14407 out.writeInt(0);
14408 }
Bookatzc8c44962017-05-11 12:12:54 -070014409 if (u.mAggregatedPartialWakelockTimer != null) {
14410 out.writeInt(1);
14411 u.mAggregatedPartialWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14412 } else {
14413 out.writeInt(0);
14414 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014415 if (u.mBluetoothScanTimer != null) {
14416 out.writeInt(1);
14417 u.mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14418 } else {
14419 out.writeInt(0);
14420 }
Bookatzb1f04f32017-05-19 13:57:32 -070014421 if (u.mBluetoothUnoptimizedScanTimer != null) {
14422 out.writeInt(1);
14423 u.mBluetoothUnoptimizedScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14424 } else {
14425 out.writeInt(0);
14426 }
Bookatz956f36bf2017-04-28 09:48:17 -070014427 if (u.mBluetoothScanResultCounter != null) {
14428 out.writeInt(1);
14429 u.mBluetoothScanResultCounter.writeSummaryFromParcelLocked(out);
14430 } else {
14431 out.writeInt(0);
14432 }
Bookatzb1f04f32017-05-19 13:57:32 -070014433 if (u.mBluetoothScanResultBgCounter != null) {
14434 out.writeInt(1);
14435 u.mBluetoothScanResultBgCounter.writeSummaryFromParcelLocked(out);
14436 } else {
14437 out.writeInt(0);
14438 }
Dianne Hackborn61659e52014-07-09 16:13:01 -070014439 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
14440 if (u.mProcessStateTimer[i] != null) {
14441 out.writeInt(1);
14442 u.mProcessStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14443 } else {
14444 out.writeInt(0);
14445 }
14446 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014447 if (u.mVibratorOnTimer != null) {
14448 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014449 u.mVibratorOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014450 } else {
14451 out.writeInt(0);
14452 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014453
Dianne Hackborn617f8772009-03-31 15:04:46 -070014454 if (u.mUserActivityCounters == null) {
14455 out.writeInt(0);
14456 } else {
14457 out.writeInt(1);
14458 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
14459 u.mUserActivityCounters[i].writeSummaryFromParcelLocked(out);
14460 }
14461 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014462
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014463 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014464 out.writeInt(0);
14465 } else {
14466 out.writeInt(1);
14467 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014468 u.mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
14469 u.mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014470 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080014471 u.mMobileRadioActiveTime.writeSummaryFromParcelLocked(out);
14472 u.mMobileRadioActiveCount.writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014473 }
14474
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014475 u.mUserCpuTime.writeSummaryFromParcelLocked(out);
14476 u.mSystemCpuTime.writeSummaryFromParcelLocked(out);
14477
Sudheer Shankaaf857412017-07-21 00:14:24 -070014478 if (u.mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -070014479 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -070014480 out.writeInt(u.mCpuClusterSpeedTimesUs.length);
14481 for (LongSamplingCounter[] cpuSpeeds : u.mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -070014482 if (cpuSpeeds != null) {
14483 out.writeInt(1);
14484 out.writeInt(cpuSpeeds.length);
14485 for (LongSamplingCounter c : cpuSpeeds) {
14486 if (c != null) {
14487 out.writeInt(1);
14488 c.writeSummaryFromParcelLocked(out);
14489 } else {
14490 out.writeInt(0);
14491 }
14492 }
14493 } else {
14494 out.writeInt(0);
14495 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014496 }
Adam Lesinski6832f392015-09-05 18:05:40 -070014497 } else {
14498 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014499 }
14500
Sudheer Shanka59f5c002017-05-15 10:57:15 -070014501 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mCpuFreqTimeMs);
14502 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mScreenOffCpuFreqTimeMs);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070014503
Mike Ma3d422c32017-10-25 11:08:57 -070014504 u.mCpuActiveTimeMs.writeSummaryFromParcelLocked(out);
14505 u.mCpuClusterTimesMs.writeSummaryToParcelLocked(out);
14506
Sudheer Shankab2f83c12017-11-13 19:25:01 -080014507 if (u.mProcStateTimeMs != null) {
14508 out.writeInt(u.mProcStateTimeMs.length);
14509 for (LongSamplingCounterArray counters : u.mProcStateTimeMs) {
14510 LongSamplingCounterArray.writeSummaryToParcelLocked(out, counters);
14511 }
14512 } else {
14513 out.writeInt(0);
14514 }
14515 if (u.mProcStateScreenOffTimeMs != null) {
14516 out.writeInt(u.mProcStateScreenOffTimeMs.length);
14517 for (LongSamplingCounterArray counters : u.mProcStateScreenOffTimeMs) {
14518 LongSamplingCounterArray.writeSummaryToParcelLocked(out, counters);
14519 }
14520 } else {
14521 out.writeInt(0);
14522 }
14523
Adam Lesinski5f056f62016-07-14 16:56:08 -070014524 if (u.mMobileRadioApWakeupCount != null) {
14525 out.writeInt(1);
14526 u.mMobileRadioApWakeupCount.writeSummaryFromParcelLocked(out);
14527 } else {
14528 out.writeInt(0);
14529 }
14530
14531 if (u.mWifiRadioApWakeupCount != null) {
14532 out.writeInt(1);
14533 u.mWifiRadioApWakeupCount.writeSummaryFromParcelLocked(out);
14534 } else {
14535 out.writeInt(0);
14536 }
14537
Dianne Hackbornd953c532014-08-16 18:17:38 -070014538 final ArrayMap<String, Uid.Wakelock> wakeStats = u.mWakelockStats.getMap();
14539 int NW = wakeStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014540 out.writeInt(NW);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014541 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014542 out.writeString(wakeStats.keyAt(iw));
14543 Uid.Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014544 if (wl.mTimerFull != null) {
14545 out.writeInt(1);
14546 wl.mTimerFull.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14547 } else {
14548 out.writeInt(0);
14549 }
14550 if (wl.mTimerPartial != null) {
14551 out.writeInt(1);
14552 wl.mTimerPartial.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14553 } else {
14554 out.writeInt(0);
14555 }
14556 if (wl.mTimerWindow != null) {
14557 out.writeInt(1);
14558 wl.mTimerWindow.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14559 } else {
14560 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014561 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070014562 if (wl.mTimerDraw != null) {
Adam Lesinski9425fe22015-06-19 12:02:13 -070014563 out.writeInt(1);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070014564 wl.mTimerDraw.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9425fe22015-06-19 12:02:13 -070014565 } else {
14566 out.writeInt(0);
14567 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014568 }
14569
Bookatz2bffb5b2017-04-13 11:59:33 -070014570 final ArrayMap<String, DualTimer> syncStats = u.mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014571 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014572 out.writeInt(NS);
14573 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014574 out.writeString(syncStats.keyAt(is));
14575 syncStats.valueAt(is).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014576 }
14577
Bookatzaa4594a2017-03-24 12:39:56 -070014578 final ArrayMap<String, DualTimer> jobStats = u.mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014579 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014580 out.writeInt(NJ);
14581 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014582 out.writeString(jobStats.keyAt(ij));
14583 jobStats.valueAt(ij).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014584 }
14585
Dianne Hackborn94326cb2017-06-28 16:17:20 -070014586 u.writeJobCompletionsToParcelLocked(out);
14587
Amith Yamasani977e11f2018-02-16 11:29:54 -080014588 u.mJobsDeferredEventCount.writeSummaryFromParcelLocked(out);
14589 u.mJobsDeferredCount.writeSummaryFromParcelLocked(out);
14590 u.mJobsFreshnessTimeMs.writeSummaryFromParcelLocked(out);
14591 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
14592 if (u.mJobsFreshnessBuckets[i] != null) {
Adam Lesinski14082082018-02-23 12:35:55 -080014593 out.writeInt(1);
Amith Yamasani977e11f2018-02-16 11:29:54 -080014594 u.mJobsFreshnessBuckets[i].writeSummaryFromParcelLocked(out);
14595 } else {
14596 out.writeInt(0);
14597 }
14598 }
14599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014600 int NSE = u.mSensorStats.size();
14601 out.writeInt(NSE);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014602 for (int ise=0; ise<NSE; ise++) {
14603 out.writeInt(u.mSensorStats.keyAt(ise));
14604 Uid.Sensor se = u.mSensorStats.valueAt(ise);
14605 if (se.mTimer != null) {
14606 out.writeInt(1);
14607 se.mTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14608 } else {
14609 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014610 }
14611 }
14612
14613 int NP = u.mProcessStats.size();
14614 out.writeInt(NP);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014615 for (int ip=0; ip<NP; ip++) {
14616 out.writeString(u.mProcessStats.keyAt(ip));
14617 Uid.Proc ps = u.mProcessStats.valueAt(ip);
14618 out.writeLong(ps.mUserTime);
14619 out.writeLong(ps.mSystemTime);
14620 out.writeLong(ps.mForegroundTime);
14621 out.writeInt(ps.mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014622 out.writeInt(ps.mNumCrashes);
14623 out.writeInt(ps.mNumAnrs);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014624 ps.writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014625 }
14626
14627 NP = u.mPackageStats.size();
14628 out.writeInt(NP);
14629 if (NP > 0) {
14630 for (Map.Entry<String, BatteryStatsImpl.Uid.Pkg> ent
14631 : u.mPackageStats.entrySet()) {
14632 out.writeString(ent.getKey());
14633 Uid.Pkg ps = ent.getValue();
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014634 final int NWA = ps.mWakeupAlarms.size();
14635 out.writeInt(NWA);
14636 for (int iwa=0; iwa<NWA; iwa++) {
14637 out.writeString(ps.mWakeupAlarms.keyAt(iwa));
14638 ps.mWakeupAlarms.valueAt(iwa).writeSummaryFromParcelLocked(out);
14639 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014640 NS = ps.mServiceStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014641 out.writeInt(NS);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014642 for (int is=0; is<NS; is++) {
14643 out.writeString(ps.mServiceStats.keyAt(is));
14644 BatteryStatsImpl.Uid.Pkg.Serv ss = ps.mServiceStats.valueAt(is);
14645 long time = ss.getStartTimeToNowLocked(
14646 mOnBatteryTimeBase.getUptime(NOW_SYS));
14647 out.writeLong(time);
14648 out.writeInt(ss.mStarts);
14649 out.writeInt(ss.mLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014650 }
14651 }
14652 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014653 }
14654 }
14655
14656 public void readFromParcel(Parcel in) {
14657 readFromParcelLocked(in);
14658 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014660 void readFromParcelLocked(Parcel in) {
14661 int magic = in.readInt();
14662 if (magic != MAGIC) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014663 throw new ParcelFormatException("Bad magic number: #" + Integer.toHexString(magic));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014664 }
14665
Dianne Hackbornae384452011-06-28 12:33:48 -070014666 readHistory(in, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014668 mStartCount = in.readInt();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080014669 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014670 mStartPlatformVersion = in.readString();
14671 mEndPlatformVersion = in.readString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014672 mUptime = in.readLong();
14673 mUptimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014674 mRealtime = in.readLong();
14675 mRealtimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014676 mOnBattery = in.readInt() != 0;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014677 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070014678 mMinLearnedBatteryCapacity = in.readInt();
14679 mMaxLearnedBatteryCapacity = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014680 mOnBatteryInternal = false; // we are no longer really running.
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014681 mOnBatteryTimeBase.readFromParcel(in);
14682 mOnBatteryScreenOffTimeBase.readFromParcel(in);
14683
Jeff Browne95c3cd2014-05-02 16:59:26 -070014684 mScreenState = Display.STATE_UNKNOWN;
Joe Onoratoabded112016-02-08 16:49:39 -080014685 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070014686 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014687 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014688 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
14689 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014690 }
Dianne Hackborn29325132014-05-21 15:01:03 -070014691 mInteractive = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014692 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014693 mPhoneOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014694 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
14695 mOnBatteryTimeBase, in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014696 mLongestLightIdleTime = in.readLong();
14697 mLongestFullIdleTime = in.readLong();
Joe Onoratoabded112016-02-08 16:49:39 -080014698 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -14, null,
14699 mOnBatteryTimeBase, in);
14700 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -11, null,
14701 mOnBatteryTimeBase, in);
14702 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null,
14703 mOnBatteryTimeBase, in);
14704 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase, in);
14705 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014706 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014707 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014708 null, mOnBatteryTimeBase, in);
14709 }
Joe Onoratoabded112016-02-08 16:49:39 -080014710 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
14711 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014712 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014713 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014714 null, mOnBatteryTimeBase, in);
14715 }
14716 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
14717 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
14718 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
14719 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014720 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Joe Onoratoabded112016-02-08 16:49:39 -080014721 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null,
14722 mOnBatteryTimeBase, in);
Kweku Adams87b19ec2017-10-09 12:40:03 -070014723 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
Joe Onoratoabded112016-02-08 16:49:39 -080014724 mOnBatteryTimeBase, in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014725 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014726 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
14727 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase, in);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014728 mWifiMulticastWakelockTimer = new StopwatchTimer(mClocks, null, -4, null,
14729 mOnBatteryTimeBase, in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070014730 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014731 mWifiOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014732 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014733 mGlobalWifiRunning = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014734 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null,
14735 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014736 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014737 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014738 null, mOnBatteryTimeBase, in);
14739 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014740 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014741 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070014742 null, mOnBatteryTimeBase, in);
14743 }
14744 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014745 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070014746 null, mOnBatteryTimeBase, in);
14747 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014748 mWifiActiveTimer = new StopwatchTimer(mClocks, null, -900, null,
14749 mOnBatteryTimeBase, in);
14750 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14751 NUM_WIFI_TX_LEVELS, in);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014752 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14753 mGpsSignalQualityTimer[i] = new StopwatchTimer(mClocks, null, -1000-i,
14754 null, mOnBatteryTimeBase, in);
14755 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014756 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14757 NUM_BT_TX_LEVELS, in);
14758 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14759 ModemActivityInfo.TX_POWER_LEVELS, in);
14760 mHasWifiReporting = in.readInt() != 0;
14761 mHasBluetoothReporting = in.readInt() != 0;
14762 mHasModemReporting = in.readInt() != 0;
14763
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014764 mNumConnectivityChange = in.readInt();
14765 mLoadedNumConnectivityChange = in.readInt();
14766 mUnpluggedNumConnectivityChange = in.readInt();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014767 mAudioOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014768 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014769 mVideoOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014770 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014771 mFlashlightOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014772 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014773 mCameraOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014774 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014775 mBluetoothScanNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014776 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase, in);
Siddharth Rayf5e796a2018-01-22 18:18:17 -080014777 mIsCellularTxPowerHigh = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014778 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014779 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070014780 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014781 mCurrentBatteryLevel = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014782 mLowDischargeAmountSinceCharge = in.readInt();
14783 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014784 mDischargeAmountScreenOn = in.readInt();
14785 mDischargeAmountScreenOnSinceCharge = in.readInt();
14786 mDischargeAmountScreenOff = in.readInt();
14787 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070014788 mDischargeAmountScreenDoze = in.readInt();
14789 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014790 mDischargeStepTracker.readFromParcel(in);
14791 mChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070014792 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070014793 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase, in);
14794 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Ma15313c92017-11-15 17:58:21 -080014795 mDischargeLightDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
14796 mDischargeDeepDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014797 mLastWriteTime = in.readLong();
14798
Bookatz50df7112017-08-04 14:53:26 -070014799 mRpmStats.clear();
14800 int NRPMS = in.readInt();
14801 for (int irpm = 0; irpm < NRPMS; irpm++) {
14802 if (in.readInt() != 0) {
14803 String rpmName = in.readString();
14804 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
14805 mRpmStats.put(rpmName, rpmt);
14806 }
14807 }
14808 mScreenOffRpmStats.clear();
14809 int NSORPMS = in.readInt();
14810 for (int irpm = 0; irpm < NSORPMS; irpm++) {
14811 if (in.readInt() != 0) {
14812 String rpmName = in.readString();
14813 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
14814 mScreenOffRpmStats.put(rpmName, rpmt);
14815 }
14816 }
14817
Evan Millarc64edde2009-04-18 12:26:32 -070014818 mKernelWakelockStats.clear();
14819 int NKW = in.readInt();
14820 for (int ikw = 0; ikw < NKW; ikw++) {
14821 if (in.readInt() != 0) {
14822 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080014823 SamplingTimer kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -070014824 mKernelWakelockStats.put(wakelockName, kwlt);
14825 }
14826 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014827
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014828 mWakeupReasonStats.clear();
14829 int NWR = in.readInt();
14830 for (int iwr = 0; iwr < NWR; iwr++) {
14831 if (in.readInt() != 0) {
14832 String reasonName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080014833 SamplingTimer timer = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014834 mWakeupReasonStats.put(reasonName, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014835 }
14836 }
14837
James Carr3a226052016-07-01 14:49:52 -070014838 mKernelMemoryStats.clear();
14839 int nmt = in.readInt();
14840 for (int imt = 0; imt < nmt; imt++) {
14841 if (in.readInt() != 0) {
14842 Long bucket = in.readLong();
14843 SamplingTimer kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
14844 mKernelMemoryStats.put(bucket, kmt);
14845 }
14846 }
14847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014848 mPartialTimers.clear();
14849 mFullTimers.clear();
14850 mWindowTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014851 mWifiRunningTimers.clear();
14852 mFullWifiLockTimers.clear();
Nick Pelly6ccaa542012-06-15 15:22:47 -070014853 mWifiScanTimers.clear();
Robert Greenwalta029ea12013-09-25 16:38:12 -070014854 mWifiBatchedScanTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014855 mWifiMulticastTimers.clear();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014856 mAudioTurnedOnTimers.clear();
14857 mVideoTurnedOnTimers.clear();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014858 mFlashlightTurnedOnTimers.clear();
14859 mCameraTurnedOnTimers.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014860
14861 int numUids = in.readInt();
14862 mUidStats.clear();
14863 for (int i = 0; i < numUids; i++) {
14864 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080014865 Uid u = new Uid(this, uid);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014866 u.readFromParcelLocked(mOnBatteryTimeBase, mOnBatteryScreenOffTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014867 mUidStats.append(uid, u);
14868 }
14869 }
14870
14871 public void writeToParcel(Parcel out, int flags) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014872 writeToParcelLocked(out, true, flags);
14873 }
14874
14875 public void writeToParcelWithoutUids(Parcel out, int flags) {
14876 writeToParcelLocked(out, false, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014877 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014878
14879 @SuppressWarnings("unused")
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014880 void writeToParcelLocked(Parcel out, boolean inclUids, int flags) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014881 // Need to update with current kernel wake lock counts.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080014882 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014883
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014884 // Pull the clock time. This may update the time and make a new history entry
14885 // if we had originally pulled a time before the RTC was set.
14886 long startClockTime = getStartClockTime();
14887
Joe Onoratoabded112016-02-08 16:49:39 -080014888 final long uSecUptime = mClocks.uptimeMillis() * 1000;
14889 final long uSecRealtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014890 final long batteryRealtime = mOnBatteryTimeBase.getRealtime(uSecRealtime);
14891 final long batteryScreenOffRealtime = mOnBatteryScreenOffTimeBase.getRealtime(uSecRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014892
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014893 out.writeInt(MAGIC);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014894
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070014895 writeHistory(out, true, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014896
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014897 out.writeInt(mStartCount);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014898 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014899 out.writeString(mStartPlatformVersion);
14900 out.writeString(mEndPlatformVersion);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014901 out.writeLong(mUptime);
14902 out.writeLong(mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014903 out.writeLong(mRealtime);
14904 out.writeLong(mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014905 out.writeInt(mOnBattery ? 1 : 0);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014906 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070014907 out.writeInt(mMinLearnedBatteryCapacity);
14908 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014909 mOnBatteryTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
14910 mOnBatteryScreenOffTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
14911
14912 mScreenOnTimer.writeToParcel(out, uSecRealtime);
Mike Mac2f518a2017-09-19 16:06:03 -070014913 mScreenDozeTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014914 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
14915 mScreenBrightnessTimer[i].writeToParcel(out, uSecRealtime);
14916 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070014917 mInteractiveTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070014918 mPowerSaveModeEnabledTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014919 out.writeLong(mLongestLightIdleTime);
14920 out.writeLong(mLongestFullIdleTime);
14921 mDeviceIdleModeLightTimer.writeToParcel(out, uSecRealtime);
14922 mDeviceIdleModeFullTimer.writeToParcel(out, uSecRealtime);
14923 mDeviceLightIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014924 mDeviceIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014925 mPhoneOnTimer.writeToParcel(out, uSecRealtime);
14926 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
14927 mPhoneSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
14928 }
14929 mPhoneSignalScanningTimer.writeToParcel(out, uSecRealtime);
14930 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
14931 mPhoneDataConnectionsTimer[i].writeToParcel(out, uSecRealtime);
14932 }
14933 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
14934 mNetworkByteActivityCounters[i].writeToParcel(out);
14935 mNetworkPacketActivityCounters[i].writeToParcel(out);
14936 }
14937 mMobileRadioActiveTimer.writeToParcel(out, uSecRealtime);
14938 mMobileRadioActivePerAppTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014939 mMobileRadioActiveAdjustedTime.writeToParcel(out);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014940 mMobileRadioActiveUnknownTime.writeToParcel(out);
14941 mMobileRadioActiveUnknownCount.writeToParcel(out);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014942 mWifiMulticastWakelockTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014943 mWifiOnTimer.writeToParcel(out, uSecRealtime);
14944 mGlobalWifiRunningTimer.writeToParcel(out, uSecRealtime);
14945 for (int i=0; i<NUM_WIFI_STATES; i++) {
14946 mWifiStateTimer[i].writeToParcel(out, uSecRealtime);
14947 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014948 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
14949 mWifiSupplStateTimer[i].writeToParcel(out, uSecRealtime);
14950 }
14951 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
14952 mWifiSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
14953 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014954 mWifiActiveTimer.writeToParcel(out, uSecRealtime);
14955 mWifiActivity.writeToParcel(out, 0);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014956 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14957 mGpsSignalQualityTimer[i].writeToParcel(out, uSecRealtime);
14958 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014959 mBluetoothActivity.writeToParcel(out, 0);
14960 mModemActivity.writeToParcel(out, 0);
14961 out.writeInt(mHasWifiReporting ? 1 : 0);
14962 out.writeInt(mHasBluetoothReporting ? 1 : 0);
14963 out.writeInt(mHasModemReporting ? 1 : 0);
14964
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014965 out.writeInt(mNumConnectivityChange);
14966 out.writeInt(mLoadedNumConnectivityChange);
14967 out.writeInt(mUnpluggedNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070014968 mFlashlightOnTimer.writeToParcel(out, uSecRealtime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014969 mCameraOnTimer.writeToParcel(out, uSecRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014970 mBluetoothScanTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014971 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014972 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070014973 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014974 out.writeInt(mCurrentBatteryLevel);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014975 out.writeInt(mLowDischargeAmountSinceCharge);
14976 out.writeInt(mHighDischargeAmountSinceCharge);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014977 out.writeInt(mDischargeAmountScreenOn);
14978 out.writeInt(mDischargeAmountScreenOnSinceCharge);
14979 out.writeInt(mDischargeAmountScreenOff);
14980 out.writeInt(mDischargeAmountScreenOffSinceCharge);
Mike Mac2f518a2017-09-19 16:06:03 -070014981 out.writeInt(mDischargeAmountScreenDoze);
14982 out.writeInt(mDischargeAmountScreenDozeSinceCharge);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014983 mDischargeStepTracker.writeToParcel(out);
14984 mChargeStepTracker.writeToParcel(out);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070014985 mDischargeCounter.writeToParcel(out);
14986 mDischargeScreenOffCounter.writeToParcel(out);
Mike Mac2f518a2017-09-19 16:06:03 -070014987 mDischargeScreenDozeCounter.writeToParcel(out);
Mike Ma15313c92017-11-15 17:58:21 -080014988 mDischargeLightDozeCounter.writeToParcel(out);
14989 mDischargeDeepDozeCounter.writeToParcel(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014990 out.writeLong(mLastWriteTime);
14991
Bookatz50df7112017-08-04 14:53:26 -070014992 out.writeInt(mRpmStats.size());
14993 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
14994 SamplingTimer rpmt = ent.getValue();
14995 if (rpmt != null) {
14996 out.writeInt(1);
14997 out.writeString(ent.getKey());
14998 rpmt.writeToParcel(out, uSecRealtime);
14999 } else {
15000 out.writeInt(0);
15001 }
15002 }
15003 out.writeInt(mScreenOffRpmStats.size());
15004 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
15005 SamplingTimer rpmt = ent.getValue();
15006 if (rpmt != null) {
15007 out.writeInt(1);
15008 out.writeString(ent.getKey());
15009 rpmt.writeToParcel(out, uSecRealtime);
15010 } else {
15011 out.writeInt(0);
15012 }
15013 }
15014
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015015 if (inclUids) {
15016 out.writeInt(mKernelWakelockStats.size());
15017 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
15018 SamplingTimer kwlt = ent.getValue();
15019 if (kwlt != null) {
15020 out.writeInt(1);
15021 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070015022 kwlt.writeToParcel(out, uSecRealtime);
15023 } else {
15024 out.writeInt(0);
15025 }
15026 }
15027 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070015028 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
15029 SamplingTimer timer = ent.getValue();
15030 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070015031 out.writeInt(1);
15032 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070015033 timer.writeToParcel(out, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015034 } else {
15035 out.writeInt(0);
15036 }
Evan Millarc64edde2009-04-18 12:26:32 -070015037 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015038 } else {
Bookatzba78b2b2017-10-10 11:06:33 -070015039 out.writeInt(0);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015040 out.writeInt(0);
Evan Millarc64edde2009-04-18 12:26:32 -070015041 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070015042
James Carr3a226052016-07-01 14:49:52 -070015043 out.writeInt(mKernelMemoryStats.size());
15044 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
15045 SamplingTimer kmt = mKernelMemoryStats.valueAt(i);
15046 if (kmt != null) {
15047 out.writeInt(1);
15048 out.writeLong(mKernelMemoryStats.keyAt(i));
15049 kmt.writeToParcel(out, uSecRealtime);
15050 } else {
15051 out.writeInt(0);
15052 }
15053 }
15054
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015055 if (inclUids) {
15056 int size = mUidStats.size();
15057 out.writeInt(size);
15058 for (int i = 0; i < size; i++) {
15059 out.writeInt(mUidStats.keyAt(i));
15060 Uid uid = mUidStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015061
Bookatz867c0d72017-03-07 18:23:42 -080015062 uid.writeToParcelLocked(out, uSecUptime, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015063 }
15064 } else {
15065 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015066 }
15067 }
15068
15069 public static final Parcelable.Creator<BatteryStatsImpl> CREATOR =
15070 new Parcelable.Creator<BatteryStatsImpl>() {
15071 public BatteryStatsImpl createFromParcel(Parcel in) {
15072 return new BatteryStatsImpl(in);
15073 }
15074
15075 public BatteryStatsImpl[] newArray(int size) {
15076 return new BatteryStatsImpl[size];
15077 }
15078 };
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070015079
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070015080 public void prepareForDumpLocked() {
15081 // Need to retrieve current kernel wake lock stats before printing.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080015082 pullPendingStateUpdatesLocked();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070015083
15084 // Pull the clock time. This may update the time and make a new history entry
15085 // if we had originally pulled a time before the RTC was set.
15086 getStartClockTime();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070015087 }
15088
Dianne Hackbornc51cf032014-03-02 19:08:15 -080015089 public void dumpLocked(Context context, PrintWriter pw, int flags, int reqUid, long histStart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015090 if (DEBUG) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080015091 pw.println("mOnBatteryTimeBase:");
15092 mOnBatteryTimeBase.dump(pw, " ");
15093 pw.println("mOnBatteryScreenOffTimeBase:");
15094 mOnBatteryScreenOffTimeBase.dump(pw, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015095 Printer pr = new PrintWriterPrinter(pw);
Mike Mac2f518a2017-09-19 16:06:03 -070015096 pr.println("*** Screen on timer:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015097 mScreenOnTimer.logState(pr, " ");
Mike Mac2f518a2017-09-19 16:06:03 -070015098 pr.println("*** Screen doze timer:");
15099 mScreenDozeTimer.logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070015100 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015101 pr.println("*** Screen brightness #" + i + ":");
15102 mScreenBrightnessTimer[i].logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070015103 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070015104 pr.println("*** Interactive timer:");
15105 mInteractiveTimer.logState(pr, " ");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070015106 pr.println("*** Power save mode timer:");
15107 mPowerSaveModeEnabledTimer.logState(pr, " ");
Dianne Hackborn08c47a52015-10-15 12:38:14 -070015108 pr.println("*** Device idle mode light timer:");
15109 mDeviceIdleModeLightTimer.logState(pr, " ");
15110 pr.println("*** Device idle mode full timer:");
15111 mDeviceIdleModeFullTimer.logState(pr, " ");
15112 pr.println("*** Device light idling timer:");
15113 mDeviceLightIdlingTimer.logState(pr, " ");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070015114 pr.println("*** Device idling timer:");
15115 mDeviceIdlingTimer.logState(pr, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015116 pr.println("*** Phone timer:");
15117 mPhoneOnTimer.logState(pr, " ");
Wink Saville52840902011-02-18 12:40:47 -080015118 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3251b902014-06-20 14:40:53 -070015119 pr.println("*** Phone signal strength #" + i + ":");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015120 mPhoneSignalStrengthsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070015121 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070015122 pr.println("*** Signal scanning :");
15123 mPhoneSignalScanningTimer.logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070015124 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015125 pr.println("*** Data connection type #" + i + ":");
15126 mPhoneDataConnectionsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070015127 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070015128 pr.println("*** mMobileRadioPowerState=" + mMobileRadioPowerState);
Dianne Hackborne13c4c02014-02-11 17:18:35 -080015129 pr.println("*** Mobile network active timer:");
15130 mMobileRadioActiveTimer.logState(pr, " ");
Dianne Hackborna1bd7922014-03-21 11:07:11 -070015131 pr.println("*** Mobile network active adjusted timer:");
15132 mMobileRadioActiveAdjustedTime.logState(pr, " ");
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080015133 pr.println("*** Wifi Multicast WakeLock Timer:");
15134 mWifiMulticastWakelockTimer.logState(pr, " ");
Dianne Hackborn0c820db2015-04-14 17:47:34 -070015135 pr.println("*** mWifiRadioPowerState=" + mWifiRadioPowerState);
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015136 pr.println("*** Wifi timer:");
15137 mWifiOnTimer.logState(pr, " ");
15138 pr.println("*** WifiRunning timer:");
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070015139 mGlobalWifiRunningTimer.logState(pr, " ");
Dianne Hackbornca1bf212014-02-14 14:18:36 -080015140 for (int i=0; i<NUM_WIFI_STATES; i++) {
15141 pr.println("*** Wifi state #" + i + ":");
15142 mWifiStateTimer[i].logState(pr, " ");
15143 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070015144 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
15145 pr.println("*** Wifi suppl state #" + i + ":");
15146 mWifiSupplStateTimer[i].logState(pr, " ");
15147 }
15148 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
15149 pr.println("*** Wifi signal strength #" + i + ":");
15150 mWifiSignalStrengthsTimer[i].logState(pr, " ");
15151 }
Siddharth Ray78ccaf52017-12-23 16:16:21 -080015152 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
15153 pr.println("*** GPS signal quality #" + i + ":");
15154 mGpsSignalQualityTimer[i].logState(pr, " ");
15155 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -070015156 pr.println("*** Flashlight timer:");
15157 mFlashlightOnTimer.logState(pr, " ");
Ruben Brunk6d2c3632015-05-26 17:32:16 -070015158 pr.println("*** Camera timer:");
15159 mCameraOnTimer.logState(pr, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015160 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -080015161 super.dumpLocked(context, pw, flags, reqUid, histStart);
Sudheer Shankac20379e2018-02-15 00:06:21 -080015162 pw.print("Total cpu time reads: ");
Mike Ma234d1822018-03-13 18:53:21 -070015163 pw.println(mNumSingleUidCpuTimeReads);
Sudheer Shankac20379e2018-02-15 00:06:21 -080015164 pw.print("Batched cpu time reads: ");
Mike Ma234d1822018-03-13 18:53:21 -070015165 pw.println(mNumBatchedSingleUidCpuTimeReads);
Sudheer Shankac20379e2018-02-15 00:06:21 -080015166 pw.print("Batching Duration (min): ");
15167 pw.println((mClocks.uptimeMillis() - mCpuTimeReadsTrackingStartTime) / (60 * 1000));
Mike Ma234d1822018-03-13 18:53:21 -070015168 pw.print("All UID cpu time reads since the later of device start or stats reset: ");
15169 pw.println(mNumAllUidCpuTimeReads);
15170 pw.print("UIDs removed since the later of device start or stats reset: ");
15171 pw.println(mNumUidsRemoved);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015172 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015173}